diff --git a/app/cli/cmd/workflow_run_timeline.go b/app/cli/cmd/workflow_run_timeline.go new file mode 100644 index 000000000..f525ad47a --- /dev/null +++ b/app/cli/cmd/workflow_run_timeline.go @@ -0,0 +1,411 @@ +// +// Copyright 2026 The Chainloop Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package cmd + +import ( + "fmt" + "io" + "slices" + "strings" + "time" + "unicode/utf8" + + "github.com/chainloop-dev/chainloop/app/cli/pkg/action" + "github.com/jedib0t/go-pretty/v6/text" +) + +const ( + timelineKeyAttestation = "chainloop.attestation" + // timelineMaxDetail keeps each line of the tree readable. JSON output has the full text. + timelineMaxDetail = 120 + + timelineFailed = "failed" + timelineSourceCLI = "cli" + timelineStarted = "started" + timelineSucceeded = "succeeded" +) + +// timelineNode is one line of the timeline tree +type timelineNode struct { + at string + symbol string + name string + details []string + children []*timelineNode +} + +// renderRunTimeline writes the events of a run as a tree. The root line is the attestation, +// with its start and its end. Each step is one line, and a step with more than one event +// folds its events below it. For a run in progress, progress adds the contract materials +// that are still missing, and the push that is still to come. The closing event of the +// control plane is the last line, with the policy status of the stored attestation. +func renderRunTimeline(w io.Writer, events []*action.RunEvent, progress *action.RunProgress, stored *action.PolicyEvaluationStatus, now time.Time) { + // An older CLI records no events, and the run shows as before. The closing event of the + // control plane alone is not a timeline. + if !slices.ContainsFunc(events, func(e *action.RunEvent) bool { return e.Source == timelineSourceCLI }) { + return + } + + // group the events by key, in the order of their first event + var keys []string + groups := make(map[string][]*action.RunEvent) + for _, e := range events { + if _, ok := groups[e.Key]; !ok { + keys = append(keys, e.Key) + } + groups[e.Key] = append(groups[e.Key], e) + } + + materials := make(map[string]*action.RunProgressMaterial) + if progress != nil { + for _, m := range progress.Materials { + materials[m.Name] = m + } + } + + var nodes []*timelineNode + var started, closing *action.RunEvent + reported := make(map[string]bool) + for _, key := range keys { + evs := groups[key] + switch key { + case timelineKeyAttestation: + for _, e := range evs { + if e.Status == timelineStarted { + started = e + nodes = append(nodes, timelineInit(e)) + break + } + } + // the closing event of the control plane ends the timeline + if last := evs[len(evs)-1]; last.Status != timelineStarted { + closing = last + } + default: + if m := evs[len(evs)-1].Material; m != nil { + reported[m.Name] = true + } + nodes = append(nodes, timelineStep(key, evs, materials)) + } + } + + if progress != nil { + for _, m := range progress.Materials { + if m.Requirement != action.RunMaterialNotInContract && !reported[m.Name] { + nodes = append(nodes, &timelineNode{ + symbol: text.Faint.Sprint("○"), name: "missing evidence " + timelineQuote(m.Name), + details: []string{timelineRequirement(m)}, + }) + } + } + if closing == nil { + nodes = append(nodes, &timelineNode{symbol: timelineSymbol(timelineStarted), name: "waiting for push"}) + } + } + + if closing != nil { + nodes = append(nodes, timelineEnd(closing, stored)) + } + + fmt.Fprintln(w, timelineHeader(started, events, closing, progress, now)) + writeTimelineNodes(w, nodes, "", timelineNameWidth(nodes)) +} + +// timelineHeader is the root line: the start of the attestation, and its end or how long it runs +func timelineHeader(started *action.RunEvent, events []*action.RunEvent, closing *action.RunEvent, progress *action.RunProgress, now time.Time) string { + title := "Timeline" + if progress != nil { + title = "Timeline (reported progress)" + } + + start := events[0].CreatedAt + if started != nil { + start = started.CreatedAt + } + + parts := []string{title} + if start != nil { + parts = append(parts, "started "+timelineTime(start)) + } + + switch { + case closing != nil: + end := "finished " + timelineTime(closing.CreatedAt) + if start != nil && closing.CreatedAt != nil { + end += fmt.Sprintf(" (%s)", closing.CreatedAt.Sub(*start).Round(time.Second)) + } + parts = append(parts, end, timelineStatus(closing.Status)) + case start != nil: + parts = append(parts, "running for "+now.Sub(*start).Round(time.Second).String()) + } + + if progress != nil { + parts = append(parts, fmt.Sprintf("%d of %d required provided", progress.RequiredProvided, progress.RequiredTotal)) + if s := runPolicyCountSummary(progress.AttestationPolicies); s != "" { + parts = append(parts, "attestation policies: "+s) + } + } + + return strings.Join(parts, " · ") +} + +// timelineInit is the line of the start of the attestation, with its contract and its runner +func timelineInit(e *action.RunEvent) *timelineNode { + node := &timelineNode{at: timelineTime(e.CreatedAt), symbol: timelineSymbol(timelineSucceeded), name: "initialized"} + a := e.Attestation + if a == nil { + return node + } + + if a.ContractName != "" { + contract := "contract " + a.ContractName + if a.ContractRevision > 0 { + contract += fmt.Sprintf(" rev %d", a.ContractRevision) + } + node.details = append(node.details, contract) + } + if a.RunnerType != "" { + node.details = append(node.details, a.RunnerType) + } + if a.RemoteState { + node.details = append(node.details, "remote state") + } else { + node.details = append(node.details, "local state") + } + if s := runPolicyCountSummary(a.Policies); s != "" { + node.details = append(node.details, "policies: "+s) + } + + return node +} + +// timelineEnd is the last line of the timeline. The control plane closes the timeline when +// it stores the attestation: the push and the store are one step for the user, with the +// policy status of the signed attestation and its digest. A run that ends with no store +// (reset or expiry) shows how it ended. +func timelineEnd(closing *action.RunEvent, stored *action.PolicyEvaluationStatus) *timelineNode { + node := &timelineNode{at: timelineTime(closing.CreatedAt), symbol: timelineSymbol(closing.Status), name: closing.Status} + if closing.Status == timelineSucceeded { + node.name = "pushed and stored" + node.details = append(node.details, timelinePolicyStatus(stored)...) + } + if d := timelineDigest(closing); d != "" { + node.details = append(node.details, d) + } + if closing.Message != "" { + node.details = append(node.details, timelineMessage(closing)) + } + + return node +} + +// timelinePolicyStatus is the policy result of the stored attestation. A blocked attestation +// is stored too, and the push command fails after the store. The line does not name the +// gates: when the policy evaluations are in the CAS, the stored attestation holds only +// the counts and the blocked flag, and the push output of the CI job names them. +func timelinePolicyStatus(st *action.PolicyEvaluationStatus) []string { + if st == nil { + return nil + } + + var details []string + counts := &action.RunEventPolicyCount{Evaluated: int32(st.Total), Passed: int32(st.Passed), Violated: int32(st.Violated), Skipped: int32(st.Skipped)} + if s := runPolicyCountSummary(counts); s != "" { + details = append(details, "policies: "+s) + } + if st.Blocked { + details = append(details, text.FgHiRed.Sprint("blocked by policy gates")) + } + + return details +} + +// timelineDigest is the short digest of the stored attestation. The attestation table has it in full. +func timelineDigest(e *action.RunEvent) string { + if e.Attestation == nil || e.Attestation.AttestationDigest == "" { + return "" + } + + d := e.Attestation.AttestationDigest + if algo, hex, ok := strings.Cut(d, ":"); ok && len(hex) > 12 { + return algo + ":" + hex[:12] + "…" + } + return d +} + +// timelineStep is the line of one step of evidence. A step with more than one event folds +// its events below it. +func timelineStep(key string, evs []*action.RunEvent, materials map[string]*action.RunProgressMaterial) *timelineNode { + last := evs[len(evs)-1] + // A failed add after a successful one leaves the material in the attestation, so the + // step shows the last successful add, and the failed attempts below it. The control + // plane applies the same rule to the progress (biz.BuildWorkflowRunProgress). The + // timeline needs its own copy because a finished run has no progress. + shown := last + for _, e := range slices.Backward(evs) { + if e.Status == timelineSucceeded { + shown = e + break + } + } + + name := action.RunStepName(key) + node := &timelineNode{at: timelineTime(evs[0].CreatedAt), symbol: timelineSymbol(shown.Status), name: timelineEvidenceAction(shown, name)} + + // details in order: type, value, requirement, policies + m := shown.Material + if m != nil && m.MaterialType != "" { + node.details = append(node.details, m.MaterialType) + } + if m != nil && m.Value != "" { + node.details = append(node.details, m.Value) + } + if req := materials[name]; req != nil { + node.details = append(node.details, timelineRequirement(req)) + } + if m != nil { + if s := runPolicyCountSummary(m.Policies); s != "" { + node.details = append(node.details, "policies: "+s) + } + } + + if len(evs) == 1 { + if last.Message != "" { + node.details = append(node.details, timelineMessage(last)) + } + return node + } + + var failed int + for _, e := range evs { + if e.Status == timelineFailed { + failed++ + } + node.children = append(node.children, &timelineNode{at: timelineTime(e.CreatedAt), symbol: timelineSymbol(e.Status), name: timelineMessage(e)}) + } + switch { + case failed == 1: + node.details = append(node.details, "1 failed attempt") + case failed > 1: + node.details = append(node.details, fmt.Sprintf("%d failed attempts", failed)) + } + + return node +} + +// timelineEvidenceAction names what happened to a piece of evidence +func timelineEvidenceAction(last *action.RunEvent, name string) string { + quoted := timelineQuote(name) + switch { + case last.Status == timelineFailed: + return "failed to add evidence " + quoted + case last.Material != nil && last.Material.AddedByCollector: + return "collected evidence " + quoted + default: + return "added evidence " + quoted + } +} + +func timelineQuote(name string) string { + if name == "" { + return "(no name)" + } + return "`" + name + "`" +} + +func writeTimelineNodes(w io.Writer, nodes []*timelineNode, prefix string, nameWidth int) { + for i, n := range nodes { + connector, next := "├─ ", "│ " + if i == len(nodes)-1 { + connector, next = "└─ ", " " + } + + line := fmt.Sprintf("%-8s %s %s", n.at, n.symbol, n.name) + if len(n.details) > 0 { + line = fmt.Sprintf("%-8s %s %-*s %s", n.at, n.symbol, nameWidth, n.name, strings.Join(n.details, " · ")) + } + fmt.Fprintln(w, strings.TrimRight(prefix+connector+line, " ")) + + // the events of a step do not align with the names of the steps + writeTimelineNodes(w, n.children, prefix+next, 0) + } +} + +func timelineNameWidth(nodes []*timelineNode) int { + var width int + for _, n := range nodes { + width = max(width, utf8.RuneCountInString(n.name)) + } + return width +} + +// timelineRequirement shows how the contract asks for a material +func timelineRequirement(m *action.RunProgressMaterial) string { + switch m.Requirement { + case action.RunMaterialNotInContract: + return "not in contract" + case action.RunMaterialOneOfGroup: + return "one of " + m.Group + case action.RunMaterialRequired: + return "required" + default: + return "optional" + } +} + +func timelineSymbol(status string) string { + switch status { + case timelineSucceeded: + return text.FgHiGreen.Sprint("✓") + case timelineFailed: + return text.FgHiRed.Sprint("✗") + case "canceled": + return text.FgYellow.Sprint("⊘") + default: + return text.FgYellow.Sprint("●") + } +} + +// timelineStatus names how the attestation ended +func timelineStatus(status string) string { + if status == timelineSucceeded { + return "stored" + } + return status +} + +func timelineMessage(e *action.RunEvent) string { + msg := e.Message + if msg == "" { + return e.Status + } + + msg = strings.Join(strings.Fields(msg), " ") + if utf8.RuneCountInString(msg) > timelineMaxDetail { + msg = string([]rune(msg)[:timelineMaxDetail]) + "…" + } + if e.Status == timelineFailed { + return text.FgHiRed.Sprint(msg) + } + return msg +} + +func timelineTime(t *time.Time) string { + if t == nil { + return "" + } + return t.Local().Format(time.TimeOnly) +} diff --git a/app/cli/cmd/workflow_run_timeline_test.go b/app/cli/cmd/workflow_run_timeline_test.go new file mode 100644 index 000000000..13d1a2431 --- /dev/null +++ b/app/cli/cmd/workflow_run_timeline_test.go @@ -0,0 +1,159 @@ +// +// Copyright 2026 The Chainloop Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package cmd + +import ( + "bytes" + "testing" + "time" + + "github.com/chainloop-dev/chainloop/app/cli/pkg/action" + "github.com/jedib0t/go-pretty/v6/text" + "github.com/stretchr/testify/assert" +) + +func TestRenderRunTimeline(t *testing.T) { + text.DisableColors() + t.Cleanup(text.EnableColors) + + start := time.Date(2026, 11, 30, 10, 0, 2, 0, time.Local) + at := func(d time.Duration) *time.Time { + v := start.Add(d) + return &v + } + started := &action.RunEvent{CreatedAt: at(0), Source: timelineSourceCLI, Key: timelineKeyAttestation, Status: "started", Attestation: &action.RunEventAttestation{ + ContractName: "build", ContractRevision: 3, RunnerType: "GITHUB_ACTION", Policies: &action.RunEventPolicyCount{Evaluated: 2, Passed: 2}}} + material := func(d time.Duration, name, status, msg string, policies *action.RunEventPolicyCount) *action.RunEvent { + return &action.RunEvent{CreatedAt: at(d), Source: timelineSourceCLI, Key: "chainloop.material." + name, Status: status, Message: msg, + Material: &action.RunEventMaterial{Name: name, Policies: policies}} + } + + testCases := []struct { + name string + events []*action.RunEvent + progress *action.RunProgress + stored *action.PolicyEvaluationStatus + want string + }{ + { + name: "run in progress, with a failed then repeated add and a missing material", + events: []*action.RunEvent{ + started, + material(139*time.Second, "sast-report", "succeeded", "", &action.RunEventPolicyCount{Evaluated: 2, Passed: 1, Violated: 1}), + material(188*time.Second, "sbom", "failed", "invalid CycloneDX document: missing bomFormat", nil), + material(243*time.Second, "sbom", "succeeded", "", &action.RunEventPolicyCount{Evaluated: 2, Passed: 2}), + material(328*time.Second, "build-log", "succeeded", "", nil), + }, + progress: &action.RunProgress{ + RequiredTotal: 2, RequiredProvided: 1, + AttestationPolicies: &action.RunEventPolicyCount{Evaluated: 2, Passed: 2}, + Materials: []*action.RunProgressMaterial{ + {Name: "sbom", Requirement: action.RunMaterialRequired, Status: action.RunMaterialProvided}, + {Name: "image", Requirement: action.RunMaterialRequired, Status: action.RunMaterialMissing}, + {Name: "sast-report", Requirement: action.RunMaterialOptional, Status: action.RunMaterialProvided}, + {Name: "build-log", Requirement: action.RunMaterialNotInContract, Status: action.RunMaterialProvided}, + }, + }, + want: "Timeline (reported progress) · started 10:00:02 · running for 5m43s · 1 of 2 required provided · attestation policies: 2 passed\n" + + "├─ 10:00:02 ✓ initialized contract build rev 3 · GITHUB_ACTION · local state · policies: 2 passed\n" + + "├─ 10:02:21 ✓ added evidence `sast-report` optional · policies: 1 passed, 1 violated\n" + + "├─ 10:03:10 ✓ added evidence `sbom` required · policies: 2 passed · 1 failed attempt\n" + + "│ ├─ 10:03:10 ✗ invalid CycloneDX document: missing bomFormat\n" + + "│ └─ 10:04:05 ✓ succeeded\n" + + "├─ 10:05:30 ✓ added evidence `build-log` not in contract\n" + + "├─ ○ missing evidence `image` required\n" + + "└─ ● waiting for push\n", + }, + { + name: "provided, then a rejected duplicate add", + events: []*action.RunEvent{ + started, + material(60*time.Second, "sbom", "succeeded", "", nil), + material(120*time.Second, "sbom", "failed", "material already exists in the attestation", nil), + }, + progress: &action.RunProgress{ + RequiredTotal: 1, RequiredProvided: 1, + Materials: []*action.RunProgressMaterial{ + {Name: "sbom", Requirement: action.RunMaterialRequired, Status: action.RunMaterialProvided, LastError: "material already exists in the attestation", FailedAttempts: 1}, + }, + }, + want: "Timeline (reported progress) · started 10:00:02 · running for 5m43s · 1 of 1 required provided\n" + + "├─ 10:00:02 ✓ initialized contract build rev 3 · GITHUB_ACTION · local state · policies: 2 passed\n" + + "├─ 10:01:02 ✓ added evidence `sbom` required · 1 failed attempt\n" + + "│ ├─ 10:01:02 ✓ succeeded\n" + + "│ └─ 10:02:02 ✗ material already exists in the attestation\n" + + "└─ ● waiting for push\n", + }, + { + name: "stored run", + events: []*action.RunEvent{ + started, + material(451*time.Second, "vulnerability-report", "succeeded", "", nil), + {CreatedAt: at(501 * time.Second), Key: timelineKeyAttestation, Status: timelineSucceeded, Attestation: &action.RunEventAttestation{ + AttestationDigest: "sha256:4de7a1b2c3d4e5f60718293a4b5c6d7e8f"}}, + }, + stored: &action.PolicyEvaluationStatus{Total: 3, Passed: 3}, + want: "Timeline · started 10:00:02 · finished 10:08:23 (8m21s) · stored\n" + + "├─ 10:00:02 ✓ initialized contract build rev 3 · GITHUB_ACTION · local state · policies: 2 passed\n" + + "├─ 10:07:33 ✓ added evidence `vulnerability-report`\n" + + "└─ 10:08:23 ✓ pushed and stored policies: 3 passed · sha256:4de7a1b2c3d4…\n", + }, + { + name: "stored run blocked by a gate", + events: []*action.RunEvent{ + started, + {CreatedAt: at(60 * time.Second), Key: timelineKeyAttestation, Status: "succeeded", Attestation: &action.RunEventAttestation{ + AttestationDigest: "sha256:4de7"}}, + }, + stored: &action.PolicyEvaluationStatus{Total: 3, Passed: 2, Violated: 1, Blocked: true, HasGatedViolations: true}, + want: "Timeline · started 10:00:02 · finished 10:01:02 (1m0s) · stored\n" + + "├─ 10:00:02 ✓ initialized contract build rev 3 · GITHUB_ACTION · local state · policies: 2 passed\n" + + "└─ 10:01:02 ✓ pushed and stored policies: 2 passed, 1 violated · blocked by policy gates · sha256:4de7\n", + }, + { + name: "expired run", + events: []*action.RunEvent{ + started, + {CreatedAt: at(3600 * time.Second), Key: timelineKeyAttestation, Status: "failed", Message: "expired"}, + }, + want: "Timeline · started 10:00:02 · finished 11:00:02 (1h0m0s) · failed\n" + + "├─ 10:00:02 ✓ initialized contract build rev 3 · GITHUB_ACTION · local state · policies: 2 passed\n" + + "└─ 11:00:02 ✗ failed expired\n", + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + var buf bytes.Buffer + renderRunTimeline(&buf, tc.events, tc.progress, tc.stored, start.Add(343*time.Second)) + assert.Equal(t, tc.want, buf.String()) + }) + } +} + +// A run of an older CLI has no events, or only the closing event of the control plane. It +// shows as before, with no timeline. +func TestRenderRunTimelineNoCLIEvents(t *testing.T) { + now := time.Now() + closing := &action.RunEvent{CreatedAt: &now, Source: "control_plane", Key: timelineKeyAttestation, Status: "succeeded", + Attestation: &action.RunEventAttestation{AttestationDigest: "sha256:4de7"}} + + for _, events := range [][]*action.RunEvent{nil, {closing}} { + var buf bytes.Buffer + renderRunTimeline(&buf, events, nil, nil, now) + assert.Empty(t, buf.String()) + } +} diff --git a/app/cli/cmd/workflow_workflow_run_describe.go b/app/cli/cmd/workflow_workflow_run_describe.go index 45c4d7486..87e5fdbb2 100644 --- a/app/cli/cmd/workflow_workflow_run_describe.go +++ b/app/cli/cmd/workflow_workflow_run_describe.go @@ -134,8 +134,15 @@ func workflowRunDescribeTableOutput(run *action.WorkflowRunItemFull) error { gt.AppendRow(table.Row{"Policy Status", wr.PolicyStatus}) gt.AppendRow(table.Row{"Runner Link", wr.RunURL}) + if run.Progress != nil { + gt.Render() + renderRunTimeline(os.Stdout, run.Events, run.Progress, nil, time.Now()) + return nil + } + if run.WorkflowRun.FinishedAt == nil { gt.Render() + renderRunTimeline(os.Stdout, run.Events, nil, nil, time.Now()) logger.Info().Msg("the attestation crafting process is in progress, it has not been received yet") return nil } @@ -143,6 +150,7 @@ func workflowRunDescribeTableOutput(run *action.WorkflowRunItemFull) error { att := run.Attestation if att == nil { gt.Render() + renderRunTimeline(os.Stdout, run.Events, nil, nil, time.Now()) logger.Warn().Msg("there was an issue retrieving the attestation") return nil } @@ -175,10 +183,32 @@ func workflowRunDescribeTableOutput(run *action.WorkflowRunItemFull) error { gt.Render() predicateV1Table(att) + // The timeline is history: the signed attestation above is the source of truth + renderRunTimeline(os.Stdout, run.Events, nil, att.PolicyEvaluationStatus, time.Now()) logger.Info().Msg("you can use the flag \"--output statement\" to see the full in-toto statement") return nil } +// runPolicyCountSummary returns for example "2 passed, 1 violated", or an empty string with no evaluations +func runPolicyCountSummary(c *action.RunEventPolicyCount) string { + if c == nil || c.Evaluated == 0 { + return "" + } + + parts := make([]string, 0, 3) + if c.Passed > 0 { + parts = append(parts, fmt.Sprintf("%d passed", c.Passed)) + } + if c.Violated > 0 { + parts = append(parts, fmt.Sprintf("%d violated", c.Violated)) + } + if c.Skipped > 0 { + parts = append(parts, fmt.Sprintf("%d skipped", c.Skipped)) + } + + return strings.Join(parts, ", ") +} + // appendPolicyStrategyRows adds the policy enforcement rows of a run. // Only show the strategy when it is enforced. Showing "ADVISORY" is misleading // when individual policies are configured as gates. diff --git a/app/cli/pkg/action/attestation_add.go b/app/cli/pkg/action/attestation_add.go index a17976559..c3dea5fb8 100644 --- a/app/cli/pkg/action/attestation_add.go +++ b/app/cli/pkg/action/attestation_add.go @@ -147,6 +147,40 @@ func (action *AttestationAdd) Run(ctx context.Context, attestationID, materialNa return nil, err } + // Progress events are best effort, they never change the result of the add + events := newRunEventRecorderFromState(action.CPConnection, crafter.CraftingState.CraftingState, action.Logger) + results, err := action.addMaterial(ctx, crafter, attestationID, materialName, materialValue, materialType, annotations, policyInputFiles, runtimeInputs) + if err != nil { + _ = events.Record(ctx, materialFailedEvent(crafter, materialName, materialType, materialValue, err)) + return nil, err + } + + recordMaterialEvents(ctx, events, crafter, materialName, materialType, materialValue, results) + + return results, nil +} + +// recordMaterialEvents records the events of a successful add. A large archive records one +// summary event, so that it does not use up the events of the run. An archive add also records +// the EVIDENCE material that stores the archive itself. +func recordMaterialEvents(ctx context.Context, events *runEventRecorder, c *crafter.Crafter, materialName, materialType, materialValue string, results []*AttestationStatusMaterial) { + if len(results) > runEventMaxArchiveMaterials { + _ = events.Record(ctx, archiveAddedEvent(c, materialName, materialType, materialValue, results)) + } else { + for _, r := range results { + _ = events.Record(ctx, materialAddedEvent(c, r, false)) + } + } + + if format, err := shouldExplode(materialType, materialValue); err == nil && format != materials.ArchiveNone { + if archive := archiveEvidenceMaterial(c, results); archive != nil { + _ = events.Record(ctx, materialAddedEvent(c, archive, false)) + } + } +} + +// addMaterial adds the material, or the materials of an archive, to the loaded crafting state +func (action *AttestationAdd) addMaterial(ctx context.Context, crafter *crafter.Crafter, attestationID, materialName, materialValue, materialType string, annotations map[string]string, policyInputFiles []*PolicyInputFromFile, runtimeInputs *policies.RuntimeInputs) ([]*AttestationStatusMaterial, error) { // Default to inline CASBackend and override if we are not in dry-run mode casBackend := &casclient.CASBackend{ Name: "not-set", diff --git a/app/cli/pkg/action/attestation_init.go b/app/cli/pkg/action/attestation_init.go index 1c0144447..d895f0636 100644 --- a/app/cli/pkg/action/attestation_init.go +++ b/app/cli/pkg/action/attestation_init.go @@ -389,6 +389,14 @@ func (action *AttestationInit) Run(ctx context.Context, opts *AttestationInitRun return "", fmt.Errorf("evaluating attestation policies: %w", err) } + // Progress events are best effort, they never stop the attestation. The start of the + // timeline holds the init policy results, then come the materials that collectors added. + events := newRunEventRecorder(action.CPConnection, attestationID, action.Logger) + _ = events.Record(ctx, attestationStartedEvent(action.c.CraftingState.CraftingState, action.useRemoteState, action.CLIVersion)) + for _, ev := range collectedMaterialEvents(action.c, action.Logger) { + _ = events.Record(ctx, ev) + } + return attestationID, nil } diff --git a/app/cli/pkg/action/runevents.go b/app/cli/pkg/action/runevents.go new file mode 100644 index 000000000..3649bc986 --- /dev/null +++ b/app/cli/pkg/action/runevents.go @@ -0,0 +1,384 @@ +// +// Copyright 2026 The Chainloop Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package action + +import ( + "context" + "fmt" + "os" + "path/filepath" + "slices" + "strconv" + "strings" + "time" + "unicode/utf8" + + pb "github.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1" + schemaapi "github.com/chainloop-dev/chainloop/app/controlplane/api/workflowcontract/v1" + "github.com/chainloop-dev/chainloop/pkg/attestation/crafter" + api "github.com/chainloop-dev/chainloop/pkg/attestation/crafter/api/attestation/v1" + "github.com/chainloop-dev/chainloop/pkg/attestation/crafter/materials" + + "github.com/rs/zerolog" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +const ( + // runEventTimeout bounds each call, so that progress never slows down the attestation much + runEventTimeout = 2 * time.Second + // runEventMaxMessageBytes is the limit of the control plane for an event message, + // see the max_bytes rule of WorkflowRunEvent.message in workflow_run.proto + runEventMaxMessageBytes = 1024 + // runEventMaxValueChars is the limit of the control plane for a material value, + // see the max_len rule of WorkflowRunEvent.MaterialAttributes.value in workflow_run.proto + runEventMaxValueChars = 256 + // runEventMaxPolicyNames is the limit of the control plane for a list of policy names, + // see the max_items rules of PolicyCounts in workflow_run.proto + runEventMaxPolicyNames = 100 + // runEventMaxExpectedMaterials is the limit of the control plane for the list of expected + // materials, see the max_items rule of AttestationAttributes.expected_materials + runEventMaxExpectedMaterials = 1000 + // runEventMaxArchiveMaterials is the number of materials of an archive add above which + // the add records one summary event instead of one event for each material + runEventMaxArchiveMaterials = 20 + + runEventKeyPrefix = "chainloop." + runEventKeyAttestation = runEventKeyPrefix + "attestation" + runEventKeyMaterial = runEventKeyPrefix + "material" + runEventKeyMaterialPrefix = runEventKeyMaterial + "." +) + +// runEventRecorder sends progress events of an attestation to the control plane. +// Events are informational only: callers must never stop the attestation on its error. +// It turns itself off for the rest of the command when the control plane does not know the call. +type runEventRecorder struct { + client pb.AttestationServiceClient + runID string + logger zerolog.Logger + timeout time.Duration + disabled bool +} + +// newRunEventRecorder returns a recorder for the run. An empty run ID, for example +// in a dry run, returns a recorder that sends nothing. +func newRunEventRecorder(conn *grpc.ClientConn, runID string, logger zerolog.Logger) *runEventRecorder { + r := &runEventRecorder{runID: runID, logger: logger, timeout: runEventTimeout, disabled: runID == "" || conn == nil} + if conn != nil { + r.client = pb.NewAttestationServiceClient(conn) + } + + return r +} + +// newRunEventRecorderFromState returns a recorder for the run of the crafting state +func newRunEventRecorderFromState(conn *grpc.ClientConn, state *api.CraftingState, logger zerolog.Logger) *runEventRecorder { + var runID string + if !state.GetDryRun() { + runID = state.GetAttestation().GetWorkflow().GetWorkflowRunId() + } + + return newRunEventRecorder(conn, runID, logger) +} + +// Record sends the event. It returns the error of the call, so that a caller that must +// tell the user can do it, but it already logged it. +func (r *runEventRecorder) Record(ctx context.Context, event *pb.WorkflowRunEvent) error { + if r == nil || r.disabled || event == nil { + return nil + } + + event.Message = truncateBytes(event.GetMessage(), runEventMaxMessageBytes) + if m := event.GetMaterial(); m != nil { + m.Value = truncateChars(m.GetValue(), runEventMaxValueChars) + capPolicyNames(m.GetPolicies()) + } + if a := event.GetAttestation(); a != nil { + capPolicyNames(a.GetPolicies()) + } + + ctx, cancel := context.WithTimeout(ctx, r.timeout) + defer cancel() + + _, err := r.client.RecordEvent(ctx, &pb.AttestationServiceRecordEventRequest{WorkflowRunId: r.runID, Event: event}) + if err == nil { + return nil + } + + switch status.Code(err) { + case codes.Unimplemented: + // an older control plane, stop sending for the rest of the command + r.disabled = true + r.logger.Debug().Err(err).Msg("the control plane does not support run events") + case codes.InvalidArgument, codes.FailedPrecondition: + r.logger.Warn().Err(err).Str("key", event.GetKey()).Msg("the control plane rejected a progress event") + default: + r.logger.Debug().Err(err).Str("key", event.GetKey()).Msg("failed to record a progress event") + } + + return err +} + +// attestationStartedEvent opens the timeline of the run. It is sent at the end of init, +// so it holds the results of the attestation policies evaluated at init. +func attestationStartedEvent(state *api.CraftingState, remoteState bool, cliVersion string) *pb.WorkflowRunEvent { + att := state.GetAttestation() + var revision int32 + if r, err := strconv.ParseInt(att.GetWorkflow().GetSchemaRevision(), 10, 32); err == nil { + revision = int32(r) + } + + return &pb.WorkflowRunEvent{ + Type: pb.WorkflowRunEvent_TYPE_ATTESTATION, + Key: runEventKeyAttestation, + Status: pb.WorkflowRunEvent_STATUS_STARTED, + Attributes: &pb.WorkflowRunEvent_Attestation{Attestation: &pb.WorkflowRunEvent_AttestationAttributes{ + ContractName: att.GetWorkflow().GetContractName(), + ContractRevision: revision, + RunnerType: att.GetRunnerType().String(), + RemoteState: remoteState, + CliVersion: cliVersion, + Policies: policyCounts(state, ""), + ExpectedMaterials: expectedMaterials(state), + }}, + } +} + +// expectedMaterials returns the materials that the attestation expects, as init resolved +// them: the contract and its policy groups, with interpolated names. The control plane +// builds the progress of the run from them. +func expectedMaterials(state *api.CraftingState) []*pb.WorkflowRunEvent_ExpectedMaterial { + materials := state.GetMaterials() + if len(materials) > runEventMaxExpectedMaterials { + materials = materials[:runEventMaxExpectedMaterials] + } + + out := make([]*pb.WorkflowRunEvent_ExpectedMaterial, 0, len(materials)) + for _, m := range materials { + out = append(out, &pb.WorkflowRunEvent_ExpectedMaterial{ + Name: m.GetName(), MaterialType: m.GetType().String(), Optional: m.GetOptional(), Group: m.GetGroup(), + }) + } + + return out +} + +// materialAddedEvent describes a material in the crafting state. It holds only the +// name, the type, the value that attestation status shows, the digest, and policy counts. +func materialAddedEvent(c *crafter.Crafter, m *AttestationStatusMaterial, addedByCollector bool) *pb.WorkflowRunEvent { + name := m.Name + return &pb.WorkflowRunEvent{ + Type: pb.WorkflowRunEvent_TYPE_MATERIAL, + Key: runEventKeyMaterialPrefix + name, + Status: pb.WorkflowRunEvent_STATUS_SUCCEEDED, + Attributes: &pb.WorkflowRunEvent_Material{Material: &pb.WorkflowRunEvent_MaterialAttributes{ + Name: name, + MaterialType: m.Type, + Value: m.Value, + Digest: m.Hash, + InContract: c.IsMaterialInContract(name), + AddedByCollector: addedByCollector, + Policies: policyCounts(c.CraftingState.CraftingState, name), + }}, + } +} + +// materialFailedEvent records a failed add, with the error text +func materialFailedEvent(c *crafter.Crafter, name, materialType, value string, addErr error) *pb.WorkflowRunEvent { + key := runEventKeyMaterialPrefix + name + if name == "" { + // the name is generated on add, so a failed add with no name has none + key = runEventKeyMaterial + } + + return &pb.WorkflowRunEvent{ + Type: pb.WorkflowRunEvent_TYPE_MATERIAL, + Key: key, + Status: pb.WorkflowRunEvent_STATUS_FAILED, + Message: addErr.Error(), + Attributes: &pb.WorkflowRunEvent_Material{Material: &pb.WorkflowRunEvent_MaterialAttributes{ + Name: name, + MaterialType: materialType, + Value: displayValue(value), + InContract: name != "" && c.IsMaterialInContract(name), + }}, + } +} + +// archiveAddedEvent summarizes an add that expanded an archive into many materials. +// It has the archive file name as value, the sum of the policy counts of the materials, +// and a message with the number of materials. +func archiveAddedEvent(c *crafter.Crafter, name, materialType, archivePath string, results []*AttestationStatusMaterial) *pb.WorkflowRunEvent { + value := displayValue(archivePath) + if name == "" { + // with no --name, the archive file name names the step + name = filepath.Base(archivePath) + for _, ext := range []string{".tar.gz", ".tgz", ".tar", ".zip"} { + if trimmed, ok := strings.CutSuffix(name, ext); ok { + name = trimmed + break + } + } + } + + counts := &pb.WorkflowRunEvent_PolicyCounts{} + for _, r := range results { + pc := policyCounts(c.CraftingState.CraftingState, r.Name) + counts.Evaluated += pc.GetEvaluated() + counts.Passed += pc.GetPassed() + counts.Violated += pc.GetViolated() + counts.Skipped += pc.GetSkipped() + counts.ViolatedPolicies = append(counts.ViolatedPolicies, pc.GetViolatedPolicies()...) + } + slices.Sort(counts.ViolatedPolicies) + counts.ViolatedPolicies = slices.Compact(counts.ViolatedPolicies) + + return &pb.WorkflowRunEvent{ + Type: pb.WorkflowRunEvent_TYPE_MATERIAL, + Key: runEventKeyMaterialPrefix + name, + Status: pb.WorkflowRunEvent_STATUS_SUCCEEDED, + Message: fmt.Sprintf("%d materials from the archive", len(results)), + Attributes: &pb.WorkflowRunEvent_Material{Material: &pb.WorkflowRunEvent_MaterialAttributes{ + Name: name, + MaterialType: materialType, + Value: value, + InContract: c.IsMaterialInContract(name), + Policies: counts, + }}, + } +} + +// archiveEvidenceMaterial returns the EVIDENCE material that an archive add stores for the +// archive itself, or nil. The expanded materials and the archive reference each other. +func archiveEvidenceMaterial(c *crafter.Crafter, results []*AttestationStatusMaterial) *AttestationStatusMaterial { + if len(results) == 0 { + return nil + } + + state := c.CraftingState.GetAttestation().GetMaterials() + first := results[0].Name + refs := strings.Split(state[first].GetAnnotations()[materials.AnnotationMaterialReferences], ",") + for _, ref := range refs { + m, ok := state[ref] + if !ok || m.GetMaterialType() != schemaapi.CraftingSchema_Material_EVIDENCE { + continue + } + + back := strings.Split(m.GetAnnotations()[materials.AnnotationMaterialReferences], ",") + if !slices.Contains(back, first) { + continue + } + + res, err := attMaterialToAction(m) + if err != nil { + return nil + } + return res + } + + return nil +} + +// collectedMaterialEvents describe the materials in the state, which collectors added at init +func collectedMaterialEvents(c *crafter.Crafter, logger zerolog.Logger) []*pb.WorkflowRunEvent { + materials := c.CraftingState.GetAttestation().GetMaterials() + events := make([]*pb.WorkflowRunEvent, 0, len(materials)) + for _, m := range materials { + res, err := attMaterialToAction(m) + if err != nil { + logger.Debug().Err(err).Str("material", m.GetId()).Msg("skipping the progress event of a collected material") + continue + } + events = append(events, materialAddedEvent(c, res, true)) + } + + return events +} + +// policyCounts counts the policy evaluations of a material, or of the attestation when +// materialName is empty. A violation that an assessment suppresses does not count. +func policyCounts(state *api.CraftingState, materialName string) *pb.WorkflowRunEvent_PolicyCounts { + counts := &pb.WorkflowRunEvent_PolicyCounts{} + for _, ev := range state.GetAttestation().GetPolicyEvaluations() { + if ev.GetMaterialName() != materialName { + continue + } + + counts.Evaluated++ + switch { + case ev.GetSkipped(): + counts.Skipped++ + case hasUnsuppressedViolation(ev): + counts.Violated++ + counts.ViolatedPolicies = append(counts.ViolatedPolicies, ev.GetName()) + default: + counts.Passed++ + } + } + + return counts +} + +func hasUnsuppressedViolation(ev *api.PolicyEvaluation) bool { + for _, v := range ev.GetViolations() { + if !v.GetSuppress() { + return true + } + } + + return false +} + +// displayValue returns the file name of a path, or the value itself, as attestation status shows it +func displayValue(value string) string { + if fi, err := os.Stat(value); err == nil && !fi.IsDir() { + return filepath.Base(value) + } + + return value +} + +// capPolicyNames keeps the first violated policy names that the control plane accepts. +// The counts stay complete. +func capPolicyNames(c *pb.WorkflowRunEvent_PolicyCounts) { + if c != nil && len(c.ViolatedPolicies) > runEventMaxPolicyNames { + c.ViolatedPolicies = c.ViolatedPolicies[:runEventMaxPolicyNames] + } +} + +// truncateBytes cuts s to at most n bytes without splitting a UTF-8 character +func truncateBytes(s string, n int) string { + if len(s) <= n { + return s + } + + cut := s[:n] + for len(cut) > 0 && !utf8.ValidString(cut) { + cut = cut[:len(cut)-1] + } + + return cut +} + +// truncateChars cuts s to at most n characters +func truncateChars(s string, n int) string { + if utf8.RuneCountInString(s) <= n { + return s + } + + return string([]rune(s)[:n]) +} diff --git a/app/cli/pkg/action/runevents_compat_test.go b/app/cli/pkg/action/runevents_compat_test.go new file mode 100644 index 000000000..9dad7e2d1 --- /dev/null +++ b/app/cli/pkg/action/runevents_compat_test.go @@ -0,0 +1,96 @@ +// +// Copyright 2026 The Chainloop Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package action + +import ( + "context" + "path/filepath" + "testing" + + pb "github.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1" + "github.com/rs/zerolog" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// withoutMethods returns a copy of the service description with no handler for the given +// methods, as an older control plane that does not know them. +func withoutMethods(desc grpc.ServiceDesc, names ...string) grpc.ServiceDesc { + drop := make(map[string]bool, len(names)) + for _, n := range names { + drop[n] = true + } + + methods := make([]grpc.MethodDesc, 0, len(desc.Methods)) + for _, m := range desc.Methods { + if !drop[m.MethodName] { + methods = append(methods, m) + } + } + desc.Methods = methods + + return desc +} + +// A new CLI against an older control plane never fails or panics (R-002, R-004) +func TestRunEventsAgainstOlderControlPlane(t *testing.T) { + attSvc := &fakeEventsControlPlane{} + runSvc := &fakeRunViewServer{status: pb.RunStatus_RUN_STATUS_INITIALIZED} + + conn := newBufConn(t, func(s *grpc.Server) { + attDesc := withoutMethods(pb.AttestationService_ServiceDesc, "RecordEvent") + s.RegisterService(&attDesc, attSvc) + runDesc := withoutMethods(pb.WorkflowRunService_ServiceDesc, "GetProgress") + s.RegisterService(&runDesc, runSvc) + }) + + t.Run("the recorder gets Unimplemented and turns off", func(t *testing.T) { + r := newRunEventRecorder(conn, testRunID, zerolog.Nop()) + err := r.Record(context.Background(), testEvent()) + assert.Equal(t, codes.Unimplemented, status.Code(err)) + assert.NoError(t, r.Record(context.Background(), testEvent()), "no more calls after Unimplemented") + }) + + t.Run("an add completes as before", func(t *testing.T) { + statePath := filepath.Join(t.TempDir(), "state.json") + newLocalCrafter(t, conn, statePath) + + add, err := NewAttestationAdd(&AttestationAddOpts{ + ActionsOpts: &ActionsOpts{CPConnection: conn, Logger: zerolog.Nop()}, + LocalStatePath: statePath, + }) + require.NoError(t, err) + + res, err := add.Run(context.Background(), "", "build-ref", "commit-1234", "", nil, nil, nil) + require.NoError(t, err) + require.Len(t, res, 1) + assert.Equal(t, "commit-1234", res[0].Value) + }) + + t.Run("describe shows the run as before", func(t *testing.T) { + got, err := NewWorkflowRunDescribe(&ActionsOpts{CPConnection: conn, Logger: zerolog.Nop()}). + Run(context.Background(), &WorkflowRunDescribeOpts{RunID: testRunID}) + require.NoError(t, err) + assert.Equal(t, testRunID, got.WorkflowRun.ID) + assert.Nil(t, got.Events) + assert.Nil(t, got.Progress) + }) + + assert.Empty(t, attSvc.received(), "the older control plane never got an event") +} diff --git a/app/cli/pkg/action/runevents_test.go b/app/cli/pkg/action/runevents_test.go new file mode 100644 index 000000000..4cb188e11 --- /dev/null +++ b/app/cli/pkg/action/runevents_test.go @@ -0,0 +1,537 @@ +// +// Copyright 2026 The Chainloop Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package action + +import ( + "context" + "fmt" + "net" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + pb "github.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1" + schemaapi "github.com/chainloop-dev/chainloop/app/controlplane/api/workflowcontract/v1" + "github.com/chainloop-dev/chainloop/pkg/attestation/crafter" + api "github.com/chainloop-dev/chainloop/pkg/attestation/crafter/api/attestation/v1" + "github.com/chainloop-dev/chainloop/pkg/attestation/crafter/runners" + "github.com/chainloop-dev/chainloop/pkg/attestation/crafter/statemanager/filesystem" + "github.com/rs/zerolog" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" + "google.golang.org/grpc/test/bufconn" + "google.golang.org/protobuf/encoding/protojson" +) + +const ( + testSBOM = "sbom" + testImage = "image" + testSBOMKind = "SBOM_CYCLONEDX_JSON" + testSBOMKey = "chainloop.material.sbom" + testAttKey = "chainloop.attestation" + testSBOMFile = "sbom.json" + testAttGate = "att-gate" + testBad = "bad" + testAtt = "att" + testCommit = "commit-1234" + testSBOMGate = "sbom-gate" + testLicenses = "cdx-licenses" + testSBOMs = "sboms" + testCDX = "cdx" + testInvalid = "invalid CycloneDX document" +) + +const testRunID = "4f8d2b7e-8c1b-4b1e-9f3a-2a6f1b2c3d4e" + +// fakeEventsControlPlane records the events it receives and answers with a configured error +type fakeEventsControlPlane struct { + pb.UnimplementedAttestationServiceServer + mu sync.Mutex + events []*pb.AttestationServiceRecordEventRequest + err error + delay time.Duration +} + +func (f *fakeEventsControlPlane) RecordEvent(ctx context.Context, req *pb.AttestationServiceRecordEventRequest) (*pb.AttestationServiceRecordEventResponse, error) { + if f.delay > 0 { + select { + case <-time.After(f.delay): + case <-ctx.Done(): + return nil, ctx.Err() + } + } + + f.mu.Lock() + defer f.mu.Unlock() + f.events = append(f.events, req) + if f.err != nil { + return nil, f.err + } + + return &pb.AttestationServiceRecordEventResponse{}, nil +} + +// GetUploadCreds answers with an inline backend, so that an add stores the material in the attestation +func (f *fakeEventsControlPlane) GetUploadCreds(context.Context, *pb.AttestationServiceGetUploadCredsRequest) (*pb.AttestationServiceGetUploadCredsResponse, error) { + return &pb.AttestationServiceGetUploadCredsResponse{ + Result: &pb.AttestationServiceGetUploadCredsResponse_Result{Backend: &pb.CASBackendItem{Name: "inline", Provider: "INLINE", IsInline: true}}, + }, nil +} + +func (f *fakeEventsControlPlane) received() []*pb.AttestationServiceRecordEventRequest { + f.mu.Lock() + defer f.mu.Unlock() + return append([]*pb.AttestationServiceRecordEventRequest(nil), f.events...) +} + +// newBufConn serves the registered services in process and returns a client connection +func newBufConn(t *testing.T, register func(*grpc.Server)) *grpc.ClientConn { + t.Helper() + + l := bufconn.Listen(1 << 20) + srv := grpc.NewServer() + register(srv) + go func() { _ = srv.Serve(l) }() + + conn, err := grpc.NewClient("passthrough:///bufnet", + grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return l.DialContext(ctx) }), + grpc.WithTransportCredentials(insecure.NewCredentials()), + ) + require.NoError(t, err) + + t.Cleanup(func() { + conn.Close() + srv.Stop() + }) + + return conn +} + +func newFakeEventsConn(t *testing.T, fake *fakeEventsControlPlane) *grpc.ClientConn { + return newBufConn(t, func(s *grpc.Server) { pb.RegisterAttestationServiceServer(s, fake) }) +} + +func testEvent() *pb.WorkflowRunEvent { + return &pb.WorkflowRunEvent{ + Type: pb.WorkflowRunEvent_TYPE_MATERIAL, + Key: testSBOMKey, + Status: pb.WorkflowRunEvent_STATUS_SUCCEEDED, + } +} + +// Each answer of the control plane, as in the table of plan step 06 +func TestRunEventRecorderAnswers(t *testing.T) { + testCases := []struct { + name string + err error + // expected code returned by Record, codes.OK for no error + wantCode codes.Code + // whether a second event is still sent + wantSecondSent bool + }{ + {name: "accepted", wantCode: codes.OK, wantSecondSent: true}, + {name: "older control plane", err: status.Error(codes.Unimplemented, "unknown method"), wantCode: codes.Unimplemented, wantSecondSent: false}, + {name: "rejected event", err: status.Error(codes.InvalidArgument, "bad key"), wantCode: codes.InvalidArgument, wantSecondSent: true}, + {name: "run not in progress", err: status.Error(codes.FailedPrecondition, "not in progress"), wantCode: codes.FailedPrecondition, wantSecondSent: true}, + {name: "network error", err: status.Error(codes.Unavailable, "down"), wantCode: codes.Unavailable, wantSecondSent: true}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + fake := &fakeEventsControlPlane{err: tc.err} + r := newRunEventRecorder(newFakeEventsConn(t, fake), testRunID, zerolog.Nop()) + + err := r.Record(context.Background(), testEvent()) + assert.Equal(t, tc.wantCode, status.Code(err)) + + // a second call after the first answer + err = r.Record(context.Background(), testEvent()) + if tc.wantSecondSent { + assert.Len(t, fake.received(), 2) + assert.Equal(t, tc.wantCode, status.Code(err)) + } else { + assert.Len(t, fake.received(), 1, "the recorder turns off for the rest of the command") + assert.NoError(t, err) + } + }) + } +} + +func TestRunEventRecorderTimeout(t *testing.T) { + fake := &fakeEventsControlPlane{delay: time.Second} + r := newRunEventRecorder(newFakeEventsConn(t, fake), testRunID, zerolog.Nop()) + r.timeout = 50 * time.Millisecond + + start := time.Now() + err := r.Record(context.Background(), testEvent()) + assert.Equal(t, codes.DeadlineExceeded, status.Code(err)) + assert.Less(t, time.Since(start), 500*time.Millisecond) +} + +func TestRunEventRecorderDefaultTimeout(t *testing.T) { + r := newRunEventRecorder(nil, testRunID, zerolog.Nop()) + assert.Equal(t, 2*time.Second, r.timeout) +} + +func TestRunEventRecorderSendsNothingWithoutRun(t *testing.T) { + fake := &fakeEventsControlPlane{} + conn := newFakeEventsConn(t, fake) + + // a dry run has no run ID + require.NoError(t, newRunEventRecorder(conn, "", zerolog.Nop()).Record(context.Background(), testEvent())) + // a nil recorder is safe + var nilRecorder *runEventRecorder + require.NoError(t, nilRecorder.Record(context.Background(), testEvent())) + + assert.Empty(t, fake.received()) +} + +func TestRunEventRecorderLimits(t *testing.T) { + fake := &fakeEventsControlPlane{} + r := newRunEventRecorder(newFakeEventsConn(t, fake), testRunID, zerolog.Nop()) + + ev := testEvent() + ev.Status = pb.WorkflowRunEvent_STATUS_FAILED + ev.Message = strings.Repeat("é", 1000) // 2000 bytes + ev.Attributes = &pb.WorkflowRunEvent_Material{Material: &pb.WorkflowRunEvent_MaterialAttributes{ + Name: testSBOM, Value: strings.Repeat("v", 300), + }} + require.NoError(t, r.Record(context.Background(), ev)) + + got := fake.received() + require.Len(t, got, 1) + assert.Equal(t, testRunID, got[0].GetWorkflowRunId()) + msg := got[0].GetEvent().GetMessage() + assert.LessOrEqual(t, len(msg), 1024) + assert.Equal(t, strings.Repeat("é", 512), msg, "the cut keeps whole characters") + assert.Len(t, got[0].GetEvent().GetMaterial().GetValue(), 256) +} + +// An archive add records one event for each material up to 20 materials, and one summary +// event above. Both record the EVIDENCE material that stores the archive itself. +func TestAttestationAddArchiveEvents(t *testing.T) { + sbom, err := os.ReadFile("../../../../pkg/attestation/crafter/materials/testdata/sbom.cyclonedx-1.5.json") + require.NoError(t, err) + + testCases := []struct { + name string + entries int + wantEvents int + wantSummary bool + }{ + {name: "small archive", entries: 3, wantEvents: 3 + 1}, + {name: "archive at the limit", entries: 20, wantEvents: 20 + 1}, + {name: "archive above the limit", entries: 25, wantEvents: 1 + 1, wantSummary: true}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + fake := &fakeEventsControlPlane{} + conn := newFakeEventsConn(t, fake) + statePath := filepath.Join(t.TempDir(), "state.json") + newLocalCrafter(t, conn, statePath) + + files := make(map[string]string, tc.entries) + for i := range tc.entries { + files[fmt.Sprintf("sbom-%02d.json", i)] = string(sbom) + } + zipPath := filepath.Join(t.TempDir(), "sboms.zip") + writeZipWithFiles(t, zipPath, files) + + add, err := NewAttestationAdd(&AttestationAddOpts{ + ActionsOpts: &ActionsOpts{CPConnection: conn, Logger: zerolog.Nop()}, + LocalStatePath: statePath, + }) + require.NoError(t, err) + + res, err := add.Run(context.Background(), "", testSBOMs, zipPath, testSBOMKind, nil, nil, nil) + require.NoError(t, err) + require.Len(t, res, tc.entries) + + got := fake.received() + require.Len(t, got, tc.wantEvents) + + // the archive event comes last, for the EVIDENCE material of the archive + archive := got[len(got)-1].GetEvent() + assert.Equal(t, "chainloop.material.sboms-archive", archive.GetKey()) + assert.Equal(t, "EVIDENCE", archive.GetMaterial().GetMaterialType()) + assert.Empty(t, archive.GetMessage()) + + first := got[0].GetEvent() + if tc.wantSummary { + assert.Equal(t, "chainloop.material.sboms", first.GetKey()) + assert.Equal(t, fmt.Sprintf("%d materials from the archive", tc.entries), first.GetMessage()) + return + } + assert.Empty(t, first.GetMessage()) + assert.Equal(t, testSBOMKind, first.GetMaterial().GetMaterialType()) + }) + } +} + +// A large archive add records one summary event, with the sum of the policy counts +func TestArchiveAddedEvent(t *testing.T) { + conn := newFakeEventsConn(t, &fakeEventsControlPlane{}) + c := newLocalCrafter(t, conn, filepath.Join(t.TempDir(), "state.json")) + violation := []*api.PolicyEvaluation_Violation{{Message: testBad}} + c.CraftingState.Attestation.PolicyEvaluations = []*api.PolicyEvaluation{ + {Name: "cdx-fresh", MaterialName: "sbom-1"}, + {Name: testLicenses, MaterialName: "sbom-2", Violations: violation}, + {Name: testLicenses, MaterialName: "sbom-3", Violations: violation}, + } + + results := make([]*AttestationStatusMaterial, 0, 25) + for i := range 25 { + results = append(results, &AttestationStatusMaterial{Material: &Material{Name: fmt.Sprintf("sbom-%d", i)}}) + } + + testCases := []struct { + name string + flagName string + wantKey string + }{ + {name: "with --name", flagName: testSBOMs, wantKey: "chainloop.material." + testSBOMs}, + {name: "with no --name, the archive file name", wantKey: "chainloop.material.bundle"}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + ev := archiveAddedEvent(c, tc.flagName, testSBOMKind, "/tmp/out/bundle.zip", results) + + assert.Equal(t, tc.wantKey, ev.GetKey()) + assert.Equal(t, pb.WorkflowRunEvent_STATUS_SUCCEEDED, ev.GetStatus()) + assert.Equal(t, "25 materials from the archive", ev.GetMessage()) + m := ev.GetMaterial() + assert.Equal(t, "/tmp/out/bundle.zip", m.GetValue(), "the path does not exist, so the value is kept") + assert.Equal(t, testSBOMKind, m.GetMaterialType()) + assert.Equal(t, int32(3), m.GetPolicies().GetEvaluated()) + assert.Equal(t, int32(1), m.GetPolicies().GetPassed()) + assert.Equal(t, int32(2), m.GetPolicies().GetViolated()) + assert.Equal(t, []string{testLicenses}, m.GetPolicies().GetViolatedPolicies(), "each policy once") + }) + } +} + +// The recorder keeps the policy name lists within the limit of the control plane +func TestRunEventRecorderCapsPolicyNames(t *testing.T) { + names := make([]string, 150) + for i := range names { + names[i] = testAttGate + } + + fake := &fakeEventsControlPlane{} + r := newRunEventRecorder(newFakeEventsConn(t, fake), testRunID, zerolog.Nop()) + require.NoError(t, r.Record(context.Background(), &pb.WorkflowRunEvent{ + Type: pb.WorkflowRunEvent_TYPE_ATTESTATION, Key: runEventKeyAttestation, Status: pb.WorkflowRunEvent_STATUS_STARTED, + Attributes: &pb.WorkflowRunEvent_Attestation{Attestation: &pb.WorkflowRunEvent_AttestationAttributes{ + Policies: &pb.WorkflowRunEvent_PolicyCounts{Violated: 150, ViolatedPolicies: names}, + }}, + })) + + got := fake.received() + require.Len(t, got, 1) + att := got[0].GetEvent().GetAttestation() + assert.Len(t, att.GetPolicies().GetViolatedPolicies(), 100) + assert.Equal(t, int32(150), att.GetPolicies().GetViolated(), "the counts stay complete") +} + +func TestPolicyCounts(t *testing.T) { + violation := []*api.PolicyEvaluation_Violation{{Message: testBad}} + suppressed := []*api.PolicyEvaluation_Violation{{Message: "not affected", Suppress: true}} + state := &api.CraftingState{Attestation: &api.Attestation{PolicyEvaluations: []*api.PolicyEvaluation{ + {Name: "att-pass"}, + {Name: "att-violated", Violations: violation}, + {Name: "sbom-pass", MaterialName: testSBOM}, + {Name: "sbom-skipped", MaterialName: testSBOM, Skipped: true}, + {Name: "sbom-violated", MaterialName: testSBOM, Violations: violation}, + {Name: "sbom-suppressed", MaterialName: testSBOM, Violations: suppressed}, + }}} + + testCases := []struct { + name string + material string + want *pb.WorkflowRunEvent_PolicyCounts + }{ + { + name: "attestation policies", + want: &pb.WorkflowRunEvent_PolicyCounts{Evaluated: 2, Passed: 1, Violated: 1, ViolatedPolicies: []string{"att-violated"}}, + }, + { + name: "material policies", + material: testSBOM, + want: &pb.WorkflowRunEvent_PolicyCounts{Evaluated: 4, Passed: 2, Violated: 1, Skipped: 1, ViolatedPolicies: []string{"sbom-violated"}}, + }, + { + name: "material with no policies", + material: testImage, + want: &pb.WorkflowRunEvent_PolicyCounts{}, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, policyCounts(state, tc.material)) + }) + } +} + +// newLocalCrafter initializes a crafter with local state for the run of testRunID +func newLocalCrafter(t *testing.T, conn *grpc.ClientConn, statePath string) *crafter.Crafter { + t.Helper() + + sm, err := filesystem.New(statePath) + require.NoError(t, err) + c, err := crafter.NewCrafter(sm, pb.NewAttestationServiceClient(conn)) + require.NoError(t, err) + require.NoError(t, c.Init(context.Background(), &crafter.InitOpts{ + SchemaV1: &schemaapi.CraftingSchema{SchemaVersion: "v1", Materials: []*schemaapi.CraftingSchema_Material{ + {Name: "build-ref", Type: schemaapi.CraftingSchema_Material_STRING}, + }}, + WfInfo: &api.WorkflowMetadata{WorkflowRunId: testRunID, ContractName: "build-contract", SchemaRevision: "3"}, + Runner: runners.NewGeneric(), + })) + + return c +} + +// Automatic events hold only safe data (R-005): no environment variables, no annotations +func TestMaterialEventHoldsOnlySafeData(t *testing.T) { + const ( + secretEnvValue = "env-secret-value" + annotationValue = "annotation-secret-value" + ) + t.Setenv("SOME_ENV_VAR", secretEnvValue) + + conn := newFakeEventsConn(t, &fakeEventsControlPlane{}) + c := newLocalCrafter(t, conn, filepath.Join(t.TempDir(), "state.json")) + c.CraftingState.Attestation.EnvVars = map[string]string{"SOME_ENV_VAR": secretEnvValue} + + mt, err := c.AddMaterialFromContract(context.Background(), "", "build-ref", testCommit, nil, map[string]string{"owner": annotationValue}) + require.NoError(t, err) + res, err := attMaterialToAction(mt) + require.NoError(t, err) + + events := []*pb.WorkflowRunEvent{ + materialAddedEvent(c, res, false), + attestationStartedEvent(c.CraftingState.CraftingState, true, "v1.2.3"), + } + + for _, ev := range events { + raw, err := protojson.Marshal(ev) + require.NoError(t, err) + assert.NotContains(t, string(raw), secretEnvValue) + assert.NotContains(t, string(raw), annotationValue) + } + + m := events[0].GetMaterial() + assert.Equal(t, "chainloop.material.build-ref", events[0].GetKey()) + assert.Equal(t, testCommit, m.GetValue()) + assert.Equal(t, "STRING", m.GetMaterialType()) + assert.True(t, m.GetInContract()) + assert.NotEmpty(t, m.GetDigest()) + + att := events[1].GetAttestation() + assert.Equal(t, "build-contract", att.GetContractName()) + assert.Equal(t, int32(3), att.GetContractRevision()) + assert.True(t, att.GetRemoteState()) + assert.Equal(t, "v1.2.3", att.GetCliVersion()) +} + +// A failed send never changes the result of an add (R-002), and the add records its events +func TestAttestationAddRecordsEvents(t *testing.T) { + testCases := []struct { + name string + eventErr error + value string + kind string + wantErr bool + wantEvent pb.WorkflowRunEvent_Status + }{ + {name: "add succeeds", value: testCommit, wantEvent: pb.WorkflowRunEvent_STATUS_SUCCEEDED}, + {name: "add succeeds, event rejected", value: testCommit, eventErr: status.Error(codes.FailedPrecondition, "not in progress"), wantEvent: pb.WorkflowRunEvent_STATUS_SUCCEEDED}, + {name: "add succeeds, older control plane", value: testCommit, eventErr: status.Error(codes.Unimplemented, "unknown method"), wantEvent: pb.WorkflowRunEvent_STATUS_SUCCEEDED}, + {name: "add fails", value: "/does/not/exist.json", kind: testSBOMKind, wantErr: true, wantEvent: pb.WorkflowRunEvent_STATUS_FAILED}, + {name: "add fails, event fails", value: "/does/not/exist.json", kind: testSBOMKind, eventErr: status.Error(codes.Unavailable, "down"), wantErr: true, wantEvent: pb.WorkflowRunEvent_STATUS_FAILED}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + fake := &fakeEventsControlPlane{err: tc.eventErr} + conn := newFakeEventsConn(t, fake) + statePath := filepath.Join(t.TempDir(), "state.json") + newLocalCrafter(t, conn, statePath) + + add, err := NewAttestationAdd(&AttestationAddOpts{ + ActionsOpts: &ActionsOpts{CPConnection: conn, Logger: zerolog.Nop()}, + LocalStatePath: statePath, + }) + require.NoError(t, err) + + name := "build-ref" + if tc.kind != "" { + name = testSBOM + } + res, err := add.Run(context.Background(), "", name, tc.value, tc.kind, nil, nil, nil) + if tc.wantErr { + require.Error(t, err) + } else { + require.NoError(t, err) + require.Len(t, res, 1) + assert.Equal(t, tc.value, res[0].Value) + } + + got := fake.received() + require.Len(t, got, 1) + ev := got[0].GetEvent() + assert.Equal(t, "chainloop.material."+name, ev.GetKey()) + assert.Equal(t, tc.wantEvent, ev.GetStatus()) + if tc.wantErr { + assert.NotEmpty(t, ev.GetMessage(), "a failed add keeps its error text") + } else { + assert.Empty(t, ev.GetMessage()) + } + }) + } +} + +// The start event lists the materials of the resolved contract, policy groups included, +// so that the control plane can build the progress of the run +// +//nolint:staticcheck // the V1 schema holds the materials of this crafting state +func TestAttestationStartedEventExpectedMaterials(t *testing.T) { + state := &api.CraftingState{ + Schema: &api.CraftingState_InputSchema{InputSchema: &schemaapi.CraftingSchema{Materials: []*schemaapi.CraftingSchema_Material{ + {Name: testSBOM, Type: schemaapi.CraftingSchema_Material_SBOM_CYCLONEDX_JSON}, + {Name: "notes", Type: schemaapi.CraftingSchema_Material_STRING, Optional: true}, + {Name: testCDX, Type: schemaapi.CraftingSchema_Material_SBOM_CYCLONEDX_JSON, Group: testSBOMs}, + }}}, + Attestation: &api.Attestation{}, + } + + got := attestationStartedEvent(state, false, "v1.2.3").GetAttestation().GetExpectedMaterials() + require.Len(t, got, 3) + assert.Equal(t, testSBOM, got[0].GetName()) + assert.Equal(t, "SBOM_CYCLONEDX_JSON", got[0].GetMaterialType()) + assert.True(t, got[1].GetOptional()) + assert.Equal(t, testSBOMs, got[2].GetGroup()) +} diff --git a/app/cli/pkg/action/workflow_run_describe.go b/app/cli/pkg/action/workflow_run_describe.go index 0f64ff021..1f3b9557c 100644 --- a/app/cli/pkg/action/workflow_run_describe.go +++ b/app/cli/pkg/action/workflow_run_describe.go @@ -23,6 +23,7 @@ import ( "fmt" "sort" "strings" + "time" "unicode/utf8" pb "github.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1" @@ -37,6 +38,8 @@ import ( "github.com/sigstore/sigstore/pkg/cryptoutils" "github.com/sigstore/sigstore/pkg/signature" sigdsee "github.com/sigstore/sigstore/pkg/signature/dsse" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) type WorkflowRunDescribe struct { @@ -48,6 +51,10 @@ type WorkflowRunItemFull struct { Workflow *WorkflowItem `json:"workflow"` Attestation *WorkflowRunAttestationItem `json:"attestation,omitempty"` Verified bool `json:"verified"` + // Progress events reported during the attestation. Unsigned, informational data. + Events []*RunEvent `json:"events,omitempty"` + // Progress of a run in progress, built by the control plane + Progress *RunProgress `json:"progress,omitempty"` } type WorkflowRunAttestationItem struct { @@ -209,6 +216,9 @@ func (action *WorkflowRunDescribe) Run(ctx context.Context, opts *WorkflowRunDes item.WorkflowRun.FinishedAt = toTimePtr(wr.FinishedAt.AsTime()) } + // Progress and events are optional: without them, describe shows the run as before + action.addRunProgress(ctx, client, wr.GetId(), item) + att := resp.GetResult().GetAttestation() // The item does not have associated attestation if att == nil { @@ -514,3 +524,195 @@ func loadCertificates(certPath string) ([]*x509.Certificate, error) { return certs, nil } + +// RunEvent is a progress event of a run. It is unsigned, reported data, never part of the attestation. +type RunEvent struct { + ID string `json:"id"` + CreatedAt *time.Time `json:"created_at,omitempty"` + Source string `json:"source"` + Type string `json:"type"` + Key string `json:"key"` + Status string `json:"status"` + Message string `json:"message,omitempty"` + Attestation *RunEventAttestation `json:"attestation,omitempty"` + Material *RunEventMaterial `json:"material,omitempty"` +} + +type RunEventAttestation struct { + ContractName string `json:"contract_name,omitempty"` + ContractRevision int32 `json:"contract_revision,omitempty"` + RunnerType string `json:"runner_type,omitempty"` + RemoteState bool `json:"remote_state"` + CLIVersion string `json:"cli_version,omitempty"` + AttestationDigest string `json:"attestation_digest,omitempty"` + // results of the attestation policies evaluated at init + Policies *RunEventPolicyCount `json:"policies,omitempty"` +} + +type RunEventMaterial struct { + Name string `json:"name"` + MaterialType string `json:"material_type,omitempty"` + Value string `json:"value,omitempty"` + Digest string `json:"digest,omitempty"` + InContract bool `json:"in_contract"` + AddedByCollector bool `json:"added_by_collector"` + Policies *RunEventPolicyCount `json:"policies,omitempty"` +} + +type RunEventPolicyCount struct { + Evaluated int32 `json:"evaluated"` + Passed int32 `json:"passed"` + Violated int32 `json:"violated"` + Skipped int32 `json:"skipped"` + ViolatedPolicies []string `json:"violated_policies,omitempty"` +} + +// RunProgress is the progress of a run in progress, as the control plane builds it from +// the expected materials and the reported events +type RunProgress struct { + // one row for each expected material, then the materials not in the contract + Materials []*RunProgressMaterial `json:"materials"` + // required materials, where a group of materials counts once + RequiredTotal int `json:"required_total"` + RequiredProvided int `json:"required_provided"` + // results of the attestation policies evaluated at init + AttestationPolicies *RunEventPolicyCount `json:"attestation_policies,omitempty"` +} + +type RunProgressMaterial struct { + Name string `json:"name"` + Type string `json:"type,omitempty"` + // required, optional, one_of_group, or not_in_contract + Requirement string `json:"requirement"` + // set when the material is one of a group, of which one is required + Group string `json:"group,omitempty"` + // missing, provided, or failed + Status string `json:"status"` + // value and policy results of the last successful add + Value string `json:"value,omitempty"` + Policies *RunEventPolicyCount `json:"policies,omitempty"` + // error of the last add, when it failed + LastError string `json:"last_error,omitempty"` + FailedAttempts int `json:"failed_attempts,omitempty"` +} + +// Values of RunProgressMaterial +const ( + RunMaterialRequired = "required" + RunMaterialOptional = "optional" + RunMaterialOneOfGroup = "one_of_group" + RunMaterialNotInContract = "not_in_contract" + + RunMaterialMissing = "missing" + RunMaterialProvided = "provided" + RunMaterialFailed = "failed" +) + +func pbRunEventToAction(in *pb.WorkflowRunEvent) *RunEvent { + out := &RunEvent{ + ID: in.GetId(), + Source: strings.ToLower(strings.TrimPrefix(in.GetSource().String(), "SOURCE_")), + Type: strings.ToLower(strings.TrimPrefix(in.GetType().String(), "TYPE_")), + Key: in.GetKey(), + Status: strings.ToLower(strings.TrimPrefix(in.GetStatus().String(), "STATUS_")), + Message: in.GetMessage(), + } + + if in.GetCreatedAt() != nil { + out.CreatedAt = toTimePtr(in.GetCreatedAt().AsTime()) + } + + if a := in.GetAttestation(); a != nil { + out.Attestation = &RunEventAttestation{ + ContractName: a.GetContractName(), ContractRevision: a.GetContractRevision(), RunnerType: a.GetRunnerType(), + RemoteState: a.GetRemoteState(), CLIVersion: a.GetCliVersion(), AttestationDigest: a.GetAttestationDigest(), + Policies: pbRunEventPolicyCountToAction(a.GetPolicies()), + } + } + + if m := in.GetMaterial(); m != nil { + out.Material = &RunEventMaterial{ + Name: m.GetName(), MaterialType: m.GetMaterialType(), Value: m.GetValue(), Digest: m.GetDigest(), + InContract: m.GetInContract(), AddedByCollector: m.GetAddedByCollector(), Policies: pbRunEventPolicyCountToAction(m.GetPolicies()), + } + } + + return out +} + +func pbRunEventPolicyCountToAction(in *pb.WorkflowRunEvent_PolicyCounts) *RunEventPolicyCount { + if in == nil { + return nil + } + + return &RunEventPolicyCount{ + Evaluated: in.GetEvaluated(), Passed: in.GetPassed(), Violated: in.GetViolated(), Skipped: in.GetSkipped(), + ViolatedPolicies: in.GetViolatedPolicies(), + } +} + +// RunStepName is the name of a step shown to the user: the key with no automatic prefix +func RunStepName(key string) string { + if material, ok := strings.CutPrefix(key, runEventKeyMaterialPrefix); ok { + return material + } + + return strings.TrimPrefix(key, runEventKeyPrefix) +} + +var ( + pbToActionRunMaterialRequirement = map[pb.WorkflowRunProgress_Requirement]string{ + pb.WorkflowRunProgress_REQUIREMENT_REQUIRED: RunMaterialRequired, + pb.WorkflowRunProgress_REQUIREMENT_OPTIONAL: RunMaterialOptional, + pb.WorkflowRunProgress_REQUIREMENT_ONE_OF_GROUP: RunMaterialOneOfGroup, + pb.WorkflowRunProgress_REQUIREMENT_NOT_IN_CONTRACT: RunMaterialNotInContract, + } + pbToActionRunMaterialStatus = map[pb.WorkflowRunProgress_Status]string{ + pb.WorkflowRunProgress_STATUS_MISSING: RunMaterialMissing, + pb.WorkflowRunProgress_STATUS_PROVIDED: RunMaterialProvided, + pb.WorkflowRunProgress_STATUS_FAILED: RunMaterialFailed, + } +) + +// addRunProgress adds the events and the progress of the run to the item. An older control +// plane does not have the call, and an error never fails describe. +func (action *WorkflowRunDescribe) addRunProgress(ctx context.Context, client pb.WorkflowRunServiceClient, runID string, item *WorkflowRunItemFull) { + resp, err := client.GetProgress(ctx, &pb.WorkflowRunServiceGetProgressRequest{WorkflowRunId: runID}) + if err != nil { + if status.Code(err) == codes.Unimplemented { + action.cfg.Logger.Debug().Err(err).Msg("the control plane does not support run progress") + } else { + action.cfg.Logger.Warn().Err(err).Msg("failed to retrieve the progress of the run") + } + return + } + + for _, e := range resp.GetEvents() { + item.Events = append(item.Events, pbRunEventToAction(e)) + } + item.Progress = pbRunProgressToAction(resp.GetProgress()) +} + +func pbRunProgressToAction(in *pb.WorkflowRunProgress) *RunProgress { + if in == nil { + return nil + } + + out := &RunProgress{ + RequiredTotal: int(in.GetRequiredTotal()), RequiredProvided: int(in.GetRequiredProvided()), + AttestationPolicies: pbRunEventPolicyCountToAction(in.GetAttestationPolicies()), + Materials: make([]*RunProgressMaterial, 0, len(in.GetMaterials())), + } + for _, m := range in.GetMaterials() { + out.Materials = append(out.Materials, &RunProgressMaterial{ + Name: m.GetName(), Type: m.GetMaterialType(), + Requirement: pbToActionRunMaterialRequirement[m.GetRequirement()], + Group: m.GetGroup(), + Status: pbToActionRunMaterialStatus[m.GetStatus()], + Value: m.GetValue(), Policies: pbRunEventPolicyCountToAction(m.GetPolicies()), + LastError: m.GetLastError(), FailedAttempts: int(m.GetFailedAttempts()), + }) + } + + return out +} diff --git a/app/cli/pkg/action/workflow_run_describe_test.go b/app/cli/pkg/action/workflow_run_describe_test.go index ff5266fe1..85fa7e3cb 100644 --- a/app/cli/pkg/action/workflow_run_describe_test.go +++ b/app/cli/pkg/action/workflow_run_describe_test.go @@ -22,9 +22,15 @@ import ( "testing" pb "github.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1" + "github.com/rs/zerolog" "github.com/secure-systems-lab/go-securesystemslib/dsse" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/timestamppb" ) type WorkflowRunDescribeTestSuite struct { @@ -156,3 +162,94 @@ func TestPBPolicyEvaluationsRefToAction(t *testing.T) { }) } } + +// fakeRunViewServer serves View for one run, and GetProgress with the events, the progress, +// or the error it is given +type fakeRunViewServer struct { + pb.UnimplementedWorkflowRunServiceServer + status pb.RunStatus + events []*pb.WorkflowRunEvent + progress *pb.WorkflowRunProgress + progressErr error +} + +func (f *fakeRunViewServer) View(context.Context, *pb.WorkflowRunServiceViewRequest) (*pb.WorkflowRunServiceViewResponse, error) { + return &pb.WorkflowRunServiceViewResponse{Result: &pb.WorkflowRunServiceViewResponse_Result{ + WorkflowRun: &pb.WorkflowRunItem{Id: testRunID, Status: f.status, CreatedAt: timestamppb.Now()}, + }}, nil +} + +func (f *fakeRunViewServer) GetProgress(context.Context, *pb.WorkflowRunServiceGetProgressRequest) (*pb.WorkflowRunServiceGetProgressResponse, error) { + if f.progressErr != nil { + return nil, f.progressErr + } + + return &pb.WorkflowRunServiceGetProgressResponse{Events: f.events, Progress: f.progress}, nil +} + +func TestWorkflowRunDescribeEvents(t *testing.T) { + sbomFailed := &pb.WorkflowRunEvent{ + Id: "1", CreatedAt: timestamppb.Now(), Source: pb.WorkflowRunEvent_SOURCE_CLI, Type: pb.WorkflowRunEvent_TYPE_MATERIAL, + Key: testSBOMKey, Status: pb.WorkflowRunEvent_STATUS_FAILED, Message: testInvalid, + Attributes: &pb.WorkflowRunEvent_Material{Material: &pb.WorkflowRunEvent_MaterialAttributes{Name: testSBOM, InContract: true}}, + } + expired := &pb.WorkflowRunEvent{ + Id: "2", CreatedAt: timestamppb.Now(), Source: pb.WorkflowRunEvent_SOURCE_CONTROL_PLANE, Type: pb.WorkflowRunEvent_TYPE_ATTESTATION, + Key: testAttKey, Status: pb.WorkflowRunEvent_STATUS_FAILED, Message: "expired", + } + progress := &pb.WorkflowRunProgress{ + RequiredTotal: 2, RequiredProvided: 1, + Materials: []*pb.WorkflowRunProgress_Material{ + {Name: testSBOM, MaterialType: testSBOMKind, Requirement: pb.WorkflowRunProgress_REQUIREMENT_REQUIRED, + Status: pb.WorkflowRunProgress_STATUS_FAILED, LastError: testInvalid, FailedAttempts: 1}, + {Name: testCDX, Requirement: pb.WorkflowRunProgress_REQUIREMENT_ONE_OF_GROUP, Group: testSBOMs, Status: pb.WorkflowRunProgress_STATUS_PROVIDED, Value: "bom.json"}, + }, + } + + testCases := []struct { + name string + server *fakeRunViewServer + wantEvents int + wantProgress *RunProgress + }{ + { + name: "run in progress", + server: &fakeRunViewServer{status: pb.RunStatus_RUN_STATUS_INITIALIZED, events: []*pb.WorkflowRunEvent{sbomFailed}, progress: progress}, + wantEvents: 1, + wantProgress: &RunProgress{RequiredTotal: 2, RequiredProvided: 1, Materials: []*RunProgressMaterial{ + {Name: testSBOM, Type: testSBOMKind, Requirement: RunMaterialRequired, Status: RunMaterialFailed, LastError: testInvalid, FailedAttempts: 1}, + {Name: testCDX, Requirement: RunMaterialOneOfGroup, Group: testSBOMs, Status: RunMaterialProvided, Value: "bom.json"}, + }}, + }, + { + name: "expired run shows the timeline as history", + server: &fakeRunViewServer{status: pb.RunStatus_RUN_STATUS_EXPIRED, events: []*pb.WorkflowRunEvent{sbomFailed, expired}}, + wantEvents: 2, + }, + { + name: "run with no events, as from an older CLI", + server: &fakeRunViewServer{status: pb.RunStatus_RUN_STATUS_INITIALIZED}, + }, + { + name: "older control plane", + server: &fakeRunViewServer{status: pb.RunStatus_RUN_STATUS_INITIALIZED, progressErr: status.Error(codes.Unimplemented, "unknown method")}, + }, + { + name: "other error", + server: &fakeRunViewServer{status: pb.RunStatus_RUN_STATUS_INITIALIZED, progressErr: status.Error(codes.Internal, "boom")}, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + conn := newBufConn(t, func(s *grpc.Server) { pb.RegisterWorkflowRunServiceServer(s, tc.server) }) + + got, err := NewWorkflowRunDescribe(&ActionsOpts{CPConnection: conn, Logger: zerolog.Nop()}). + Run(context.Background(), &WorkflowRunDescribeOpts{RunID: testRunID}) + require.NoError(t, err, "describe never fails because of the progress") + + assert.Len(t, got.Events, tc.wantEvents) + assert.Equal(t, tc.wantProgress, got.Progress) + }) + } +} diff --git a/app/controlplane/api/controlplane/v1/workflow_run.pb.go b/app/controlplane/api/controlplane/v1/workflow_run.pb.go index 529777e3a..1bbfe1b77 100644 --- a/app/controlplane/api/controlplane/v1/workflow_run.pb.go +++ b/app/controlplane/api/controlplane/v1/workflow_run.pb.go @@ -26,6 +26,7 @@ import ( v1 "github.com/chainloop-dev/chainloop/app/controlplane/api/workflowcontract/v1" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" + timestamppb "google.golang.org/protobuf/types/known/timestamppb" reflect "reflect" sync "sync" unsafe "unsafe" @@ -87,6 +88,269 @@ func (AttestationServiceCancelRequest_TriggerType) EnumDescriptor() ([]byte, []i return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{13, 0} } +type WorkflowRunEvent_Source int32 + +const ( + WorkflowRunEvent_SOURCE_UNSPECIFIED WorkflowRunEvent_Source = 0 + WorkflowRunEvent_SOURCE_CLI WorkflowRunEvent_Source = 1 + WorkflowRunEvent_SOURCE_CONTROL_PLANE WorkflowRunEvent_Source = 2 +) + +// Enum value maps for WorkflowRunEvent_Source. +var ( + WorkflowRunEvent_Source_name = map[int32]string{ + 0: "SOURCE_UNSPECIFIED", + 1: "SOURCE_CLI", + 2: "SOURCE_CONTROL_PLANE", + } + WorkflowRunEvent_Source_value = map[string]int32{ + "SOURCE_UNSPECIFIED": 0, + "SOURCE_CLI": 1, + "SOURCE_CONTROL_PLANE": 2, + } +) + +func (x WorkflowRunEvent_Source) Enum() *WorkflowRunEvent_Source { + p := new(WorkflowRunEvent_Source) + *p = x + return p +} + +func (x WorkflowRunEvent_Source) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (WorkflowRunEvent_Source) Descriptor() protoreflect.EnumDescriptor { + return file_controlplane_v1_workflow_run_proto_enumTypes[1].Descriptor() +} + +func (WorkflowRunEvent_Source) Type() protoreflect.EnumType { + return &file_controlplane_v1_workflow_run_proto_enumTypes[1] +} + +func (x WorkflowRunEvent_Source) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use WorkflowRunEvent_Source.Descriptor instead. +func (WorkflowRunEvent_Source) EnumDescriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{17, 0} +} + +type WorkflowRunEvent_Type int32 + +const ( + WorkflowRunEvent_TYPE_UNSPECIFIED WorkflowRunEvent_Type = 0 + WorkflowRunEvent_TYPE_ATTESTATION WorkflowRunEvent_Type = 1 + WorkflowRunEvent_TYPE_MATERIAL WorkflowRunEvent_Type = 2 +) + +// Enum value maps for WorkflowRunEvent_Type. +var ( + WorkflowRunEvent_Type_name = map[int32]string{ + 0: "TYPE_UNSPECIFIED", + 1: "TYPE_ATTESTATION", + 2: "TYPE_MATERIAL", + } + WorkflowRunEvent_Type_value = map[string]int32{ + "TYPE_UNSPECIFIED": 0, + "TYPE_ATTESTATION": 1, + "TYPE_MATERIAL": 2, + } +) + +func (x WorkflowRunEvent_Type) Enum() *WorkflowRunEvent_Type { + p := new(WorkflowRunEvent_Type) + *p = x + return p +} + +func (x WorkflowRunEvent_Type) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (WorkflowRunEvent_Type) Descriptor() protoreflect.EnumDescriptor { + return file_controlplane_v1_workflow_run_proto_enumTypes[2].Descriptor() +} + +func (WorkflowRunEvent_Type) Type() protoreflect.EnumType { + return &file_controlplane_v1_workflow_run_proto_enumTypes[2] +} + +func (x WorkflowRunEvent_Type) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use WorkflowRunEvent_Type.Descriptor instead. +func (WorkflowRunEvent_Type) EnumDescriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{17, 1} +} + +type WorkflowRunEvent_Status int32 + +const ( + WorkflowRunEvent_STATUS_UNSPECIFIED WorkflowRunEvent_Status = 0 + WorkflowRunEvent_STATUS_STARTED WorkflowRunEvent_Status = 1 + WorkflowRunEvent_STATUS_SUCCEEDED WorkflowRunEvent_Status = 2 + WorkflowRunEvent_STATUS_FAILED WorkflowRunEvent_Status = 3 + WorkflowRunEvent_STATUS_CANCELED WorkflowRunEvent_Status = 4 +) + +// Enum value maps for WorkflowRunEvent_Status. +var ( + WorkflowRunEvent_Status_name = map[int32]string{ + 0: "STATUS_UNSPECIFIED", + 1: "STATUS_STARTED", + 2: "STATUS_SUCCEEDED", + 3: "STATUS_FAILED", + 4: "STATUS_CANCELED", + } + WorkflowRunEvent_Status_value = map[string]int32{ + "STATUS_UNSPECIFIED": 0, + "STATUS_STARTED": 1, + "STATUS_SUCCEEDED": 2, + "STATUS_FAILED": 3, + "STATUS_CANCELED": 4, + } +) + +func (x WorkflowRunEvent_Status) Enum() *WorkflowRunEvent_Status { + p := new(WorkflowRunEvent_Status) + *p = x + return p +} + +func (x WorkflowRunEvent_Status) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (WorkflowRunEvent_Status) Descriptor() protoreflect.EnumDescriptor { + return file_controlplane_v1_workflow_run_proto_enumTypes[3].Descriptor() +} + +func (WorkflowRunEvent_Status) Type() protoreflect.EnumType { + return &file_controlplane_v1_workflow_run_proto_enumTypes[3] +} + +func (x WorkflowRunEvent_Status) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use WorkflowRunEvent_Status.Descriptor instead. +func (WorkflowRunEvent_Status) EnumDescriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{17, 2} +} + +type WorkflowRunProgress_Requirement int32 + +const ( + WorkflowRunProgress_REQUIREMENT_UNSPECIFIED WorkflowRunProgress_Requirement = 0 + WorkflowRunProgress_REQUIREMENT_REQUIRED WorkflowRunProgress_Requirement = 1 + WorkflowRunProgress_REQUIREMENT_OPTIONAL WorkflowRunProgress_Requirement = 2 + WorkflowRunProgress_REQUIREMENT_ONE_OF_GROUP WorkflowRunProgress_Requirement = 3 + WorkflowRunProgress_REQUIREMENT_NOT_IN_CONTRACT WorkflowRunProgress_Requirement = 4 +) + +// Enum value maps for WorkflowRunProgress_Requirement. +var ( + WorkflowRunProgress_Requirement_name = map[int32]string{ + 0: "REQUIREMENT_UNSPECIFIED", + 1: "REQUIREMENT_REQUIRED", + 2: "REQUIREMENT_OPTIONAL", + 3: "REQUIREMENT_ONE_OF_GROUP", + 4: "REQUIREMENT_NOT_IN_CONTRACT", + } + WorkflowRunProgress_Requirement_value = map[string]int32{ + "REQUIREMENT_UNSPECIFIED": 0, + "REQUIREMENT_REQUIRED": 1, + "REQUIREMENT_OPTIONAL": 2, + "REQUIREMENT_ONE_OF_GROUP": 3, + "REQUIREMENT_NOT_IN_CONTRACT": 4, + } +) + +func (x WorkflowRunProgress_Requirement) Enum() *WorkflowRunProgress_Requirement { + p := new(WorkflowRunProgress_Requirement) + *p = x + return p +} + +func (x WorkflowRunProgress_Requirement) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (WorkflowRunProgress_Requirement) Descriptor() protoreflect.EnumDescriptor { + return file_controlplane_v1_workflow_run_proto_enumTypes[4].Descriptor() +} + +func (WorkflowRunProgress_Requirement) Type() protoreflect.EnumType { + return &file_controlplane_v1_workflow_run_proto_enumTypes[4] +} + +func (x WorkflowRunProgress_Requirement) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use WorkflowRunProgress_Requirement.Descriptor instead. +func (WorkflowRunProgress_Requirement) EnumDescriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{23, 0} +} + +type WorkflowRunProgress_Status int32 + +const ( + WorkflowRunProgress_STATUS_UNSPECIFIED WorkflowRunProgress_Status = 0 + // No add of the material yet + WorkflowRunProgress_STATUS_MISSING WorkflowRunProgress_Status = 1 + // An add of the material succeeded + WorkflowRunProgress_STATUS_PROVIDED WorkflowRunProgress_Status = 2 + // Never provided, and the last add failed + WorkflowRunProgress_STATUS_FAILED WorkflowRunProgress_Status = 3 +) + +// Enum value maps for WorkflowRunProgress_Status. +var ( + WorkflowRunProgress_Status_name = map[int32]string{ + 0: "STATUS_UNSPECIFIED", + 1: "STATUS_MISSING", + 2: "STATUS_PROVIDED", + 3: "STATUS_FAILED", + } + WorkflowRunProgress_Status_value = map[string]int32{ + "STATUS_UNSPECIFIED": 0, + "STATUS_MISSING": 1, + "STATUS_PROVIDED": 2, + "STATUS_FAILED": 3, + } +) + +func (x WorkflowRunProgress_Status) Enum() *WorkflowRunProgress_Status { + p := new(WorkflowRunProgress_Status) + *p = x + return p +} + +func (x WorkflowRunProgress_Status) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (WorkflowRunProgress_Status) Descriptor() protoreflect.EnumDescriptor { + return file_controlplane_v1_workflow_run_proto_enumTypes[5].Descriptor() +} + +func (WorkflowRunProgress_Status) Type() protoreflect.EnumType { + return &file_controlplane_v1_workflow_run_proto_enumTypes[5] +} + +func (x WorkflowRunProgress_Status) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use WorkflowRunProgress_Status.Descriptor instead. +func (WorkflowRunProgress_Status) EnumDescriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{23, 1} +} + type FindOrCreateWorkflowRequest struct { state protoimpl.MessageState `protogen:"open.v1"` WorkflowName string `protobuf:"bytes,4,opt,name=workflow_name,json=workflowName,proto3" json:"workflow_name,omitempty"` @@ -952,56 +1216,29 @@ func (*AttestationServiceCancelResponse) Descriptor() ([]byte, []int) { return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{14} } -type WorkflowRunServiceListRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - // Filters - // by workflow - WorkflowName string `protobuf:"bytes,1,opt,name=workflow_name,json=workflowName,proto3" json:"workflow_name,omitempty"` - // Not required since filtering by workflow and project is optional - ProjectName string `protobuf:"bytes,4,opt,name=project_name,json=projectName,proto3" json:"project_name,omitempty"` - // by run status - Status RunStatus `protobuf:"varint,3,opt,name=status,proto3,enum=controlplane.v1.RunStatus" json:"status,omitempty"` - // by project version (UUID). - // Deprecated: use project_version_name together with project_name. A version - // name is unique only within a project, so filtering by name is the canonical - // and discoverable path; the UUID is kept for backward compatibility. - // - // Deprecated: Marked as deprecated in controlplane/v1/workflow_run.proto. - ProjectVersion string `protobuf:"bytes,5,opt,name=project_version,json=projectVersion,proto3" json:"project_version,omitempty"` - // by project version name (e.g. v1.2.0). Requires project_name, since a - // version name is unique only within a project. - ProjectVersionName string `protobuf:"bytes,9,opt,name=project_version_name,json=projectVersionName,proto3" json:"project_version_name,omitempty"` - // by policy violations status - // Deprecated: use policy_status (PolicyStatusFilter), which aligns 1:1 with - // the canonical PolicyStatus enum. When both are set, policy_status wins. - // - // Deprecated: Marked as deprecated in controlplane/v1/workflow_run.proto. - PolicyViolations PolicyViolationsFilter `protobuf:"varint,6,opt,name=policy_violations,json=policyViolations,proto3,enum=controlplane.v1.PolicyViolationsFilter" json:"policy_violations,omitempty"` - // by canonical policy status - PolicyStatus PolicyStatusFilter `protobuf:"varint,7,opt,name=policy_status,json=policyStatus,proto3,enum=controlplane.v1.PolicyStatusFilter" json:"policy_status,omitempty"` - // by whether the run had gates in effect (either a policy marked gate:true - // or the contract using the ENFORCED blocking strategy) - PolicyGates PolicyGatesFilter `protobuf:"varint,8,opt,name=policy_gates,json=policyGates,proto3,enum=controlplane.v1.PolicyGatesFilter" json:"policy_gates,omitempty"` - // pagination options - Pagination *CursorPaginationRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` +type AttestationServiceRecordEventRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + WorkflowRunId string `protobuf:"bytes,1,opt,name=workflow_run_id,json=workflowRunId,proto3" json:"workflow_run_id,omitempty"` + // id, created_at, and source are set by the server and ignored here. + Event *WorkflowRunEvent `protobuf:"bytes,2,opt,name=event,proto3" json:"event,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } -func (x *WorkflowRunServiceListRequest) Reset() { - *x = WorkflowRunServiceListRequest{} +func (x *AttestationServiceRecordEventRequest) Reset() { + *x = AttestationServiceRecordEventRequest{} mi := &file_controlplane_v1_workflow_run_proto_msgTypes[15] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } -func (x *WorkflowRunServiceListRequest) String() string { +func (x *AttestationServiceRecordEventRequest) String() string { return protoimpl.X.MessageStringOf(x) } -func (*WorkflowRunServiceListRequest) ProtoMessage() {} +func (*AttestationServiceRecordEventRequest) ProtoMessage() {} -func (x *WorkflowRunServiceListRequest) ProtoReflect() protoreflect.Message { +func (x *AttestationServiceRecordEventRequest) ProtoReflect() protoreflect.Message { mi := &file_controlplane_v1_workflow_run_proto_msgTypes[15] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) @@ -1013,99 +1250,98 @@ func (x *WorkflowRunServiceListRequest) ProtoReflect() protoreflect.Message { return mi.MessageOf(x) } -// Deprecated: Use WorkflowRunServiceListRequest.ProtoReflect.Descriptor instead. -func (*WorkflowRunServiceListRequest) Descriptor() ([]byte, []int) { +// Deprecated: Use AttestationServiceRecordEventRequest.ProtoReflect.Descriptor instead. +func (*AttestationServiceRecordEventRequest) Descriptor() ([]byte, []int) { return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{15} } -func (x *WorkflowRunServiceListRequest) GetWorkflowName() string { - if x != nil { - return x.WorkflowName - } - return "" -} - -func (x *WorkflowRunServiceListRequest) GetProjectName() string { +func (x *AttestationServiceRecordEventRequest) GetWorkflowRunId() string { if x != nil { - return x.ProjectName + return x.WorkflowRunId } return "" } -func (x *WorkflowRunServiceListRequest) GetStatus() RunStatus { +func (x *AttestationServiceRecordEventRequest) GetEvent() *WorkflowRunEvent { if x != nil { - return x.Status + return x.Event } - return RunStatus_RUN_STATUS_UNSPECIFIED + return nil } -// Deprecated: Marked as deprecated in controlplane/v1/workflow_run.proto. -func (x *WorkflowRunServiceListRequest) GetProjectVersion() string { - if x != nil { - return x.ProjectVersion - } - return "" +type AttestationServiceRecordEventResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } -func (x *WorkflowRunServiceListRequest) GetProjectVersionName() string { - if x != nil { - return x.ProjectVersionName - } - return "" +func (x *AttestationServiceRecordEventResponse) Reset() { + *x = AttestationServiceRecordEventResponse{} + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[16] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } -// Deprecated: Marked as deprecated in controlplane/v1/workflow_run.proto. -func (x *WorkflowRunServiceListRequest) GetPolicyViolations() PolicyViolationsFilter { - if x != nil { - return x.PolicyViolations - } - return PolicyViolationsFilter_POLICY_VIOLATIONS_FILTER_UNSPECIFIED +func (x *AttestationServiceRecordEventResponse) String() string { + return protoimpl.X.MessageStringOf(x) } -func (x *WorkflowRunServiceListRequest) GetPolicyStatus() PolicyStatusFilter { - if x != nil { - return x.PolicyStatus - } - return PolicyStatusFilter_POLICY_STATUS_FILTER_UNSPECIFIED -} +func (*AttestationServiceRecordEventResponse) ProtoMessage() {} -func (x *WorkflowRunServiceListRequest) GetPolicyGates() PolicyGatesFilter { +func (x *AttestationServiceRecordEventResponse) ProtoReflect() protoreflect.Message { + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[16] if x != nil { - return x.PolicyGates + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms } - return PolicyGatesFilter_POLICY_GATES_FILTER_UNSPECIFIED + return mi.MessageOf(x) } -func (x *WorkflowRunServiceListRequest) GetPagination() *CursorPaginationRequest { - if x != nil { - return x.Pagination - } - return nil +// Deprecated: Use AttestationServiceRecordEventResponse.ProtoReflect.Descriptor instead. +func (*AttestationServiceRecordEventResponse) Descriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{16} } -type WorkflowRunServiceListResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Result []*WorkflowRunItem `protobuf:"bytes,1,rep,name=result,proto3" json:"result,omitempty"` - Pagination *CursorPaginationResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` +// A progress event of a workflow run. Unsigned and informational only. +// It is never part of the attestation. +type WorkflowRunEvent struct { + state protoimpl.MessageState `protogen:"open.v1"` + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` + // Time the control plane received the event + CreatedAt *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=created_at,json=createdAt,proto3" json:"created_at,omitempty"` + Source WorkflowRunEvent_Source `protobuf:"varint,3,opt,name=source,proto3,enum=controlplane.v1.WorkflowRunEvent_Source" json:"source,omitempty"` + Type WorkflowRunEvent_Type `protobuf:"varint,4,opt,name=type,proto3,enum=controlplane.v1.WorkflowRunEvent_Type" json:"type,omitempty"` + // Events with the same key are one step of the timeline + Key string `protobuf:"bytes,5,opt,name=key,proto3" json:"key,omitempty"` + Status WorkflowRunEvent_Status `protobuf:"varint,6,opt,name=status,proto3,enum=controlplane.v1.WorkflowRunEvent_Status" json:"status,omitempty"` + Message string `protobuf:"bytes,7,opt,name=message,proto3" json:"message,omitempty"` + // Types that are valid to be assigned to Attributes: + // + // *WorkflowRunEvent_Attestation + // *WorkflowRunEvent_Material + Attributes isWorkflowRunEvent_Attributes `protobuf_oneof:"attributes"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } -func (x *WorkflowRunServiceListResponse) Reset() { - *x = WorkflowRunServiceListResponse{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[16] +func (x *WorkflowRunEvent) Reset() { + *x = WorkflowRunEvent{} + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[17] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } -func (x *WorkflowRunServiceListResponse) String() string { +func (x *WorkflowRunEvent) String() string { return protoimpl.X.MessageStringOf(x) } -func (*WorkflowRunServiceListResponse) ProtoMessage() {} +func (*WorkflowRunEvent) ProtoMessage() {} -func (x *WorkflowRunServiceListResponse) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[16] +func (x *WorkflowRunEvent) ProtoReflect() protoreflect.Message { + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[17] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1116,33 +1352,292 @@ func (x *WorkflowRunServiceListResponse) ProtoReflect() protoreflect.Message { return mi.MessageOf(x) } -// Deprecated: Use WorkflowRunServiceListResponse.ProtoReflect.Descriptor instead. -func (*WorkflowRunServiceListResponse) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{16} +// Deprecated: Use WorkflowRunEvent.ProtoReflect.Descriptor instead. +func (*WorkflowRunEvent) Descriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{17} } -func (x *WorkflowRunServiceListResponse) GetResult() []*WorkflowRunItem { +func (x *WorkflowRunEvent) GetId() string { if x != nil { - return x.Result + return x.Id } - return nil + return "" } -func (x *WorkflowRunServiceListResponse) GetPagination() *CursorPaginationResponse { +func (x *WorkflowRunEvent) GetCreatedAt() *timestamppb.Timestamp { if x != nil { - return x.Pagination + return x.CreatedAt } return nil } -type WorkflowRunServiceViewRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - // It can search by either ID or digest - // - // Types that are valid to be assigned to Ref: - // - // *WorkflowRunServiceViewRequest_Id - // *WorkflowRunServiceViewRequest_Digest +func (x *WorkflowRunEvent) GetSource() WorkflowRunEvent_Source { + if x != nil { + return x.Source + } + return WorkflowRunEvent_SOURCE_UNSPECIFIED +} + +func (x *WorkflowRunEvent) GetType() WorkflowRunEvent_Type { + if x != nil { + return x.Type + } + return WorkflowRunEvent_TYPE_UNSPECIFIED +} + +func (x *WorkflowRunEvent) GetKey() string { + if x != nil { + return x.Key + } + return "" +} + +func (x *WorkflowRunEvent) GetStatus() WorkflowRunEvent_Status { + if x != nil { + return x.Status + } + return WorkflowRunEvent_STATUS_UNSPECIFIED +} + +func (x *WorkflowRunEvent) GetMessage() string { + if x != nil { + return x.Message + } + return "" +} + +func (x *WorkflowRunEvent) GetAttributes() isWorkflowRunEvent_Attributes { + if x != nil { + return x.Attributes + } + return nil +} + +func (x *WorkflowRunEvent) GetAttestation() *WorkflowRunEvent_AttestationAttributes { + if x != nil { + if x, ok := x.Attributes.(*WorkflowRunEvent_Attestation); ok { + return x.Attestation + } + } + return nil +} + +func (x *WorkflowRunEvent) GetMaterial() *WorkflowRunEvent_MaterialAttributes { + if x != nil { + if x, ok := x.Attributes.(*WorkflowRunEvent_Material); ok { + return x.Material + } + } + return nil +} + +type isWorkflowRunEvent_Attributes interface { + isWorkflowRunEvent_Attributes() +} + +type WorkflowRunEvent_Attestation struct { + Attestation *WorkflowRunEvent_AttestationAttributes `protobuf:"bytes,10,opt,name=attestation,proto3,oneof"` +} + +type WorkflowRunEvent_Material struct { + Material *WorkflowRunEvent_MaterialAttributes `protobuf:"bytes,11,opt,name=material,proto3,oneof"` +} + +func (*WorkflowRunEvent_Attestation) isWorkflowRunEvent_Attributes() {} + +func (*WorkflowRunEvent_Material) isWorkflowRunEvent_Attributes() {} + +type WorkflowRunServiceListRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + // Filters + // by workflow + WorkflowName string `protobuf:"bytes,1,opt,name=workflow_name,json=workflowName,proto3" json:"workflow_name,omitempty"` + // Not required since filtering by workflow and project is optional + ProjectName string `protobuf:"bytes,4,opt,name=project_name,json=projectName,proto3" json:"project_name,omitempty"` + // by run status + Status RunStatus `protobuf:"varint,3,opt,name=status,proto3,enum=controlplane.v1.RunStatus" json:"status,omitempty"` + // by project version (UUID). + // Deprecated: use project_version_name together with project_name. A version + // name is unique only within a project, so filtering by name is the canonical + // and discoverable path; the UUID is kept for backward compatibility. + // + // Deprecated: Marked as deprecated in controlplane/v1/workflow_run.proto. + ProjectVersion string `protobuf:"bytes,5,opt,name=project_version,json=projectVersion,proto3" json:"project_version,omitempty"` + // by project version name (e.g. v1.2.0). Requires project_name, since a + // version name is unique only within a project. + ProjectVersionName string `protobuf:"bytes,9,opt,name=project_version_name,json=projectVersionName,proto3" json:"project_version_name,omitempty"` + // by policy violations status + // Deprecated: use policy_status (PolicyStatusFilter), which aligns 1:1 with + // the canonical PolicyStatus enum. When both are set, policy_status wins. + // + // Deprecated: Marked as deprecated in controlplane/v1/workflow_run.proto. + PolicyViolations PolicyViolationsFilter `protobuf:"varint,6,opt,name=policy_violations,json=policyViolations,proto3,enum=controlplane.v1.PolicyViolationsFilter" json:"policy_violations,omitempty"` + // by canonical policy status + PolicyStatus PolicyStatusFilter `protobuf:"varint,7,opt,name=policy_status,json=policyStatus,proto3,enum=controlplane.v1.PolicyStatusFilter" json:"policy_status,omitempty"` + // by whether the run had gates in effect (either a policy marked gate:true + // or the contract using the ENFORCED blocking strategy) + PolicyGates PolicyGatesFilter `protobuf:"varint,8,opt,name=policy_gates,json=policyGates,proto3,enum=controlplane.v1.PolicyGatesFilter" json:"policy_gates,omitempty"` + // pagination options + Pagination *CursorPaginationRequest `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *WorkflowRunServiceListRequest) Reset() { + *x = WorkflowRunServiceListRequest{} + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[18] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *WorkflowRunServiceListRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WorkflowRunServiceListRequest) ProtoMessage() {} + +func (x *WorkflowRunServiceListRequest) ProtoReflect() protoreflect.Message { + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[18] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use WorkflowRunServiceListRequest.ProtoReflect.Descriptor instead. +func (*WorkflowRunServiceListRequest) Descriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{18} +} + +func (x *WorkflowRunServiceListRequest) GetWorkflowName() string { + if x != nil { + return x.WorkflowName + } + return "" +} + +func (x *WorkflowRunServiceListRequest) GetProjectName() string { + if x != nil { + return x.ProjectName + } + return "" +} + +func (x *WorkflowRunServiceListRequest) GetStatus() RunStatus { + if x != nil { + return x.Status + } + return RunStatus_RUN_STATUS_UNSPECIFIED +} + +// Deprecated: Marked as deprecated in controlplane/v1/workflow_run.proto. +func (x *WorkflowRunServiceListRequest) GetProjectVersion() string { + if x != nil { + return x.ProjectVersion + } + return "" +} + +func (x *WorkflowRunServiceListRequest) GetProjectVersionName() string { + if x != nil { + return x.ProjectVersionName + } + return "" +} + +// Deprecated: Marked as deprecated in controlplane/v1/workflow_run.proto. +func (x *WorkflowRunServiceListRequest) GetPolicyViolations() PolicyViolationsFilter { + if x != nil { + return x.PolicyViolations + } + return PolicyViolationsFilter_POLICY_VIOLATIONS_FILTER_UNSPECIFIED +} + +func (x *WorkflowRunServiceListRequest) GetPolicyStatus() PolicyStatusFilter { + if x != nil { + return x.PolicyStatus + } + return PolicyStatusFilter_POLICY_STATUS_FILTER_UNSPECIFIED +} + +func (x *WorkflowRunServiceListRequest) GetPolicyGates() PolicyGatesFilter { + if x != nil { + return x.PolicyGates + } + return PolicyGatesFilter_POLICY_GATES_FILTER_UNSPECIFIED +} + +func (x *WorkflowRunServiceListRequest) GetPagination() *CursorPaginationRequest { + if x != nil { + return x.Pagination + } + return nil +} + +type WorkflowRunServiceListResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Result []*WorkflowRunItem `protobuf:"bytes,1,rep,name=result,proto3" json:"result,omitempty"` + Pagination *CursorPaginationResponse `protobuf:"bytes,2,opt,name=pagination,proto3" json:"pagination,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *WorkflowRunServiceListResponse) Reset() { + *x = WorkflowRunServiceListResponse{} + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[19] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *WorkflowRunServiceListResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WorkflowRunServiceListResponse) ProtoMessage() {} + +func (x *WorkflowRunServiceListResponse) ProtoReflect() protoreflect.Message { + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[19] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use WorkflowRunServiceListResponse.ProtoReflect.Descriptor instead. +func (*WorkflowRunServiceListResponse) Descriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{19} +} + +func (x *WorkflowRunServiceListResponse) GetResult() []*WorkflowRunItem { + if x != nil { + return x.Result + } + return nil +} + +func (x *WorkflowRunServiceListResponse) GetPagination() *CursorPaginationResponse { + if x != nil { + return x.Pagination + } + return nil +} + +type WorkflowRunServiceViewRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + // It can search by either ID or digest + // + // Types that are valid to be assigned to Ref: + // + // *WorkflowRunServiceViewRequest_Id + // *WorkflowRunServiceViewRequest_Digest Ref isWorkflowRunServiceViewRequest_Ref `protobuf_oneof:"ref"` // run verification Verify bool `protobuf:"varint,3,opt,name=verify,proto3" json:"verify,omitempty"` @@ -1150,21 +1645,410 @@ type WorkflowRunServiceViewRequest struct { sizeCache protoimpl.SizeCache } -func (x *WorkflowRunServiceViewRequest) Reset() { - *x = WorkflowRunServiceViewRequest{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[17] +func (x *WorkflowRunServiceViewRequest) Reset() { + *x = WorkflowRunServiceViewRequest{} + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[20] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *WorkflowRunServiceViewRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WorkflowRunServiceViewRequest) ProtoMessage() {} + +func (x *WorkflowRunServiceViewRequest) ProtoReflect() protoreflect.Message { + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[20] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use WorkflowRunServiceViewRequest.ProtoReflect.Descriptor instead. +func (*WorkflowRunServiceViewRequest) Descriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{20} +} + +func (x *WorkflowRunServiceViewRequest) GetRef() isWorkflowRunServiceViewRequest_Ref { + if x != nil { + return x.Ref + } + return nil +} + +func (x *WorkflowRunServiceViewRequest) GetId() string { + if x != nil { + if x, ok := x.Ref.(*WorkflowRunServiceViewRequest_Id); ok { + return x.Id + } + } + return "" +} + +func (x *WorkflowRunServiceViewRequest) GetDigest() string { + if x != nil { + if x, ok := x.Ref.(*WorkflowRunServiceViewRequest_Digest); ok { + return x.Digest + } + } + return "" +} + +func (x *WorkflowRunServiceViewRequest) GetVerify() bool { + if x != nil { + return x.Verify + } + return false +} + +type isWorkflowRunServiceViewRequest_Ref interface { + isWorkflowRunServiceViewRequest_Ref() +} + +type WorkflowRunServiceViewRequest_Id struct { + Id string `protobuf:"bytes,1,opt,name=id,proto3,oneof"` +} + +type WorkflowRunServiceViewRequest_Digest struct { + Digest string `protobuf:"bytes,2,opt,name=digest,proto3,oneof"` +} + +func (*WorkflowRunServiceViewRequest_Id) isWorkflowRunServiceViewRequest_Ref() {} + +func (*WorkflowRunServiceViewRequest_Digest) isWorkflowRunServiceViewRequest_Ref() {} + +type WorkflowRunServiceGetProgressRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + WorkflowRunId string `protobuf:"bytes,1,opt,name=workflow_run_id,json=workflowRunId,proto3" json:"workflow_run_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *WorkflowRunServiceGetProgressRequest) Reset() { + *x = WorkflowRunServiceGetProgressRequest{} + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[21] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *WorkflowRunServiceGetProgressRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WorkflowRunServiceGetProgressRequest) ProtoMessage() {} + +func (x *WorkflowRunServiceGetProgressRequest) ProtoReflect() protoreflect.Message { + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[21] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use WorkflowRunServiceGetProgressRequest.ProtoReflect.Descriptor instead. +func (*WorkflowRunServiceGetProgressRequest) Descriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{21} +} + +func (x *WorkflowRunServiceGetProgressRequest) GetWorkflowRunId() string { + if x != nil { + return x.WorkflowRunId + } + return "" +} + +type WorkflowRunServiceGetProgressResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + // Progress of a run in progress, built by the control plane from its events. + // Not set for a finished run: the signed attestation is the source then. + Progress *WorkflowRunProgress `protobuf:"bytes,1,opt,name=progress,proto3" json:"progress,omitempty"` + // Timeline of the run, oldest first. Reported data, never part of the attestation. + Events []*WorkflowRunEvent `protobuf:"bytes,2,rep,name=events,proto3" json:"events,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *WorkflowRunServiceGetProgressResponse) Reset() { + *x = WorkflowRunServiceGetProgressResponse{} + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[22] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *WorkflowRunServiceGetProgressResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WorkflowRunServiceGetProgressResponse) ProtoMessage() {} + +func (x *WorkflowRunServiceGetProgressResponse) ProtoReflect() protoreflect.Message { + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[22] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use WorkflowRunServiceGetProgressResponse.ProtoReflect.Descriptor instead. +func (*WorkflowRunServiceGetProgressResponse) Descriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{22} +} + +func (x *WorkflowRunServiceGetProgressResponse) GetProgress() *WorkflowRunProgress { + if x != nil { + return x.Progress + } + return nil +} + +func (x *WorkflowRunServiceGetProgressResponse) GetEvents() []*WorkflowRunEvent { + if x != nil { + return x.Events + } + return nil +} + +// The progress of a run in progress, ready to show +type WorkflowRunProgress struct { + state protoimpl.MessageState `protogen:"open.v1"` + // One row for each expected material, in contract order, then the materials not in the contract + Materials []*WorkflowRunProgress_Material `protobuf:"bytes,1,rep,name=materials,proto3" json:"materials,omitempty"` + // Required materials, where a group of materials counts once + RequiredTotal int32 `protobuf:"varint,2,opt,name=required_total,json=requiredTotal,proto3" json:"required_total,omitempty"` + RequiredProvided int32 `protobuf:"varint,3,opt,name=required_provided,json=requiredProvided,proto3" json:"required_provided,omitempty"` + // Results of the attestation policies evaluated at init + AttestationPolicies *WorkflowRunEvent_PolicyCounts `protobuf:"bytes,4,opt,name=attestation_policies,json=attestationPolicies,proto3" json:"attestation_policies,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *WorkflowRunProgress) Reset() { + *x = WorkflowRunProgress{} + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[23] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *WorkflowRunProgress) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WorkflowRunProgress) ProtoMessage() {} + +func (x *WorkflowRunProgress) ProtoReflect() protoreflect.Message { + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[23] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use WorkflowRunProgress.ProtoReflect.Descriptor instead. +func (*WorkflowRunProgress) Descriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{23} +} + +func (x *WorkflowRunProgress) GetMaterials() []*WorkflowRunProgress_Material { + if x != nil { + return x.Materials + } + return nil +} + +func (x *WorkflowRunProgress) GetRequiredTotal() int32 { + if x != nil { + return x.RequiredTotal + } + return 0 +} + +func (x *WorkflowRunProgress) GetRequiredProvided() int32 { + if x != nil { + return x.RequiredProvided + } + return 0 +} + +func (x *WorkflowRunProgress) GetAttestationPolicies() *WorkflowRunEvent_PolicyCounts { + if x != nil { + return x.AttestationPolicies + } + return nil +} + +type WorkflowRunServiceViewResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Result *WorkflowRunServiceViewResponse_Result `protobuf:"bytes,1,opt,name=result,proto3" json:"result,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *WorkflowRunServiceViewResponse) Reset() { + *x = WorkflowRunServiceViewResponse{} + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[24] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *WorkflowRunServiceViewResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WorkflowRunServiceViewResponse) ProtoMessage() {} + +func (x *WorkflowRunServiceViewResponse) ProtoReflect() protoreflect.Message { + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[24] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use WorkflowRunServiceViewResponse.ProtoReflect.Descriptor instead. +func (*WorkflowRunServiceViewResponse) Descriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{24} +} + +func (x *WorkflowRunServiceViewResponse) GetResult() *WorkflowRunServiceViewResponse_Result { + if x != nil { + return x.Result + } + return nil +} + +type AttestationServiceGetUploadCredsRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + WorkflowRunId string `protobuf:"bytes,1,opt,name=workflow_run_id,json=workflowRunId,proto3" json:"workflow_run_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AttestationServiceGetUploadCredsRequest) Reset() { + *x = AttestationServiceGetUploadCredsRequest{} + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[25] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AttestationServiceGetUploadCredsRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AttestationServiceGetUploadCredsRequest) ProtoMessage() {} + +func (x *AttestationServiceGetUploadCredsRequest) ProtoReflect() protoreflect.Message { + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[25] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AttestationServiceGetUploadCredsRequest.ProtoReflect.Descriptor instead. +func (*AttestationServiceGetUploadCredsRequest) Descriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{25} +} + +func (x *AttestationServiceGetUploadCredsRequest) GetWorkflowRunId() string { + if x != nil { + return x.WorkflowRunId + } + return "" +} + +type AttestationServiceGetUploadCredsResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Result *AttestationServiceGetUploadCredsResponse_Result `protobuf:"bytes,1,opt,name=result,proto3" json:"result,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AttestationServiceGetUploadCredsResponse) Reset() { + *x = AttestationServiceGetUploadCredsResponse{} + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[26] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AttestationServiceGetUploadCredsResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AttestationServiceGetUploadCredsResponse) ProtoMessage() {} + +func (x *AttestationServiceGetUploadCredsResponse) ProtoReflect() protoreflect.Message { + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[26] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AttestationServiceGetUploadCredsResponse.ProtoReflect.Descriptor instead. +func (*AttestationServiceGetUploadCredsResponse) Descriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{26} +} + +func (x *AttestationServiceGetUploadCredsResponse) GetResult() *AttestationServiceGetUploadCredsResponse_Result { + if x != nil { + return x.Result + } + return nil +} + +type AttestationServiceGetContractResponse_Result struct { + state protoimpl.MessageState `protogen:"open.v1"` + Workflow *WorkflowItem `protobuf:"bytes,1,opt,name=workflow,proto3" json:"workflow,omitempty"` + Contract *WorkflowContractVersionItem `protobuf:"bytes,2,opt,name=contract,proto3" json:"contract,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AttestationServiceGetContractResponse_Result) Reset() { + *x = AttestationServiceGetContractResponse_Result{} + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[27] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } -func (x *WorkflowRunServiceViewRequest) String() string { +func (x *AttestationServiceGetContractResponse_Result) String() string { return protoimpl.X.MessageStringOf(x) } -func (*WorkflowRunServiceViewRequest) ProtoMessage() {} +func (*AttestationServiceGetContractResponse_Result) ProtoMessage() {} -func (x *WorkflowRunServiceViewRequest) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[17] +func (x *AttestationServiceGetContractResponse_Result) ProtoReflect() protoreflect.Message { + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[27] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1175,81 +2059,167 @@ func (x *WorkflowRunServiceViewRequest) ProtoReflect() protoreflect.Message { return mi.MessageOf(x) } -// Deprecated: Use WorkflowRunServiceViewRequest.ProtoReflect.Descriptor instead. -func (*WorkflowRunServiceViewRequest) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{17} +// Deprecated: Use AttestationServiceGetContractResponse_Result.ProtoReflect.Descriptor instead. +func (*AttestationServiceGetContractResponse_Result) Descriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{8, 0} } -func (x *WorkflowRunServiceViewRequest) GetRef() isWorkflowRunServiceViewRequest_Ref { +func (x *AttestationServiceGetContractResponse_Result) GetWorkflow() *WorkflowItem { if x != nil { - return x.Ref + return x.Workflow } return nil } -func (x *WorkflowRunServiceViewRequest) GetId() string { +func (x *AttestationServiceGetContractResponse_Result) GetContract() *WorkflowContractVersionItem { if x != nil { - if x, ok := x.Ref.(*WorkflowRunServiceViewRequest_Id); ok { - return x.Id - } + return x.Contract } - return "" + return nil } -func (x *WorkflowRunServiceViewRequest) GetDigest() string { +type AttestationServiceInitResponse_Result struct { + state protoimpl.MessageState `protogen:"open.v1"` + WorkflowRun *WorkflowRunItem `protobuf:"bytes,2,opt,name=workflow_run,json=workflowRun,proto3" json:"workflow_run,omitempty"` + // organization name + Organization string `protobuf:"bytes,3,opt,name=organization,proto3" json:"organization,omitempty"` + // fail the attestation if there is a violation in any policy + BlockOnPolicyViolation bool `protobuf:"varint,4,opt,name=block_on_policy_violation,json=blockOnPolicyViolation,proto3" json:"block_on_policy_violation,omitempty"` + // Signing options + SigningOptions *AttestationServiceInitResponse_SigningOptions `protobuf:"bytes,5,opt,name=signing_options,json=signingOptions,proto3" json:"signing_options,omitempty"` + // array of hostnames that are allowed to be used in the policies + PoliciesAllowedHostnames []string `protobuf:"bytes,6,rep,name=policies_allowed_hostnames,json=policiesAllowedHostnames,proto3" json:"policies_allowed_hostnames,omitempty"` + // URL pointing to the web dashboard. It might be empty if not available + UiDashboardUrl string `protobuf:"bytes,7,opt,name=ui_dashboard_url,json=uiDashboardUrl,proto3" json:"ui_dashboard_url,omitempty"` + // Whether AI agent config collection is enabled at the org level + EnableAiAgentCollector bool `protobuf:"varint,8,opt,name=enable_ai_agent_collector,json=enableAiAgentCollector,proto3" json:"enable_ai_agent_collector,omitempty"` + // Whether to skip storing the environment variables automatically discovered by the CI runner in the attestation + SkipRunnerEnvVars bool `protobuf:"varint,9,opt,name=skip_runner_env_vars,json=skipRunnerEnvVars,proto3" json:"skip_runner_env_vars,omitempty"` + // Names of the environment variables whose values the CLI replaces with "[REDACTED]". + // The control plane resolves them from the org setting and enforces the same list at push. + RedactedEnvVars []string `protobuf:"bytes,10,rep,name=redacted_env_vars,json=redactedEnvVars,proto3" json:"redacted_env_vars,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AttestationServiceInitResponse_Result) Reset() { + *x = AttestationServiceInitResponse_Result{} + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[28] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AttestationServiceInitResponse_Result) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AttestationServiceInitResponse_Result) ProtoMessage() {} + +func (x *AttestationServiceInitResponse_Result) ProtoReflect() protoreflect.Message { + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[28] if x != nil { - if x, ok := x.Ref.(*WorkflowRunServiceViewRequest_Digest); ok { - return x.Digest + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AttestationServiceInitResponse_Result.ProtoReflect.Descriptor instead. +func (*AttestationServiceInitResponse_Result) Descriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{10, 0} +} + +func (x *AttestationServiceInitResponse_Result) GetWorkflowRun() *WorkflowRunItem { + if x != nil { + return x.WorkflowRun + } + return nil +} + +func (x *AttestationServiceInitResponse_Result) GetOrganization() string { + if x != nil { + return x.Organization } return "" } -func (x *WorkflowRunServiceViewRequest) GetVerify() bool { +func (x *AttestationServiceInitResponse_Result) GetBlockOnPolicyViolation() bool { if x != nil { - return x.Verify + return x.BlockOnPolicyViolation } return false } -type isWorkflowRunServiceViewRequest_Ref interface { - isWorkflowRunServiceViewRequest_Ref() +func (x *AttestationServiceInitResponse_Result) GetSigningOptions() *AttestationServiceInitResponse_SigningOptions { + if x != nil { + return x.SigningOptions + } + return nil } -type WorkflowRunServiceViewRequest_Id struct { - Id string `protobuf:"bytes,1,opt,name=id,proto3,oneof"` +func (x *AttestationServiceInitResponse_Result) GetPoliciesAllowedHostnames() []string { + if x != nil { + return x.PoliciesAllowedHostnames + } + return nil } -type WorkflowRunServiceViewRequest_Digest struct { - Digest string `protobuf:"bytes,2,opt,name=digest,proto3,oneof"` +func (x *AttestationServiceInitResponse_Result) GetUiDashboardUrl() string { + if x != nil { + return x.UiDashboardUrl + } + return "" } -func (*WorkflowRunServiceViewRequest_Id) isWorkflowRunServiceViewRequest_Ref() {} +func (x *AttestationServiceInitResponse_Result) GetEnableAiAgentCollector() bool { + if x != nil { + return x.EnableAiAgentCollector + } + return false +} -func (*WorkflowRunServiceViewRequest_Digest) isWorkflowRunServiceViewRequest_Ref() {} +func (x *AttestationServiceInitResponse_Result) GetSkipRunnerEnvVars() bool { + if x != nil { + return x.SkipRunnerEnvVars + } + return false +} -type WorkflowRunServiceViewResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Result *WorkflowRunServiceViewResponse_Result `protobuf:"bytes,1,opt,name=result,proto3" json:"result,omitempty"` +func (x *AttestationServiceInitResponse_Result) GetRedactedEnvVars() []string { + if x != nil { + return x.RedactedEnvVars + } + return nil +} + +type AttestationServiceInitResponse_SigningOptions struct { + state protoimpl.MessageState `protogen:"open.v1"` + // TSA service to be used for signing + TimestampAuthorityUrl string `protobuf:"bytes,1,opt,name=timestamp_authority_url,json=timestampAuthorityUrl,proto3" json:"timestamp_authority_url,omitempty"` + // If set, the attestation wil be signed with ephemeral certificates issued by this CA + SigningCa string `protobuf:"bytes,2,opt,name=signing_ca,json=signingCa,proto3" json:"signing_ca,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } -func (x *WorkflowRunServiceViewResponse) Reset() { - *x = WorkflowRunServiceViewResponse{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[18] +func (x *AttestationServiceInitResponse_SigningOptions) Reset() { + *x = AttestationServiceInitResponse_SigningOptions{} + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[29] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } -func (x *WorkflowRunServiceViewResponse) String() string { +func (x *AttestationServiceInitResponse_SigningOptions) String() string { return protoimpl.X.MessageStringOf(x) } -func (*WorkflowRunServiceViewResponse) ProtoMessage() {} +func (*AttestationServiceInitResponse_SigningOptions) ProtoMessage() {} -func (x *WorkflowRunServiceViewResponse) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[18] +func (x *AttestationServiceInitResponse_SigningOptions) ProtoReflect() protoreflect.Message { + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[29] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1260,40 +2230,48 @@ func (x *WorkflowRunServiceViewResponse) ProtoReflect() protoreflect.Message { return mi.MessageOf(x) } -// Deprecated: Use WorkflowRunServiceViewResponse.ProtoReflect.Descriptor instead. -func (*WorkflowRunServiceViewResponse) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{18} +// Deprecated: Use AttestationServiceInitResponse_SigningOptions.ProtoReflect.Descriptor instead. +func (*AttestationServiceInitResponse_SigningOptions) Descriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{10, 1} } -func (x *WorkflowRunServiceViewResponse) GetResult() *WorkflowRunServiceViewResponse_Result { +func (x *AttestationServiceInitResponse_SigningOptions) GetTimestampAuthorityUrl() string { if x != nil { - return x.Result + return x.TimestampAuthorityUrl } - return nil + return "" } -type AttestationServiceGetUploadCredsRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - WorkflowRunId string `protobuf:"bytes,1,opt,name=workflow_run_id,json=workflowRunId,proto3" json:"workflow_run_id,omitempty"` +func (x *AttestationServiceInitResponse_SigningOptions) GetSigningCa() string { + if x != nil { + return x.SigningCa + } + return "" +} + +type AttestationServiceStoreResponse_Result struct { + state protoimpl.MessageState `protogen:"open.v1"` + // attestation digest + Digest string `protobuf:"bytes,2,opt,name=digest,proto3" json:"digest,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } -func (x *AttestationServiceGetUploadCredsRequest) Reset() { - *x = AttestationServiceGetUploadCredsRequest{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[19] +func (x *AttestationServiceStoreResponse_Result) Reset() { + *x = AttestationServiceStoreResponse_Result{} + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[30] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } -func (x *AttestationServiceGetUploadCredsRequest) String() string { +func (x *AttestationServiceStoreResponse_Result) String() string { return protoimpl.X.MessageStringOf(x) } -func (*AttestationServiceGetUploadCredsRequest) ProtoMessage() {} +func (*AttestationServiceStoreResponse_Result) ProtoMessage() {} -func (x *AttestationServiceGetUploadCredsRequest) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[19] +func (x *AttestationServiceStoreResponse_Result) ProtoReflect() protoreflect.Message { + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[30] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1304,85 +2282,147 @@ func (x *AttestationServiceGetUploadCredsRequest) ProtoReflect() protoreflect.Me return mi.MessageOf(x) } -// Deprecated: Use AttestationServiceGetUploadCredsRequest.ProtoReflect.Descriptor instead. -func (*AttestationServiceGetUploadCredsRequest) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{19} +// Deprecated: Use AttestationServiceStoreResponse_Result.ProtoReflect.Descriptor instead. +func (*AttestationServiceStoreResponse_Result) Descriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{12, 0} +} + +func (x *AttestationServiceStoreResponse_Result) GetDigest() string { + if x != nil { + return x.Digest + } + return "" +} + +type WorkflowRunEvent_AttestationAttributes struct { + state protoimpl.MessageState `protogen:"open.v1"` + ContractName string `protobuf:"bytes,1,opt,name=contract_name,json=contractName,proto3" json:"contract_name,omitempty"` + ContractRevision int32 `protobuf:"varint,2,opt,name=contract_revision,json=contractRevision,proto3" json:"contract_revision,omitempty"` + RunnerType string `protobuf:"bytes,3,opt,name=runner_type,json=runnerType,proto3" json:"runner_type,omitempty"` + RemoteState bool `protobuf:"varint,4,opt,name=remote_state,json=remoteState,proto3" json:"remote_state,omitempty"` + CliVersion string `protobuf:"bytes,5,opt,name=cli_version,json=cliVersion,proto3" json:"cli_version,omitempty"` + AttestationDigest string `protobuf:"bytes,6,opt,name=attestation_digest,json=attestationDigest,proto3" json:"attestation_digest,omitempty"` + // results of the attestation policies evaluated at init + Policies *WorkflowRunEvent_PolicyCounts `protobuf:"bytes,7,opt,name=policies,proto3" json:"policies,omitempty"` + // the materials that the attestation expects, from the contract and its policy groups, + // as init resolves them. Set on the start event. + ExpectedMaterials []*WorkflowRunEvent_ExpectedMaterial `protobuf:"bytes,8,rep,name=expected_materials,json=expectedMaterials,proto3" json:"expected_materials,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *WorkflowRunEvent_AttestationAttributes) Reset() { + *x = WorkflowRunEvent_AttestationAttributes{} + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[31] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *WorkflowRunEvent_AttestationAttributes) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WorkflowRunEvent_AttestationAttributes) ProtoMessage() {} + +func (x *WorkflowRunEvent_AttestationAttributes) ProtoReflect() protoreflect.Message { + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[31] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use WorkflowRunEvent_AttestationAttributes.ProtoReflect.Descriptor instead. +func (*WorkflowRunEvent_AttestationAttributes) Descriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{17, 0} +} + +func (x *WorkflowRunEvent_AttestationAttributes) GetContractName() string { + if x != nil { + return x.ContractName + } + return "" +} + +func (x *WorkflowRunEvent_AttestationAttributes) GetContractRevision() int32 { + if x != nil { + return x.ContractRevision + } + return 0 } -func (x *AttestationServiceGetUploadCredsRequest) GetWorkflowRunId() string { +func (x *WorkflowRunEvent_AttestationAttributes) GetRunnerType() string { if x != nil { - return x.WorkflowRunId + return x.RunnerType } return "" } -type AttestationServiceGetUploadCredsResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Result *AttestationServiceGetUploadCredsResponse_Result `protobuf:"bytes,1,opt,name=result,proto3" json:"result,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *AttestationServiceGetUploadCredsResponse) Reset() { - *x = AttestationServiceGetUploadCredsResponse{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[20] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) +func (x *WorkflowRunEvent_AttestationAttributes) GetRemoteState() bool { + if x != nil { + return x.RemoteState + } + return false } -func (x *AttestationServiceGetUploadCredsResponse) String() string { - return protoimpl.X.MessageStringOf(x) +func (x *WorkflowRunEvent_AttestationAttributes) GetCliVersion() string { + if x != nil { + return x.CliVersion + } + return "" } -func (*AttestationServiceGetUploadCredsResponse) ProtoMessage() {} - -func (x *AttestationServiceGetUploadCredsResponse) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[20] +func (x *WorkflowRunEvent_AttestationAttributes) GetAttestationDigest() string { if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms + return x.AttestationDigest } - return mi.MessageOf(x) + return "" } -// Deprecated: Use AttestationServiceGetUploadCredsResponse.ProtoReflect.Descriptor instead. -func (*AttestationServiceGetUploadCredsResponse) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{20} +func (x *WorkflowRunEvent_AttestationAttributes) GetPolicies() *WorkflowRunEvent_PolicyCounts { + if x != nil { + return x.Policies + } + return nil } -func (x *AttestationServiceGetUploadCredsResponse) GetResult() *AttestationServiceGetUploadCredsResponse_Result { +func (x *WorkflowRunEvent_AttestationAttributes) GetExpectedMaterials() []*WorkflowRunEvent_ExpectedMaterial { if x != nil { - return x.Result + return x.ExpectedMaterials } return nil } -type AttestationServiceGetContractResponse_Result struct { - state protoimpl.MessageState `protogen:"open.v1"` - Workflow *WorkflowItem `protobuf:"bytes,1,opt,name=workflow,proto3" json:"workflow,omitempty"` - Contract *WorkflowContractVersionItem `protobuf:"bytes,2,opt,name=contract,proto3" json:"contract,omitempty"` +type WorkflowRunEvent_ExpectedMaterial struct { + state protoimpl.MessageState `protogen:"open.v1"` + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + MaterialType string `protobuf:"bytes,2,opt,name=material_type,json=materialType,proto3" json:"material_type,omitempty"` + Optional bool `protobuf:"varint,3,opt,name=optional,proto3" json:"optional,omitempty"` + // set when the material is one of a group, of which one is required + Group string `protobuf:"bytes,4,opt,name=group,proto3" json:"group,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } -func (x *AttestationServiceGetContractResponse_Result) Reset() { - *x = AttestationServiceGetContractResponse_Result{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[21] +func (x *WorkflowRunEvent_ExpectedMaterial) Reset() { + *x = WorkflowRunEvent_ExpectedMaterial{} + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[32] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } -func (x *AttestationServiceGetContractResponse_Result) String() string { +func (x *WorkflowRunEvent_ExpectedMaterial) String() string { return protoimpl.X.MessageStringOf(x) } -func (*AttestationServiceGetContractResponse_Result) ProtoMessage() {} +func (*WorkflowRunEvent_ExpectedMaterial) ProtoMessage() {} -func (x *AttestationServiceGetContractResponse_Result) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[21] +func (x *WorkflowRunEvent_ExpectedMaterial) ProtoReflect() protoreflect.Message { + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[32] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1393,64 +2433,68 @@ func (x *AttestationServiceGetContractResponse_Result) ProtoReflect() protorefle return mi.MessageOf(x) } -// Deprecated: Use AttestationServiceGetContractResponse_Result.ProtoReflect.Descriptor instead. -func (*AttestationServiceGetContractResponse_Result) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{8, 0} +// Deprecated: Use WorkflowRunEvent_ExpectedMaterial.ProtoReflect.Descriptor instead. +func (*WorkflowRunEvent_ExpectedMaterial) Descriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{17, 1} } -func (x *AttestationServiceGetContractResponse_Result) GetWorkflow() *WorkflowItem { +func (x *WorkflowRunEvent_ExpectedMaterial) GetName() string { if x != nil { - return x.Workflow + return x.Name } - return nil + return "" } -func (x *AttestationServiceGetContractResponse_Result) GetContract() *WorkflowContractVersionItem { +func (x *WorkflowRunEvent_ExpectedMaterial) GetMaterialType() string { if x != nil { - return x.Contract + return x.MaterialType } - return nil + return "" } -type AttestationServiceInitResponse_Result struct { - state protoimpl.MessageState `protogen:"open.v1"` - WorkflowRun *WorkflowRunItem `protobuf:"bytes,2,opt,name=workflow_run,json=workflowRun,proto3" json:"workflow_run,omitempty"` - // organization name - Organization string `protobuf:"bytes,3,opt,name=organization,proto3" json:"organization,omitempty"` - // fail the attestation if there is a violation in any policy - BlockOnPolicyViolation bool `protobuf:"varint,4,opt,name=block_on_policy_violation,json=blockOnPolicyViolation,proto3" json:"block_on_policy_violation,omitempty"` - // Signing options - SigningOptions *AttestationServiceInitResponse_SigningOptions `protobuf:"bytes,5,opt,name=signing_options,json=signingOptions,proto3" json:"signing_options,omitempty"` - // array of hostnames that are allowed to be used in the policies - PoliciesAllowedHostnames []string `protobuf:"bytes,6,rep,name=policies_allowed_hostnames,json=policiesAllowedHostnames,proto3" json:"policies_allowed_hostnames,omitempty"` - // URL pointing to the web dashboard. It might be empty if not available - UiDashboardUrl string `protobuf:"bytes,7,opt,name=ui_dashboard_url,json=uiDashboardUrl,proto3" json:"ui_dashboard_url,omitempty"` - // Whether AI agent config collection is enabled at the org level - EnableAiAgentCollector bool `protobuf:"varint,8,opt,name=enable_ai_agent_collector,json=enableAiAgentCollector,proto3" json:"enable_ai_agent_collector,omitempty"` - // Whether to skip storing the environment variables automatically discovered by the CI runner in the attestation - SkipRunnerEnvVars bool `protobuf:"varint,9,opt,name=skip_runner_env_vars,json=skipRunnerEnvVars,proto3" json:"skip_runner_env_vars,omitempty"` - // Names of the environment variables whose values the CLI replaces with "[REDACTED]". - // The control plane resolves them from the org setting and enforces the same list at push. - RedactedEnvVars []string `protobuf:"bytes,10,rep,name=redacted_env_vars,json=redactedEnvVars,proto3" json:"redacted_env_vars,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache +func (x *WorkflowRunEvent_ExpectedMaterial) GetOptional() bool { + if x != nil { + return x.Optional + } + return false } -func (x *AttestationServiceInitResponse_Result) Reset() { - *x = AttestationServiceInitResponse_Result{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[22] +func (x *WorkflowRunEvent_ExpectedMaterial) GetGroup() string { + if x != nil { + return x.Group + } + return "" +} + +type WorkflowRunEvent_MaterialAttributes struct { + state protoimpl.MessageState `protogen:"open.v1"` + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + MaterialType string `protobuf:"bytes,2,opt,name=material_type,json=materialType,proto3" json:"material_type,omitempty"` + // value shown by attestation status, cut to 256 characters + Value string `protobuf:"bytes,3,opt,name=value,proto3" json:"value,omitempty"` + Digest string `protobuf:"bytes,4,opt,name=digest,proto3" json:"digest,omitempty"` + InContract bool `protobuf:"varint,5,opt,name=in_contract,json=inContract,proto3" json:"in_contract,omitempty"` + AddedByCollector bool `protobuf:"varint,6,opt,name=added_by_collector,json=addedByCollector,proto3" json:"added_by_collector,omitempty"` + Policies *WorkflowRunEvent_PolicyCounts `protobuf:"bytes,7,opt,name=policies,proto3" json:"policies,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *WorkflowRunEvent_MaterialAttributes) Reset() { + *x = WorkflowRunEvent_MaterialAttributes{} + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[33] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } -func (x *AttestationServiceInitResponse_Result) String() string { +func (x *WorkflowRunEvent_MaterialAttributes) String() string { return protoimpl.X.MessageStringOf(x) } -func (*AttestationServiceInitResponse_Result) ProtoMessage() {} +func (*WorkflowRunEvent_MaterialAttributes) ProtoMessage() {} -func (x *AttestationServiceInitResponse_Result) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[22] +func (x *WorkflowRunEvent_MaterialAttributes) ProtoReflect() protoreflect.Message { + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[33] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1461,99 +2505,86 @@ func (x *AttestationServiceInitResponse_Result) ProtoReflect() protoreflect.Mess return mi.MessageOf(x) } -// Deprecated: Use AttestationServiceInitResponse_Result.ProtoReflect.Descriptor instead. -func (*AttestationServiceInitResponse_Result) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{10, 0} -} - -func (x *AttestationServiceInitResponse_Result) GetWorkflowRun() *WorkflowRunItem { - if x != nil { - return x.WorkflowRun - } - return nil +// Deprecated: Use WorkflowRunEvent_MaterialAttributes.ProtoReflect.Descriptor instead. +func (*WorkflowRunEvent_MaterialAttributes) Descriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{17, 2} } -func (x *AttestationServiceInitResponse_Result) GetOrganization() string { +func (x *WorkflowRunEvent_MaterialAttributes) GetName() string { if x != nil { - return x.Organization + return x.Name } return "" } -func (x *AttestationServiceInitResponse_Result) GetBlockOnPolicyViolation() bool { - if x != nil { - return x.BlockOnPolicyViolation - } - return false -} - -func (x *AttestationServiceInitResponse_Result) GetSigningOptions() *AttestationServiceInitResponse_SigningOptions { +func (x *WorkflowRunEvent_MaterialAttributes) GetMaterialType() string { if x != nil { - return x.SigningOptions + return x.MaterialType } - return nil + return "" } -func (x *AttestationServiceInitResponse_Result) GetPoliciesAllowedHostnames() []string { +func (x *WorkflowRunEvent_MaterialAttributes) GetValue() string { if x != nil { - return x.PoliciesAllowedHostnames + return x.Value } - return nil + return "" } -func (x *AttestationServiceInitResponse_Result) GetUiDashboardUrl() string { +func (x *WorkflowRunEvent_MaterialAttributes) GetDigest() string { if x != nil { - return x.UiDashboardUrl + return x.Digest } return "" } -func (x *AttestationServiceInitResponse_Result) GetEnableAiAgentCollector() bool { +func (x *WorkflowRunEvent_MaterialAttributes) GetInContract() bool { if x != nil { - return x.EnableAiAgentCollector + return x.InContract } return false } -func (x *AttestationServiceInitResponse_Result) GetSkipRunnerEnvVars() bool { +func (x *WorkflowRunEvent_MaterialAttributes) GetAddedByCollector() bool { if x != nil { - return x.SkipRunnerEnvVars + return x.AddedByCollector } return false } -func (x *AttestationServiceInitResponse_Result) GetRedactedEnvVars() []string { +func (x *WorkflowRunEvent_MaterialAttributes) GetPolicies() *WorkflowRunEvent_PolicyCounts { if x != nil { - return x.RedactedEnvVars + return x.Policies } return nil } -type AttestationServiceInitResponse_SigningOptions struct { - state protoimpl.MessageState `protogen:"open.v1"` - // TSA service to be used for signing - TimestampAuthorityUrl string `protobuf:"bytes,1,opt,name=timestamp_authority_url,json=timestampAuthorityUrl,proto3" json:"timestamp_authority_url,omitempty"` - // If set, the attestation wil be signed with ephemeral certificates issued by this CA - SigningCa string `protobuf:"bytes,2,opt,name=signing_ca,json=signingCa,proto3" json:"signing_ca,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache +type WorkflowRunEvent_PolicyCounts struct { + state protoimpl.MessageState `protogen:"open.v1"` + Evaluated int32 `protobuf:"varint,1,opt,name=evaluated,proto3" json:"evaluated,omitempty"` + Passed int32 `protobuf:"varint,2,opt,name=passed,proto3" json:"passed,omitempty"` + Violated int32 `protobuf:"varint,3,opt,name=violated,proto3" json:"violated,omitempty"` + Skipped int32 `protobuf:"varint,4,opt,name=skipped,proto3" json:"skipped,omitempty"` + ViolatedPolicies []string `protobuf:"bytes,5,rep,name=violated_policies,json=violatedPolicies,proto3" json:"violated_policies,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } -func (x *AttestationServiceInitResponse_SigningOptions) Reset() { - *x = AttestationServiceInitResponse_SigningOptions{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[23] +func (x *WorkflowRunEvent_PolicyCounts) Reset() { + *x = WorkflowRunEvent_PolicyCounts{} + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[34] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } -func (x *AttestationServiceInitResponse_SigningOptions) String() string { +func (x *WorkflowRunEvent_PolicyCounts) String() string { return protoimpl.X.MessageStringOf(x) } -func (*AttestationServiceInitResponse_SigningOptions) ProtoMessage() {} +func (*WorkflowRunEvent_PolicyCounts) ProtoMessage() {} -func (x *AttestationServiceInitResponse_SigningOptions) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[23] +func (x *WorkflowRunEvent_PolicyCounts) ProtoReflect() protoreflect.Message { + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[34] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1564,48 +2595,79 @@ func (x *AttestationServiceInitResponse_SigningOptions) ProtoReflect() protorefl return mi.MessageOf(x) } -// Deprecated: Use AttestationServiceInitResponse_SigningOptions.ProtoReflect.Descriptor instead. -func (*AttestationServiceInitResponse_SigningOptions) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{10, 1} +// Deprecated: Use WorkflowRunEvent_PolicyCounts.ProtoReflect.Descriptor instead. +func (*WorkflowRunEvent_PolicyCounts) Descriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{17, 3} } -func (x *AttestationServiceInitResponse_SigningOptions) GetTimestampAuthorityUrl() string { +func (x *WorkflowRunEvent_PolicyCounts) GetEvaluated() int32 { if x != nil { - return x.TimestampAuthorityUrl + return x.Evaluated } - return "" + return 0 } -func (x *AttestationServiceInitResponse_SigningOptions) GetSigningCa() string { +func (x *WorkflowRunEvent_PolicyCounts) GetPassed() int32 { if x != nil { - return x.SigningCa + return x.Passed } - return "" + return 0 } -type AttestationServiceStoreResponse_Result struct { - state protoimpl.MessageState `protogen:"open.v1"` - // attestation digest - Digest string `protobuf:"bytes,2,opt,name=digest,proto3" json:"digest,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache +func (x *WorkflowRunEvent_PolicyCounts) GetViolated() int32 { + if x != nil { + return x.Violated + } + return 0 } -func (x *AttestationServiceStoreResponse_Result) Reset() { - *x = AttestationServiceStoreResponse_Result{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[24] +func (x *WorkflowRunEvent_PolicyCounts) GetSkipped() int32 { + if x != nil { + return x.Skipped + } + return 0 +} + +func (x *WorkflowRunEvent_PolicyCounts) GetViolatedPolicies() []string { + if x != nil { + return x.ViolatedPolicies + } + return nil +} + +type WorkflowRunProgress_Material struct { + state protoimpl.MessageState `protogen:"open.v1"` + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + MaterialType string `protobuf:"bytes,2,opt,name=material_type,json=materialType,proto3" json:"material_type,omitempty"` + Requirement WorkflowRunProgress_Requirement `protobuf:"varint,3,opt,name=requirement,proto3,enum=controlplane.v1.WorkflowRunProgress_Requirement" json:"requirement,omitempty"` + // Set when the requirement is ONE_OF_GROUP + Group string `protobuf:"bytes,4,opt,name=group,proto3" json:"group,omitempty"` + Status WorkflowRunProgress_Status `protobuf:"varint,5,opt,name=status,proto3,enum=controlplane.v1.WorkflowRunProgress_Status" json:"status,omitempty"` + // Value and policy results of the last successful add + Value string `protobuf:"bytes,6,opt,name=value,proto3" json:"value,omitempty"` + Policies *WorkflowRunEvent_PolicyCounts `protobuf:"bytes,7,opt,name=policies,proto3" json:"policies,omitempty"` + // Error of the last failed add, also after a successful one + LastError string `protobuf:"bytes,8,opt,name=last_error,json=lastError,proto3" json:"last_error,omitempty"` + FailedAttempts int32 `protobuf:"varint,9,opt,name=failed_attempts,json=failedAttempts,proto3" json:"failed_attempts,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *WorkflowRunProgress_Material) Reset() { + *x = WorkflowRunProgress_Material{} + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[35] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } -func (x *AttestationServiceStoreResponse_Result) String() string { +func (x *WorkflowRunProgress_Material) String() string { return protoimpl.X.MessageStringOf(x) } -func (*AttestationServiceStoreResponse_Result) ProtoMessage() {} +func (*WorkflowRunProgress_Material) ProtoMessage() {} -func (x *AttestationServiceStoreResponse_Result) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[24] +func (x *WorkflowRunProgress_Material) ProtoReflect() protoreflect.Message { + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[35] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1616,18 +2678,74 @@ func (x *AttestationServiceStoreResponse_Result) ProtoReflect() protoreflect.Mes return mi.MessageOf(x) } -// Deprecated: Use AttestationServiceStoreResponse_Result.ProtoReflect.Descriptor instead. -func (*AttestationServiceStoreResponse_Result) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{12, 0} +// Deprecated: Use WorkflowRunProgress_Material.ProtoReflect.Descriptor instead. +func (*WorkflowRunProgress_Material) Descriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{23, 0} } -func (x *AttestationServiceStoreResponse_Result) GetDigest() string { +func (x *WorkflowRunProgress_Material) GetName() string { if x != nil { - return x.Digest + return x.Name + } + return "" +} + +func (x *WorkflowRunProgress_Material) GetMaterialType() string { + if x != nil { + return x.MaterialType + } + return "" +} + +func (x *WorkflowRunProgress_Material) GetRequirement() WorkflowRunProgress_Requirement { + if x != nil { + return x.Requirement + } + return WorkflowRunProgress_REQUIREMENT_UNSPECIFIED +} + +func (x *WorkflowRunProgress_Material) GetGroup() string { + if x != nil { + return x.Group + } + return "" +} + +func (x *WorkflowRunProgress_Material) GetStatus() WorkflowRunProgress_Status { + if x != nil { + return x.Status + } + return WorkflowRunProgress_STATUS_UNSPECIFIED +} + +func (x *WorkflowRunProgress_Material) GetValue() string { + if x != nil { + return x.Value + } + return "" +} + +func (x *WorkflowRunProgress_Material) GetPolicies() *WorkflowRunEvent_PolicyCounts { + if x != nil { + return x.Policies + } + return nil +} + +func (x *WorkflowRunProgress_Material) GetLastError() string { + if x != nil { + return x.LastError } return "" } +func (x *WorkflowRunProgress_Material) GetFailedAttempts() int32 { + if x != nil { + return x.FailedAttempts + } + return 0 +} + type WorkflowRunServiceViewResponse_Result struct { state protoimpl.MessageState `protogen:"open.v1"` OrgName string `protobuf:"bytes,5,opt,name=org_name,json=orgName,proto3" json:"org_name,omitempty"` @@ -1641,7 +2759,7 @@ type WorkflowRunServiceViewResponse_Result struct { func (x *WorkflowRunServiceViewResponse_Result) Reset() { *x = WorkflowRunServiceViewResponse_Result{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[25] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[36] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1653,7 +2771,7 @@ func (x *WorkflowRunServiceViewResponse_Result) String() string { func (*WorkflowRunServiceViewResponse_Result) ProtoMessage() {} func (x *WorkflowRunServiceViewResponse_Result) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[25] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[36] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1666,7 +2784,7 @@ func (x *WorkflowRunServiceViewResponse_Result) ProtoReflect() protoreflect.Mess // Deprecated: Use WorkflowRunServiceViewResponse_Result.ProtoReflect.Descriptor instead. func (*WorkflowRunServiceViewResponse_Result) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{18, 0} + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{24, 0} } func (x *WorkflowRunServiceViewResponse_Result) GetOrgName() string { @@ -1709,7 +2827,7 @@ type WorkflowRunServiceViewResponse_VerificationResult struct { func (x *WorkflowRunServiceViewResponse_VerificationResult) Reset() { *x = WorkflowRunServiceViewResponse_VerificationResult{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[26] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[37] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1721,7 +2839,7 @@ func (x *WorkflowRunServiceViewResponse_VerificationResult) String() string { func (*WorkflowRunServiceViewResponse_VerificationResult) ProtoMessage() {} func (x *WorkflowRunServiceViewResponse_VerificationResult) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[26] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[37] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1734,7 +2852,7 @@ func (x *WorkflowRunServiceViewResponse_VerificationResult) ProtoReflect() proto // Deprecated: Use WorkflowRunServiceViewResponse_VerificationResult.ProtoReflect.Descriptor instead. func (*WorkflowRunServiceViewResponse_VerificationResult) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{18, 1} + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{24, 1} } func (x *WorkflowRunServiceViewResponse_VerificationResult) GetVerified() bool { @@ -1761,7 +2879,7 @@ type AttestationServiceGetUploadCredsResponse_Result struct { func (x *AttestationServiceGetUploadCredsResponse_Result) Reset() { *x = AttestationServiceGetUploadCredsResponse_Result{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[27] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[38] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1773,7 +2891,7 @@ func (x *AttestationServiceGetUploadCredsResponse_Result) String() string { func (*AttestationServiceGetUploadCredsResponse_Result) ProtoMessage() {} func (x *AttestationServiceGetUploadCredsResponse_Result) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[27] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[38] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1786,7 +2904,7 @@ func (x *AttestationServiceGetUploadCredsResponse_Result) ProtoReflect() protore // Deprecated: Use AttestationServiceGetUploadCredsResponse_Result.ProtoReflect.Descriptor instead. func (*AttestationServiceGetUploadCredsResponse_Result) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{20, 0} + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{26, 0} } func (x *AttestationServiceGetUploadCredsResponse_Result) GetToken() string { @@ -1807,7 +2925,7 @@ var File_controlplane_v1_workflow_run_proto protoreflect.FileDescriptor const file_controlplane_v1_workflow_run_proto_rawDesc = "" + "\n" + - "\"controlplane/v1/workflow_run.proto\x12\x0fcontrolplane.v1\x1a\x1bbuf/validate/validate.proto\x1a controlplane/v1/pagination.proto\x1a'controlplane/v1/response_messages.proto\x1a)workflowcontract/v1/crafting_schema.proto\"\xc3\x01\n" + + "\"controlplane/v1/workflow_run.proto\x12\x0fcontrolplane.v1\x1a\x1bbuf/validate/validate.proto\x1a controlplane/v1/pagination.proto\x1a'controlplane/v1/response_messages.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a)workflowcontract/v1/crafting_schema.proto\"\xc3\x01\n" + "\x1bFindOrCreateWorkflowRequest\x12,\n" + "\rworkflow_name\x18\x04 \x01(\tB\a\xbaH\x04r\x02\x10\x01R\fworkflowName\x12*\n" + "\fproject_name\x18\x05 \x01(\tB\a\xbaH\x04r\x02\x10\x01R\vprojectName\x12#\n" + @@ -1888,7 +3006,74 @@ const file_controlplane_v1_workflow_run_proto_rawDesc = "" + "\x18TRIGGER_TYPE_UNSPECIFIED\x10\x00\x12\x18\n" + "\x14TRIGGER_TYPE_FAILURE\x10\x01\x12\x1d\n" + "\x19TRIGGER_TYPE_CANCELLATION\x10\x02\"\"\n" + - " AttestationServiceCancelResponse\"\x83\b\n" + + " AttestationServiceCancelResponse\"\x99\x01\n" + + "$AttestationServiceRecordEventRequest\x120\n" + + "\x0fworkflow_run_id\x18\x01 \x01(\tB\b\xbaH\x05r\x03\xb0\x01\x01R\rworkflowRunId\x12?\n" + + "\x05event\x18\x02 \x01(\v2!.controlplane.v1.WorkflowRunEventB\x06\xbaH\x03\xc8\x01\x01R\x05event\"'\n" + + "%AttestationServiceRecordEventResponse\"\xd6\x0f\n" + + "\x10WorkflowRunEvent\x12\x0e\n" + + "\x02id\x18\x01 \x01(\tR\x02id\x129\n" + + "\n" + + "created_at\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\tcreatedAt\x12@\n" + + "\x06source\x18\x03 \x01(\x0e2(.controlplane.v1.WorkflowRunEvent.SourceR\x06source\x12F\n" + + "\x04type\x18\x04 \x01(\x0e2&.controlplane.v1.WorkflowRunEvent.TypeB\n" + + "\xbaH\a\x82\x01\x04\x10\x01 \x00R\x04type\x12\x1c\n" + + "\x03key\x18\x05 \x01(\tB\n" + + "\xbaH\ar\x05\x10\x01\x18\x80\x01R\x03key\x12L\n" + + "\x06status\x18\x06 \x01(\x0e2(.controlplane.v1.WorkflowRunEvent.StatusB\n" + + "\xbaH\a\x82\x01\x04\x10\x01 \x00R\x06status\x12\"\n" + + "\amessage\x18\a \x01(\tB\b\xbaH\x05r\x03(\x80\bR\amessage\x12[\n" + + "\vattestation\x18\n" + + " \x01(\v27.controlplane.v1.WorkflowRunEvent.AttestationAttributesH\x00R\vattestation\x12R\n" + + "\bmaterial\x18\v \x01(\v24.controlplane.v1.WorkflowRunEvent.MaterialAttributesH\x00R\bmaterial\x1a\xdf\x03\n" + + "\x15AttestationAttributes\x12-\n" + + "\rcontract_name\x18\x01 \x01(\tB\b\xbaH\x05r\x03\x18\x80\x02R\fcontractName\x12+\n" + + "\x11contract_revision\x18\x02 \x01(\x05R\x10contractRevision\x12)\n" + + "\vrunner_type\x18\x03 \x01(\tB\b\xbaH\x05r\x03\x18\x80\x02R\n" + + "runnerType\x12!\n" + + "\fremote_state\x18\x04 \x01(\bR\vremoteState\x12)\n" + + "\vcli_version\x18\x05 \x01(\tB\b\xbaH\x05r\x03\x18\x80\x02R\n" + + "cliVersion\x127\n" + + "\x12attestation_digest\x18\x06 \x01(\tB\b\xbaH\x05r\x03\x18\x80\x02R\x11attestationDigest\x12J\n" + + "\bpolicies\x18\a \x01(\v2..controlplane.v1.WorkflowRunEvent.PolicyCountsR\bpolicies\x12l\n" + + "\x12expected_materials\x18\b \x03(\v22.controlplane.v1.WorkflowRunEvent.ExpectedMaterialB\t\xbaH\x06\x92\x01\x03\x10\xe8\aR\x11expectedMaterials\x1a\x9b\x01\n" + + "\x10ExpectedMaterial\x12\x1c\n" + + "\x04name\x18\x01 \x01(\tB\b\xbaH\x05r\x03\x18\x80\x02R\x04name\x12-\n" + + "\rmaterial_type\x18\x02 \x01(\tB\b\xbaH\x05r\x03\x18\x80\x02R\fmaterialType\x12\x1a\n" + + "\boptional\x18\x03 \x01(\bR\boptional\x12\x1e\n" + + "\x05group\x18\x04 \x01(\tB\b\xbaH\x05r\x03\x18\x80\x02R\x05group\x1a\xbe\x02\n" + + "\x12MaterialAttributes\x12\x1c\n" + + "\x04name\x18\x01 \x01(\tB\b\xbaH\x05r\x03\x18\x80\x02R\x04name\x12-\n" + + "\rmaterial_type\x18\x02 \x01(\tB\b\xbaH\x05r\x03\x18\x80\x02R\fmaterialType\x12\x1e\n" + + "\x05value\x18\x03 \x01(\tB\b\xbaH\x05r\x03\x18\x80\x02R\x05value\x12 \n" + + "\x06digest\x18\x04 \x01(\tB\b\xbaH\x05r\x03\x18\x80\x02R\x06digest\x12\x1f\n" + + "\vin_contract\x18\x05 \x01(\bR\n" + + "inContract\x12,\n" + + "\x12added_by_collector\x18\x06 \x01(\bR\x10addedByCollector\x12J\n" + + "\bpolicies\x18\a \x01(\v2..controlplane.v1.WorkflowRunEvent.PolicyCountsR\bpolicies\x1a\xb8\x01\n" + + "\fPolicyCounts\x12\x1c\n" + + "\tevaluated\x18\x01 \x01(\x05R\tevaluated\x12\x16\n" + + "\x06passed\x18\x02 \x01(\x05R\x06passed\x12\x1a\n" + + "\bviolated\x18\x03 \x01(\x05R\bviolated\x12\x18\n" + + "\askipped\x18\x04 \x01(\x05R\askipped\x12<\n" + + "\x11violated_policies\x18\x05 \x03(\tB\x0f\xbaH\f\x92\x01\t\x10d\"\x05r\x03\x18\x80\x02R\x10violatedPolicies\"J\n" + + "\x06Source\x12\x16\n" + + "\x12SOURCE_UNSPECIFIED\x10\x00\x12\x0e\n" + + "\n" + + "SOURCE_CLI\x10\x01\x12\x18\n" + + "\x14SOURCE_CONTROL_PLANE\x10\x02\"V\n" + + "\x04Type\x12\x14\n" + + "\x10TYPE_UNSPECIFIED\x10\x00\x12\x14\n" + + "\x10TYPE_ATTESTATION\x10\x01\x12\x11\n" + + "\rTYPE_MATERIAL\x10\x02\"\x04\b\x03\x10\x03*\tTYPE_PUSH\"r\n" + + "\x06Status\x12\x16\n" + + "\x12STATUS_UNSPECIFIED\x10\x00\x12\x12\n" + + "\x0eSTATUS_STARTED\x10\x01\x12\x14\n" + + "\x10STATUS_SUCCEEDED\x10\x02\x12\x11\n" + + "\rSTATUS_FAILED\x10\x03\x12\x13\n" + + "\x0fSTATUS_CANCELED\x10\x04B\f\n" + + "\n" + + "attributesJ\x04\b\f\x10\rR\x04push\"\x83\b\n" + "\x1dWorkflowRunServiceListRequest\x12\xac\x01\n" + "\rworkflow_name\x18\x01 \x01(\tB\x86\x01\xbaH\x82\x01\xba\x01|\n" + "\rname.dns-1123\x12:must contain only lowercase letters, numbers, and hyphens.\x1a/this.matches('^[a-z0-9]([-a-z0-9]*[a-z0-9])?$')\xd8\x01\x01R\fworkflowName\x12!\n" + @@ -1913,7 +3098,39 @@ const file_controlplane_v1_workflow_run_proto_rawDesc = "" + "\x02id\x18\x01 \x01(\tB\b\xbaH\x05r\x03\xb0\x01\x01H\x00R\x02id\x12!\n" + "\x06digest\x18\x02 \x01(\tB\a\xbaH\x04r\x02\x10\x01H\x00R\x06digest\x12\x16\n" + "\x06verify\x18\x03 \x01(\bR\x06verifyB\f\n" + - "\x03ref\x12\x05\xbaH\x02\b\x01\"\xe0\x03\n" + + "\x03ref\x12\x05\xbaH\x02\b\x01\"X\n" + + "$WorkflowRunServiceGetProgressRequest\x120\n" + + "\x0fworkflow_run_id\x18\x01 \x01(\tB\b\xbaH\x05r\x03\xb0\x01\x01R\rworkflowRunId\"\xa4\x01\n" + + "%WorkflowRunServiceGetProgressResponse\x12@\n" + + "\bprogress\x18\x01 \x01(\v2$.controlplane.v1.WorkflowRunProgressR\bprogress\x129\n" + + "\x06events\x18\x02 \x03(\v2!.controlplane.v1.WorkflowRunEventR\x06events\"\xb6\a\n" + + "\x13WorkflowRunProgress\x12K\n" + + "\tmaterials\x18\x01 \x03(\v2-.controlplane.v1.WorkflowRunProgress.MaterialR\tmaterials\x12%\n" + + "\x0erequired_total\x18\x02 \x01(\x05R\rrequiredTotal\x12+\n" + + "\x11required_provided\x18\x03 \x01(\x05R\x10requiredProvided\x12a\n" + + "\x14attestation_policies\x18\x04 \x01(\v2..controlplane.v1.WorkflowRunEvent.PolicyCountsR\x13attestationPolicies\x1a\x9c\x03\n" + + "\bMaterial\x12\x12\n" + + "\x04name\x18\x01 \x01(\tR\x04name\x12#\n" + + "\rmaterial_type\x18\x02 \x01(\tR\fmaterialType\x12R\n" + + "\vrequirement\x18\x03 \x01(\x0e20.controlplane.v1.WorkflowRunProgress.RequirementR\vrequirement\x12\x14\n" + + "\x05group\x18\x04 \x01(\tR\x05group\x12C\n" + + "\x06status\x18\x05 \x01(\x0e2+.controlplane.v1.WorkflowRunProgress.StatusR\x06status\x12\x14\n" + + "\x05value\x18\x06 \x01(\tR\x05value\x12J\n" + + "\bpolicies\x18\a \x01(\v2..controlplane.v1.WorkflowRunEvent.PolicyCountsR\bpolicies\x12\x1d\n" + + "\n" + + "last_error\x18\b \x01(\tR\tlastError\x12'\n" + + "\x0ffailed_attempts\x18\t \x01(\x05R\x0efailedAttempts\"\x9d\x01\n" + + "\vRequirement\x12\x1b\n" + + "\x17REQUIREMENT_UNSPECIFIED\x10\x00\x12\x18\n" + + "\x14REQUIREMENT_REQUIRED\x10\x01\x12\x18\n" + + "\x14REQUIREMENT_OPTIONAL\x10\x02\x12\x1c\n" + + "\x18REQUIREMENT_ONE_OF_GROUP\x10\x03\x12\x1f\n" + + "\x1bREQUIREMENT_NOT_IN_CONTRACT\x10\x04\"\\\n" + + "\x06Status\x12\x16\n" + + "\x12STATUS_UNSPECIFIED\x10\x00\x12\x12\n" + + "\x0eSTATUS_MISSING\x10\x01\x12\x13\n" + + "\x0fSTATUS_PROVIDED\x10\x02\x12\x11\n" + + "\rSTATUS_FAILED\x10\x03\"\xe0\x03\n" + "\x1eWorkflowRunServiceViewResponse\x12N\n" + "\x06result\x18\x01 \x01(\v26.controlplane.v1.WorkflowRunServiceViewResponse.ResultR\x06result\x1a\x94\x02\n" + "\x06Result\x12\x19\n" + @@ -1930,19 +3147,21 @@ const file_controlplane_v1_workflow_run_proto_rawDesc = "" + "\x06result\x18\x01 \x01(\v2@.controlplane.v1.AttestationServiceGetUploadCredsResponse.ResultR\x06result\x1aY\n" + "\x06Result\x12\x14\n" + "\x05token\x18\x02 \x01(\tR\x05token\x129\n" + - "\abackend\x18\x03 \x01(\v2\x1f.controlplane.v1.CASBackendItemR\abackend2\xd3\a\n" + + "\abackend\x18\x03 \x01(\v2\x1f.controlplane.v1.CASBackendItemR\abackend2\xd1\b\n" + "\x12AttestationService\x12s\n" + "\x14FindOrCreateWorkflow\x12,.controlplane.v1.FindOrCreateWorkflowRequest\x1a-.controlplane.v1.FindOrCreateWorkflowResponse\x12|\n" + "\vGetContract\x125.controlplane.v1.AttestationServiceGetContractRequest\x1a6.controlplane.v1.AttestationServiceGetContractResponse\x12g\n" + "\x04Init\x12..controlplane.v1.AttestationServiceInitRequest\x1a/.controlplane.v1.AttestationServiceInitResponse\x12j\n" + "\x05Store\x12/.controlplane.v1.AttestationServiceStoreRequest\x1a0.controlplane.v1.AttestationServiceStoreResponse\x12\x85\x01\n" + "\x0eGetUploadCreds\x128.controlplane.v1.AttestationServiceGetUploadCredsRequest\x1a9.controlplane.v1.AttestationServiceGetUploadCredsResponse\x12m\n" + - "\x06Cancel\x120.controlplane.v1.AttestationServiceCancelRequest\x1a1.controlplane.v1.AttestationServiceCancelResponse\x12v\n" + + "\x06Cancel\x120.controlplane.v1.AttestationServiceCancelRequest\x1a1.controlplane.v1.AttestationServiceCancelResponse\x12|\n" + + "\vRecordEvent\x125.controlplane.v1.AttestationServiceRecordEventRequest\x1a6.controlplane.v1.AttestationServiceRecordEventResponse\x12v\n" + "\tGetPolicy\x123.controlplane.v1.AttestationServiceGetPolicyRequest\x1a4.controlplane.v1.AttestationServiceGetPolicyResponse\x12\x85\x01\n" + - "\x0eGetPolicyGroup\x128.controlplane.v1.AttestationServiceGetPolicyGroupRequest\x1a9.controlplane.v1.AttestationServiceGetPolicyGroupResponse2\xe6\x01\n" + + "\x0eGetPolicyGroup\x128.controlplane.v1.AttestationServiceGetPolicyGroupRequest\x1a9.controlplane.v1.AttestationServiceGetPolicyGroupResponse2\xe4\x02\n" + "\x12WorkflowRunService\x12g\n" + "\x04List\x12..controlplane.v1.WorkflowRunServiceListRequest\x1a/.controlplane.v1.WorkflowRunServiceListResponse\x12g\n" + - "\x04View\x12..controlplane.v1.WorkflowRunServiceViewRequest\x1a/.controlplane.v1.WorkflowRunServiceViewResponseBLZJgithub.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1;v1b\x06proto3" + "\x04View\x12..controlplane.v1.WorkflowRunServiceViewRequest\x1a/.controlplane.v1.WorkflowRunServiceViewResponse\x12|\n" + + "\vGetProgress\x125.controlplane.v1.WorkflowRunServiceGetProgressRequest\x1a6.controlplane.v1.WorkflowRunServiceGetProgressResponseBLZJgithub.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1;v1b\x06proto3" var ( file_controlplane_v1_workflow_run_proto_rawDescOnce sync.Once @@ -1956,106 +3175,144 @@ func file_controlplane_v1_workflow_run_proto_rawDescGZIP() []byte { return file_controlplane_v1_workflow_run_proto_rawDescData } -var file_controlplane_v1_workflow_run_proto_enumTypes = make([]protoimpl.EnumInfo, 1) -var file_controlplane_v1_workflow_run_proto_msgTypes = make([]protoimpl.MessageInfo, 28) +var file_controlplane_v1_workflow_run_proto_enumTypes = make([]protoimpl.EnumInfo, 6) +var file_controlplane_v1_workflow_run_proto_msgTypes = make([]protoimpl.MessageInfo, 39) var file_controlplane_v1_workflow_run_proto_goTypes = []any{ (AttestationServiceCancelRequest_TriggerType)(0), // 0: controlplane.v1.AttestationServiceCancelRequest.TriggerType - (*FindOrCreateWorkflowRequest)(nil), // 1: controlplane.v1.FindOrCreateWorkflowRequest - (*FindOrCreateWorkflowResponse)(nil), // 2: controlplane.v1.FindOrCreateWorkflowResponse - (*AttestationServiceGetPolicyRequest)(nil), // 3: controlplane.v1.AttestationServiceGetPolicyRequest - (*AttestationServiceGetPolicyResponse)(nil), // 4: controlplane.v1.AttestationServiceGetPolicyResponse - (*RemotePolicyReference)(nil), // 5: controlplane.v1.RemotePolicyReference - (*AttestationServiceGetPolicyGroupRequest)(nil), // 6: controlplane.v1.AttestationServiceGetPolicyGroupRequest - (*AttestationServiceGetPolicyGroupResponse)(nil), // 7: controlplane.v1.AttestationServiceGetPolicyGroupResponse - (*AttestationServiceGetContractRequest)(nil), // 8: controlplane.v1.AttestationServiceGetContractRequest - (*AttestationServiceGetContractResponse)(nil), // 9: controlplane.v1.AttestationServiceGetContractResponse - (*AttestationServiceInitRequest)(nil), // 10: controlplane.v1.AttestationServiceInitRequest - (*AttestationServiceInitResponse)(nil), // 11: controlplane.v1.AttestationServiceInitResponse - (*AttestationServiceStoreRequest)(nil), // 12: controlplane.v1.AttestationServiceStoreRequest - (*AttestationServiceStoreResponse)(nil), // 13: controlplane.v1.AttestationServiceStoreResponse - (*AttestationServiceCancelRequest)(nil), // 14: controlplane.v1.AttestationServiceCancelRequest - (*AttestationServiceCancelResponse)(nil), // 15: controlplane.v1.AttestationServiceCancelResponse - (*WorkflowRunServiceListRequest)(nil), // 16: controlplane.v1.WorkflowRunServiceListRequest - (*WorkflowRunServiceListResponse)(nil), // 17: controlplane.v1.WorkflowRunServiceListResponse - (*WorkflowRunServiceViewRequest)(nil), // 18: controlplane.v1.WorkflowRunServiceViewRequest - (*WorkflowRunServiceViewResponse)(nil), // 19: controlplane.v1.WorkflowRunServiceViewResponse - (*AttestationServiceGetUploadCredsRequest)(nil), // 20: controlplane.v1.AttestationServiceGetUploadCredsRequest - (*AttestationServiceGetUploadCredsResponse)(nil), // 21: controlplane.v1.AttestationServiceGetUploadCredsResponse - (*AttestationServiceGetContractResponse_Result)(nil), // 22: controlplane.v1.AttestationServiceGetContractResponse.Result - (*AttestationServiceInitResponse_Result)(nil), // 23: controlplane.v1.AttestationServiceInitResponse.Result - (*AttestationServiceInitResponse_SigningOptions)(nil), // 24: controlplane.v1.AttestationServiceInitResponse.SigningOptions - (*AttestationServiceStoreResponse_Result)(nil), // 25: controlplane.v1.AttestationServiceStoreResponse.Result - (*WorkflowRunServiceViewResponse_Result)(nil), // 26: controlplane.v1.WorkflowRunServiceViewResponse.Result - (*WorkflowRunServiceViewResponse_VerificationResult)(nil), // 27: controlplane.v1.WorkflowRunServiceViewResponse.VerificationResult - (*AttestationServiceGetUploadCredsResponse_Result)(nil), // 28: controlplane.v1.AttestationServiceGetUploadCredsResponse.Result - (*WorkflowItem)(nil), // 29: controlplane.v1.WorkflowItem - (*v1.Policy)(nil), // 30: workflowcontract.v1.Policy - (*v1.PolicyGroup)(nil), // 31: workflowcontract.v1.PolicyGroup - (v1.CraftingSchema_Runner_RunnerType)(0), // 32: workflowcontract.v1.CraftingSchema.Runner.RunnerType - (RunStatus)(0), // 33: controlplane.v1.RunStatus - (PolicyViolationsFilter)(0), // 34: controlplane.v1.PolicyViolationsFilter - (PolicyStatusFilter)(0), // 35: controlplane.v1.PolicyStatusFilter - (PolicyGatesFilter)(0), // 36: controlplane.v1.PolicyGatesFilter - (*CursorPaginationRequest)(nil), // 37: controlplane.v1.CursorPaginationRequest - (*WorkflowRunItem)(nil), // 38: controlplane.v1.WorkflowRunItem - (*CursorPaginationResponse)(nil), // 39: controlplane.v1.CursorPaginationResponse - (*WorkflowContractVersionItem)(nil), // 40: controlplane.v1.WorkflowContractVersionItem - (*AttestationItem)(nil), // 41: controlplane.v1.AttestationItem - (*CASBackendItem)(nil), // 42: controlplane.v1.CASBackendItem + (WorkflowRunEvent_Source)(0), // 1: controlplane.v1.WorkflowRunEvent.Source + (WorkflowRunEvent_Type)(0), // 2: controlplane.v1.WorkflowRunEvent.Type + (WorkflowRunEvent_Status)(0), // 3: controlplane.v1.WorkflowRunEvent.Status + (WorkflowRunProgress_Requirement)(0), // 4: controlplane.v1.WorkflowRunProgress.Requirement + (WorkflowRunProgress_Status)(0), // 5: controlplane.v1.WorkflowRunProgress.Status + (*FindOrCreateWorkflowRequest)(nil), // 6: controlplane.v1.FindOrCreateWorkflowRequest + (*FindOrCreateWorkflowResponse)(nil), // 7: controlplane.v1.FindOrCreateWorkflowResponse + (*AttestationServiceGetPolicyRequest)(nil), // 8: controlplane.v1.AttestationServiceGetPolicyRequest + (*AttestationServiceGetPolicyResponse)(nil), // 9: controlplane.v1.AttestationServiceGetPolicyResponse + (*RemotePolicyReference)(nil), // 10: controlplane.v1.RemotePolicyReference + (*AttestationServiceGetPolicyGroupRequest)(nil), // 11: controlplane.v1.AttestationServiceGetPolicyGroupRequest + (*AttestationServiceGetPolicyGroupResponse)(nil), // 12: controlplane.v1.AttestationServiceGetPolicyGroupResponse + (*AttestationServiceGetContractRequest)(nil), // 13: controlplane.v1.AttestationServiceGetContractRequest + (*AttestationServiceGetContractResponse)(nil), // 14: controlplane.v1.AttestationServiceGetContractResponse + (*AttestationServiceInitRequest)(nil), // 15: controlplane.v1.AttestationServiceInitRequest + (*AttestationServiceInitResponse)(nil), // 16: controlplane.v1.AttestationServiceInitResponse + (*AttestationServiceStoreRequest)(nil), // 17: controlplane.v1.AttestationServiceStoreRequest + (*AttestationServiceStoreResponse)(nil), // 18: controlplane.v1.AttestationServiceStoreResponse + (*AttestationServiceCancelRequest)(nil), // 19: controlplane.v1.AttestationServiceCancelRequest + (*AttestationServiceCancelResponse)(nil), // 20: controlplane.v1.AttestationServiceCancelResponse + (*AttestationServiceRecordEventRequest)(nil), // 21: controlplane.v1.AttestationServiceRecordEventRequest + (*AttestationServiceRecordEventResponse)(nil), // 22: controlplane.v1.AttestationServiceRecordEventResponse + (*WorkflowRunEvent)(nil), // 23: controlplane.v1.WorkflowRunEvent + (*WorkflowRunServiceListRequest)(nil), // 24: controlplane.v1.WorkflowRunServiceListRequest + (*WorkflowRunServiceListResponse)(nil), // 25: controlplane.v1.WorkflowRunServiceListResponse + (*WorkflowRunServiceViewRequest)(nil), // 26: controlplane.v1.WorkflowRunServiceViewRequest + (*WorkflowRunServiceGetProgressRequest)(nil), // 27: controlplane.v1.WorkflowRunServiceGetProgressRequest + (*WorkflowRunServiceGetProgressResponse)(nil), // 28: controlplane.v1.WorkflowRunServiceGetProgressResponse + (*WorkflowRunProgress)(nil), // 29: controlplane.v1.WorkflowRunProgress + (*WorkflowRunServiceViewResponse)(nil), // 30: controlplane.v1.WorkflowRunServiceViewResponse + (*AttestationServiceGetUploadCredsRequest)(nil), // 31: controlplane.v1.AttestationServiceGetUploadCredsRequest + (*AttestationServiceGetUploadCredsResponse)(nil), // 32: controlplane.v1.AttestationServiceGetUploadCredsResponse + (*AttestationServiceGetContractResponse_Result)(nil), // 33: controlplane.v1.AttestationServiceGetContractResponse.Result + (*AttestationServiceInitResponse_Result)(nil), // 34: controlplane.v1.AttestationServiceInitResponse.Result + (*AttestationServiceInitResponse_SigningOptions)(nil), // 35: controlplane.v1.AttestationServiceInitResponse.SigningOptions + (*AttestationServiceStoreResponse_Result)(nil), // 36: controlplane.v1.AttestationServiceStoreResponse.Result + (*WorkflowRunEvent_AttestationAttributes)(nil), // 37: controlplane.v1.WorkflowRunEvent.AttestationAttributes + (*WorkflowRunEvent_ExpectedMaterial)(nil), // 38: controlplane.v1.WorkflowRunEvent.ExpectedMaterial + (*WorkflowRunEvent_MaterialAttributes)(nil), // 39: controlplane.v1.WorkflowRunEvent.MaterialAttributes + (*WorkflowRunEvent_PolicyCounts)(nil), // 40: controlplane.v1.WorkflowRunEvent.PolicyCounts + (*WorkflowRunProgress_Material)(nil), // 41: controlplane.v1.WorkflowRunProgress.Material + (*WorkflowRunServiceViewResponse_Result)(nil), // 42: controlplane.v1.WorkflowRunServiceViewResponse.Result + (*WorkflowRunServiceViewResponse_VerificationResult)(nil), // 43: controlplane.v1.WorkflowRunServiceViewResponse.VerificationResult + (*AttestationServiceGetUploadCredsResponse_Result)(nil), // 44: controlplane.v1.AttestationServiceGetUploadCredsResponse.Result + (*WorkflowItem)(nil), // 45: controlplane.v1.WorkflowItem + (*v1.Policy)(nil), // 46: workflowcontract.v1.Policy + (*v1.PolicyGroup)(nil), // 47: workflowcontract.v1.PolicyGroup + (v1.CraftingSchema_Runner_RunnerType)(0), // 48: workflowcontract.v1.CraftingSchema.Runner.RunnerType + (*timestamppb.Timestamp)(nil), // 49: google.protobuf.Timestamp + (RunStatus)(0), // 50: controlplane.v1.RunStatus + (PolicyViolationsFilter)(0), // 51: controlplane.v1.PolicyViolationsFilter + (PolicyStatusFilter)(0), // 52: controlplane.v1.PolicyStatusFilter + (PolicyGatesFilter)(0), // 53: controlplane.v1.PolicyGatesFilter + (*CursorPaginationRequest)(nil), // 54: controlplane.v1.CursorPaginationRequest + (*WorkflowRunItem)(nil), // 55: controlplane.v1.WorkflowRunItem + (*CursorPaginationResponse)(nil), // 56: controlplane.v1.CursorPaginationResponse + (*WorkflowContractVersionItem)(nil), // 57: controlplane.v1.WorkflowContractVersionItem + (*AttestationItem)(nil), // 58: controlplane.v1.AttestationItem + (*CASBackendItem)(nil), // 59: controlplane.v1.CASBackendItem } var file_controlplane_v1_workflow_run_proto_depIdxs = []int32{ - 29, // 0: controlplane.v1.FindOrCreateWorkflowResponse.result:type_name -> controlplane.v1.WorkflowItem - 30, // 1: controlplane.v1.AttestationServiceGetPolicyResponse.policy:type_name -> workflowcontract.v1.Policy - 5, // 2: controlplane.v1.AttestationServiceGetPolicyResponse.reference:type_name -> controlplane.v1.RemotePolicyReference - 31, // 3: controlplane.v1.AttestationServiceGetPolicyGroupResponse.group:type_name -> workflowcontract.v1.PolicyGroup - 5, // 4: controlplane.v1.AttestationServiceGetPolicyGroupResponse.reference:type_name -> controlplane.v1.RemotePolicyReference - 22, // 5: controlplane.v1.AttestationServiceGetContractResponse.result:type_name -> controlplane.v1.AttestationServiceGetContractResponse.Result - 32, // 6: controlplane.v1.AttestationServiceInitRequest.runner:type_name -> workflowcontract.v1.CraftingSchema.Runner.RunnerType - 23, // 7: controlplane.v1.AttestationServiceInitResponse.result:type_name -> controlplane.v1.AttestationServiceInitResponse.Result - 25, // 8: controlplane.v1.AttestationServiceStoreResponse.result:type_name -> controlplane.v1.AttestationServiceStoreResponse.Result + 45, // 0: controlplane.v1.FindOrCreateWorkflowResponse.result:type_name -> controlplane.v1.WorkflowItem + 46, // 1: controlplane.v1.AttestationServiceGetPolicyResponse.policy:type_name -> workflowcontract.v1.Policy + 10, // 2: controlplane.v1.AttestationServiceGetPolicyResponse.reference:type_name -> controlplane.v1.RemotePolicyReference + 47, // 3: controlplane.v1.AttestationServiceGetPolicyGroupResponse.group:type_name -> workflowcontract.v1.PolicyGroup + 10, // 4: controlplane.v1.AttestationServiceGetPolicyGroupResponse.reference:type_name -> controlplane.v1.RemotePolicyReference + 33, // 5: controlplane.v1.AttestationServiceGetContractResponse.result:type_name -> controlplane.v1.AttestationServiceGetContractResponse.Result + 48, // 6: controlplane.v1.AttestationServiceInitRequest.runner:type_name -> workflowcontract.v1.CraftingSchema.Runner.RunnerType + 34, // 7: controlplane.v1.AttestationServiceInitResponse.result:type_name -> controlplane.v1.AttestationServiceInitResponse.Result + 36, // 8: controlplane.v1.AttestationServiceStoreResponse.result:type_name -> controlplane.v1.AttestationServiceStoreResponse.Result 0, // 9: controlplane.v1.AttestationServiceCancelRequest.trigger:type_name -> controlplane.v1.AttestationServiceCancelRequest.TriggerType - 33, // 10: controlplane.v1.WorkflowRunServiceListRequest.status:type_name -> controlplane.v1.RunStatus - 34, // 11: controlplane.v1.WorkflowRunServiceListRequest.policy_violations:type_name -> controlplane.v1.PolicyViolationsFilter - 35, // 12: controlplane.v1.WorkflowRunServiceListRequest.policy_status:type_name -> controlplane.v1.PolicyStatusFilter - 36, // 13: controlplane.v1.WorkflowRunServiceListRequest.policy_gates:type_name -> controlplane.v1.PolicyGatesFilter - 37, // 14: controlplane.v1.WorkflowRunServiceListRequest.pagination:type_name -> controlplane.v1.CursorPaginationRequest - 38, // 15: controlplane.v1.WorkflowRunServiceListResponse.result:type_name -> controlplane.v1.WorkflowRunItem - 39, // 16: controlplane.v1.WorkflowRunServiceListResponse.pagination:type_name -> controlplane.v1.CursorPaginationResponse - 26, // 17: controlplane.v1.WorkflowRunServiceViewResponse.result:type_name -> controlplane.v1.WorkflowRunServiceViewResponse.Result - 28, // 18: controlplane.v1.AttestationServiceGetUploadCredsResponse.result:type_name -> controlplane.v1.AttestationServiceGetUploadCredsResponse.Result - 29, // 19: controlplane.v1.AttestationServiceGetContractResponse.Result.workflow:type_name -> controlplane.v1.WorkflowItem - 40, // 20: controlplane.v1.AttestationServiceGetContractResponse.Result.contract:type_name -> controlplane.v1.WorkflowContractVersionItem - 38, // 21: controlplane.v1.AttestationServiceInitResponse.Result.workflow_run:type_name -> controlplane.v1.WorkflowRunItem - 24, // 22: controlplane.v1.AttestationServiceInitResponse.Result.signing_options:type_name -> controlplane.v1.AttestationServiceInitResponse.SigningOptions - 38, // 23: controlplane.v1.WorkflowRunServiceViewResponse.Result.workflow_run:type_name -> controlplane.v1.WorkflowRunItem - 41, // 24: controlplane.v1.WorkflowRunServiceViewResponse.Result.attestation:type_name -> controlplane.v1.AttestationItem - 27, // 25: controlplane.v1.WorkflowRunServiceViewResponse.Result.verification:type_name -> controlplane.v1.WorkflowRunServiceViewResponse.VerificationResult - 42, // 26: controlplane.v1.AttestationServiceGetUploadCredsResponse.Result.backend:type_name -> controlplane.v1.CASBackendItem - 1, // 27: controlplane.v1.AttestationService.FindOrCreateWorkflow:input_type -> controlplane.v1.FindOrCreateWorkflowRequest - 8, // 28: controlplane.v1.AttestationService.GetContract:input_type -> controlplane.v1.AttestationServiceGetContractRequest - 10, // 29: controlplane.v1.AttestationService.Init:input_type -> controlplane.v1.AttestationServiceInitRequest - 12, // 30: controlplane.v1.AttestationService.Store:input_type -> controlplane.v1.AttestationServiceStoreRequest - 20, // 31: controlplane.v1.AttestationService.GetUploadCreds:input_type -> controlplane.v1.AttestationServiceGetUploadCredsRequest - 14, // 32: controlplane.v1.AttestationService.Cancel:input_type -> controlplane.v1.AttestationServiceCancelRequest - 3, // 33: controlplane.v1.AttestationService.GetPolicy:input_type -> controlplane.v1.AttestationServiceGetPolicyRequest - 6, // 34: controlplane.v1.AttestationService.GetPolicyGroup:input_type -> controlplane.v1.AttestationServiceGetPolicyGroupRequest - 16, // 35: controlplane.v1.WorkflowRunService.List:input_type -> controlplane.v1.WorkflowRunServiceListRequest - 18, // 36: controlplane.v1.WorkflowRunService.View:input_type -> controlplane.v1.WorkflowRunServiceViewRequest - 2, // 37: controlplane.v1.AttestationService.FindOrCreateWorkflow:output_type -> controlplane.v1.FindOrCreateWorkflowResponse - 9, // 38: controlplane.v1.AttestationService.GetContract:output_type -> controlplane.v1.AttestationServiceGetContractResponse - 11, // 39: controlplane.v1.AttestationService.Init:output_type -> controlplane.v1.AttestationServiceInitResponse - 13, // 40: controlplane.v1.AttestationService.Store:output_type -> controlplane.v1.AttestationServiceStoreResponse - 21, // 41: controlplane.v1.AttestationService.GetUploadCreds:output_type -> controlplane.v1.AttestationServiceGetUploadCredsResponse - 15, // 42: controlplane.v1.AttestationService.Cancel:output_type -> controlplane.v1.AttestationServiceCancelResponse - 4, // 43: controlplane.v1.AttestationService.GetPolicy:output_type -> controlplane.v1.AttestationServiceGetPolicyResponse - 7, // 44: controlplane.v1.AttestationService.GetPolicyGroup:output_type -> controlplane.v1.AttestationServiceGetPolicyGroupResponse - 17, // 45: controlplane.v1.WorkflowRunService.List:output_type -> controlplane.v1.WorkflowRunServiceListResponse - 19, // 46: controlplane.v1.WorkflowRunService.View:output_type -> controlplane.v1.WorkflowRunServiceViewResponse - 37, // [37:47] is the sub-list for method output_type - 27, // [27:37] is the sub-list for method input_type - 27, // [27:27] is the sub-list for extension type_name - 27, // [27:27] is the sub-list for extension extendee - 0, // [0:27] is the sub-list for field type_name + 23, // 10: controlplane.v1.AttestationServiceRecordEventRequest.event:type_name -> controlplane.v1.WorkflowRunEvent + 49, // 11: controlplane.v1.WorkflowRunEvent.created_at:type_name -> google.protobuf.Timestamp + 1, // 12: controlplane.v1.WorkflowRunEvent.source:type_name -> controlplane.v1.WorkflowRunEvent.Source + 2, // 13: controlplane.v1.WorkflowRunEvent.type:type_name -> controlplane.v1.WorkflowRunEvent.Type + 3, // 14: controlplane.v1.WorkflowRunEvent.status:type_name -> controlplane.v1.WorkflowRunEvent.Status + 37, // 15: controlplane.v1.WorkflowRunEvent.attestation:type_name -> controlplane.v1.WorkflowRunEvent.AttestationAttributes + 39, // 16: controlplane.v1.WorkflowRunEvent.material:type_name -> controlplane.v1.WorkflowRunEvent.MaterialAttributes + 50, // 17: controlplane.v1.WorkflowRunServiceListRequest.status:type_name -> controlplane.v1.RunStatus + 51, // 18: controlplane.v1.WorkflowRunServiceListRequest.policy_violations:type_name -> controlplane.v1.PolicyViolationsFilter + 52, // 19: controlplane.v1.WorkflowRunServiceListRequest.policy_status:type_name -> controlplane.v1.PolicyStatusFilter + 53, // 20: controlplane.v1.WorkflowRunServiceListRequest.policy_gates:type_name -> controlplane.v1.PolicyGatesFilter + 54, // 21: controlplane.v1.WorkflowRunServiceListRequest.pagination:type_name -> controlplane.v1.CursorPaginationRequest + 55, // 22: controlplane.v1.WorkflowRunServiceListResponse.result:type_name -> controlplane.v1.WorkflowRunItem + 56, // 23: controlplane.v1.WorkflowRunServiceListResponse.pagination:type_name -> controlplane.v1.CursorPaginationResponse + 29, // 24: controlplane.v1.WorkflowRunServiceGetProgressResponse.progress:type_name -> controlplane.v1.WorkflowRunProgress + 23, // 25: controlplane.v1.WorkflowRunServiceGetProgressResponse.events:type_name -> controlplane.v1.WorkflowRunEvent + 41, // 26: controlplane.v1.WorkflowRunProgress.materials:type_name -> controlplane.v1.WorkflowRunProgress.Material + 40, // 27: controlplane.v1.WorkflowRunProgress.attestation_policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts + 42, // 28: controlplane.v1.WorkflowRunServiceViewResponse.result:type_name -> controlplane.v1.WorkflowRunServiceViewResponse.Result + 44, // 29: controlplane.v1.AttestationServiceGetUploadCredsResponse.result:type_name -> controlplane.v1.AttestationServiceGetUploadCredsResponse.Result + 45, // 30: controlplane.v1.AttestationServiceGetContractResponse.Result.workflow:type_name -> controlplane.v1.WorkflowItem + 57, // 31: controlplane.v1.AttestationServiceGetContractResponse.Result.contract:type_name -> controlplane.v1.WorkflowContractVersionItem + 55, // 32: controlplane.v1.AttestationServiceInitResponse.Result.workflow_run:type_name -> controlplane.v1.WorkflowRunItem + 35, // 33: controlplane.v1.AttestationServiceInitResponse.Result.signing_options:type_name -> controlplane.v1.AttestationServiceInitResponse.SigningOptions + 40, // 34: controlplane.v1.WorkflowRunEvent.AttestationAttributes.policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts + 38, // 35: controlplane.v1.WorkflowRunEvent.AttestationAttributes.expected_materials:type_name -> controlplane.v1.WorkflowRunEvent.ExpectedMaterial + 40, // 36: controlplane.v1.WorkflowRunEvent.MaterialAttributes.policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts + 4, // 37: controlplane.v1.WorkflowRunProgress.Material.requirement:type_name -> controlplane.v1.WorkflowRunProgress.Requirement + 5, // 38: controlplane.v1.WorkflowRunProgress.Material.status:type_name -> controlplane.v1.WorkflowRunProgress.Status + 40, // 39: controlplane.v1.WorkflowRunProgress.Material.policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts + 55, // 40: controlplane.v1.WorkflowRunServiceViewResponse.Result.workflow_run:type_name -> controlplane.v1.WorkflowRunItem + 58, // 41: controlplane.v1.WorkflowRunServiceViewResponse.Result.attestation:type_name -> controlplane.v1.AttestationItem + 43, // 42: controlplane.v1.WorkflowRunServiceViewResponse.Result.verification:type_name -> controlplane.v1.WorkflowRunServiceViewResponse.VerificationResult + 59, // 43: controlplane.v1.AttestationServiceGetUploadCredsResponse.Result.backend:type_name -> controlplane.v1.CASBackendItem + 6, // 44: controlplane.v1.AttestationService.FindOrCreateWorkflow:input_type -> controlplane.v1.FindOrCreateWorkflowRequest + 13, // 45: controlplane.v1.AttestationService.GetContract:input_type -> controlplane.v1.AttestationServiceGetContractRequest + 15, // 46: controlplane.v1.AttestationService.Init:input_type -> controlplane.v1.AttestationServiceInitRequest + 17, // 47: controlplane.v1.AttestationService.Store:input_type -> controlplane.v1.AttestationServiceStoreRequest + 31, // 48: controlplane.v1.AttestationService.GetUploadCreds:input_type -> controlplane.v1.AttestationServiceGetUploadCredsRequest + 19, // 49: controlplane.v1.AttestationService.Cancel:input_type -> controlplane.v1.AttestationServiceCancelRequest + 21, // 50: controlplane.v1.AttestationService.RecordEvent:input_type -> controlplane.v1.AttestationServiceRecordEventRequest + 8, // 51: controlplane.v1.AttestationService.GetPolicy:input_type -> controlplane.v1.AttestationServiceGetPolicyRequest + 11, // 52: controlplane.v1.AttestationService.GetPolicyGroup:input_type -> controlplane.v1.AttestationServiceGetPolicyGroupRequest + 24, // 53: controlplane.v1.WorkflowRunService.List:input_type -> controlplane.v1.WorkflowRunServiceListRequest + 26, // 54: controlplane.v1.WorkflowRunService.View:input_type -> controlplane.v1.WorkflowRunServiceViewRequest + 27, // 55: controlplane.v1.WorkflowRunService.GetProgress:input_type -> controlplane.v1.WorkflowRunServiceGetProgressRequest + 7, // 56: controlplane.v1.AttestationService.FindOrCreateWorkflow:output_type -> controlplane.v1.FindOrCreateWorkflowResponse + 14, // 57: controlplane.v1.AttestationService.GetContract:output_type -> controlplane.v1.AttestationServiceGetContractResponse + 16, // 58: controlplane.v1.AttestationService.Init:output_type -> controlplane.v1.AttestationServiceInitResponse + 18, // 59: controlplane.v1.AttestationService.Store:output_type -> controlplane.v1.AttestationServiceStoreResponse + 32, // 60: controlplane.v1.AttestationService.GetUploadCreds:output_type -> controlplane.v1.AttestationServiceGetUploadCredsResponse + 20, // 61: controlplane.v1.AttestationService.Cancel:output_type -> controlplane.v1.AttestationServiceCancelResponse + 22, // 62: controlplane.v1.AttestationService.RecordEvent:output_type -> controlplane.v1.AttestationServiceRecordEventResponse + 9, // 63: controlplane.v1.AttestationService.GetPolicy:output_type -> controlplane.v1.AttestationServiceGetPolicyResponse + 12, // 64: controlplane.v1.AttestationService.GetPolicyGroup:output_type -> controlplane.v1.AttestationServiceGetPolicyGroupResponse + 25, // 65: controlplane.v1.WorkflowRunService.List:output_type -> controlplane.v1.WorkflowRunServiceListResponse + 30, // 66: controlplane.v1.WorkflowRunService.View:output_type -> controlplane.v1.WorkflowRunServiceViewResponse + 28, // 67: controlplane.v1.WorkflowRunService.GetProgress:output_type -> controlplane.v1.WorkflowRunServiceGetProgressResponse + 56, // [56:68] is the sub-list for method output_type + 44, // [44:56] is the sub-list for method input_type + 44, // [44:44] is the sub-list for extension type_name + 44, // [44:44] is the sub-list for extension extendee + 0, // [0:44] is the sub-list for field type_name } func init() { file_controlplane_v1_workflow_run_proto_init() } @@ -2068,6 +3325,10 @@ func file_controlplane_v1_workflow_run_proto_init() { file_controlplane_v1_workflow_run_proto_msgTypes[9].OneofWrappers = []any{} file_controlplane_v1_workflow_run_proto_msgTypes[11].OneofWrappers = []any{} file_controlplane_v1_workflow_run_proto_msgTypes[17].OneofWrappers = []any{ + (*WorkflowRunEvent_Attestation)(nil), + (*WorkflowRunEvent_Material)(nil), + } + file_controlplane_v1_workflow_run_proto_msgTypes[20].OneofWrappers = []any{ (*WorkflowRunServiceViewRequest_Id)(nil), (*WorkflowRunServiceViewRequest_Digest)(nil), } @@ -2076,8 +3337,8 @@ func file_controlplane_v1_workflow_run_proto_init() { File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_controlplane_v1_workflow_run_proto_rawDesc), len(file_controlplane_v1_workflow_run_proto_rawDesc)), - NumEnums: 1, - NumMessages: 28, + NumEnums: 6, + NumMessages: 39, NumExtensions: 0, NumServices: 2, }, diff --git a/app/controlplane/api/controlplane/v1/workflow_run.proto b/app/controlplane/api/controlplane/v1/workflow_run.proto index 3495f2a1a..53f7c5ef4 100644 --- a/app/controlplane/api/controlplane/v1/workflow_run.proto +++ b/app/controlplane/api/controlplane/v1/workflow_run.proto @@ -20,6 +20,7 @@ package controlplane.v1; import "buf/validate/validate.proto"; import "controlplane/v1/pagination.proto"; import "controlplane/v1/response_messages.proto"; +import "google/protobuf/timestamp.proto"; import "workflowcontract/v1/crafting_schema.proto"; option go_package = "github.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1;v1"; @@ -34,6 +35,8 @@ service AttestationService { // This one is kept since it leverages robot-accounts in the context of a workflow rpc GetUploadCreds(AttestationServiceGetUploadCredsRequest) returns (AttestationServiceGetUploadCredsResponse); rpc Cancel(AttestationServiceCancelRequest) returns (AttestationServiceCancelResponse); + // Record a progress event on a run that is in progress. Informational only. + rpc RecordEvent(AttestationServiceRecordEventRequest) returns (AttestationServiceRecordEventResponse); // Get policies from remote providers rpc GetPolicy(AttestationServiceGetPolicyRequest) returns (AttestationServiceGetPolicyResponse); @@ -44,6 +47,8 @@ service AttestationService { service WorkflowRunService { rpc List(WorkflowRunServiceListRequest) returns (WorkflowRunServiceListResponse); rpc View(WorkflowRunServiceViewRequest) returns (WorkflowRunServiceViewResponse); + // Progress and timeline of a run. Clients poll it while the run is in progress. + rpc GetProgress(WorkflowRunServiceGetProgressRequest) returns (WorkflowRunServiceGetProgressResponse); } message FindOrCreateWorkflowRequest { @@ -204,6 +209,112 @@ message AttestationServiceCancelRequest { message AttestationServiceCancelResponse {} +message AttestationServiceRecordEventRequest { + string workflow_run_id = 1 [(buf.validate.field).string.uuid = true]; + // id, created_at, and source are set by the server and ignored here. + WorkflowRunEvent event = 2 [(buf.validate.field).required = true]; +} + +message AttestationServiceRecordEventResponse {} + +// A progress event of a workflow run. Unsigned and informational only. +// It is never part of the attestation. +message WorkflowRunEvent { + string id = 1; + // Time the control plane received the event + google.protobuf.Timestamp created_at = 2; + Source source = 3; + Type type = 4 [(buf.validate.field).enum = { + not_in: [0] + defined_only: true + }]; + // Events with the same key are one step of the timeline + string key = 5 [(buf.validate.field).string = { + min_len: 1 + max_len: 128 + }]; + Status status = 6 [(buf.validate.field).enum = { + not_in: [0] + defined_only: true + }]; + string message = 7 [(buf.validate.field).string.max_bytes = 1024]; + + oneof attributes { + AttestationAttributes attestation = 10; + MaterialAttributes material = 11; + } + reserved 12; + reserved "push"; + + enum Source { + SOURCE_UNSPECIFIED = 0; + SOURCE_CLI = 1; + SOURCE_CONTROL_PLANE = 2; + } + + enum Type { + TYPE_UNSPECIFIED = 0; + TYPE_ATTESTATION = 1; + TYPE_MATERIAL = 2; + reserved 3; + reserved "TYPE_PUSH"; + } + + enum Status { + STATUS_UNSPECIFIED = 0; + STATUS_STARTED = 1; + STATUS_SUCCEEDED = 2; + STATUS_FAILED = 3; + STATUS_CANCELED = 4; + } + + message AttestationAttributes { + string contract_name = 1 [(buf.validate.field).string.max_len = 256]; + int32 contract_revision = 2; + string runner_type = 3 [(buf.validate.field).string.max_len = 256]; + bool remote_state = 4; + string cli_version = 5 [(buf.validate.field).string.max_len = 256]; + string attestation_digest = 6 [(buf.validate.field).string.max_len = 256]; + // results of the attestation policies evaluated at init + PolicyCounts policies = 7; + // the materials that the attestation expects, from the contract and its policy groups, + // as init resolves them. Set on the start event. + repeated ExpectedMaterial expected_materials = 8 [(buf.validate.field).repeated.max_items = 1000]; + } + + message ExpectedMaterial { + string name = 1 [(buf.validate.field).string.max_len = 256]; + string material_type = 2 [(buf.validate.field).string.max_len = 256]; + bool optional = 3; + // set when the material is one of a group, of which one is required + string group = 4 [(buf.validate.field).string.max_len = 256]; + } + + message MaterialAttributes { + string name = 1 [(buf.validate.field).string.max_len = 256]; + string material_type = 2 [(buf.validate.field).string.max_len = 256]; + // value shown by attestation status, cut to 256 characters + string value = 3 [(buf.validate.field).string.max_len = 256]; + string digest = 4 [(buf.validate.field).string.max_len = 256]; + bool in_contract = 5; + bool added_by_collector = 6; + PolicyCounts policies = 7; + } + + message PolicyCounts { + int32 evaluated = 1; + int32 passed = 2; + int32 violated = 3; + int32 skipped = 4; + repeated string violated_policies = 5 [(buf.validate.field).repeated = { + max_items: 100 + items: { + string: {max_len: 256} + } + }]; + } +} + message WorkflowRunServiceListRequest { // Filters // by workflow @@ -279,6 +390,62 @@ message WorkflowRunServiceViewRequest { bool verify = 3; } +message WorkflowRunServiceGetProgressRequest { + string workflow_run_id = 1 [(buf.validate.field).string.uuid = true]; +} + +message WorkflowRunServiceGetProgressResponse { + // Progress of a run in progress, built by the control plane from its events. + // Not set for a finished run: the signed attestation is the source then. + WorkflowRunProgress progress = 1; + // Timeline of the run, oldest first. Reported data, never part of the attestation. + repeated WorkflowRunEvent events = 2; +} + +// The progress of a run in progress, ready to show +message WorkflowRunProgress { + // One row for each expected material, in contract order, then the materials not in the contract + repeated Material materials = 1; + // Required materials, where a group of materials counts once + int32 required_total = 2; + int32 required_provided = 3; + // Results of the attestation policies evaluated at init + WorkflowRunEvent.PolicyCounts attestation_policies = 4; + + message Material { + string name = 1; + string material_type = 2; + Requirement requirement = 3; + // Set when the requirement is ONE_OF_GROUP + string group = 4; + Status status = 5; + // Value and policy results of the last successful add + string value = 6; + WorkflowRunEvent.PolicyCounts policies = 7; + // Error of the last failed add, also after a successful one + string last_error = 8; + int32 failed_attempts = 9; + } + + enum Requirement { + REQUIREMENT_UNSPECIFIED = 0; + REQUIREMENT_REQUIRED = 1; + REQUIREMENT_OPTIONAL = 2; + REQUIREMENT_ONE_OF_GROUP = 3; + REQUIREMENT_NOT_IN_CONTRACT = 4; + } + + enum Status { + STATUS_UNSPECIFIED = 0; + // No add of the material yet + STATUS_MISSING = 1; + // An add of the material succeeded + STATUS_PROVIDED = 2; + // Never provided, and the last add failed + STATUS_FAILED = 3; + } +} + message WorkflowRunServiceViewResponse { Result result = 1; diff --git a/app/controlplane/api/controlplane/v1/workflow_run_grpc.pb.go b/app/controlplane/api/controlplane/v1/workflow_run_grpc.pb.go index 216637d69..b31ecc9d0 100644 --- a/app/controlplane/api/controlplane/v1/workflow_run_grpc.pb.go +++ b/app/controlplane/api/controlplane/v1/workflow_run_grpc.pb.go @@ -40,6 +40,7 @@ const ( AttestationService_Store_FullMethodName = "/controlplane.v1.AttestationService/Store" AttestationService_GetUploadCreds_FullMethodName = "/controlplane.v1.AttestationService/GetUploadCreds" AttestationService_Cancel_FullMethodName = "/controlplane.v1.AttestationService/Cancel" + AttestationService_RecordEvent_FullMethodName = "/controlplane.v1.AttestationService/RecordEvent" AttestationService_GetPolicy_FullMethodName = "/controlplane.v1.AttestationService/GetPolicy" AttestationService_GetPolicyGroup_FullMethodName = "/controlplane.v1.AttestationService/GetPolicyGroup" ) @@ -56,6 +57,8 @@ type AttestationServiceClient interface { // This one is kept since it leverages robot-accounts in the context of a workflow GetUploadCreds(ctx context.Context, in *AttestationServiceGetUploadCredsRequest, opts ...grpc.CallOption) (*AttestationServiceGetUploadCredsResponse, error) Cancel(ctx context.Context, in *AttestationServiceCancelRequest, opts ...grpc.CallOption) (*AttestationServiceCancelResponse, error) + // Record a progress event on a run that is in progress. Informational only. + RecordEvent(ctx context.Context, in *AttestationServiceRecordEventRequest, opts ...grpc.CallOption) (*AttestationServiceRecordEventResponse, error) // Get policies from remote providers GetPolicy(ctx context.Context, in *AttestationServiceGetPolicyRequest, opts ...grpc.CallOption) (*AttestationServiceGetPolicyResponse, error) GetPolicyGroup(ctx context.Context, in *AttestationServiceGetPolicyGroupRequest, opts ...grpc.CallOption) (*AttestationServiceGetPolicyGroupResponse, error) @@ -123,6 +126,15 @@ func (c *attestationServiceClient) Cancel(ctx context.Context, in *AttestationSe return out, nil } +func (c *attestationServiceClient) RecordEvent(ctx context.Context, in *AttestationServiceRecordEventRequest, opts ...grpc.CallOption) (*AttestationServiceRecordEventResponse, error) { + out := new(AttestationServiceRecordEventResponse) + err := c.cc.Invoke(ctx, AttestationService_RecordEvent_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + func (c *attestationServiceClient) GetPolicy(ctx context.Context, in *AttestationServiceGetPolicyRequest, opts ...grpc.CallOption) (*AttestationServiceGetPolicyResponse, error) { out := new(AttestationServiceGetPolicyResponse) err := c.cc.Invoke(ctx, AttestationService_GetPolicy_FullMethodName, in, out, opts...) @@ -153,6 +165,8 @@ type AttestationServiceServer interface { // This one is kept since it leverages robot-accounts in the context of a workflow GetUploadCreds(context.Context, *AttestationServiceGetUploadCredsRequest) (*AttestationServiceGetUploadCredsResponse, error) Cancel(context.Context, *AttestationServiceCancelRequest) (*AttestationServiceCancelResponse, error) + // Record a progress event on a run that is in progress. Informational only. + RecordEvent(context.Context, *AttestationServiceRecordEventRequest) (*AttestationServiceRecordEventResponse, error) // Get policies from remote providers GetPolicy(context.Context, *AttestationServiceGetPolicyRequest) (*AttestationServiceGetPolicyResponse, error) GetPolicyGroup(context.Context, *AttestationServiceGetPolicyGroupRequest) (*AttestationServiceGetPolicyGroupResponse, error) @@ -181,6 +195,9 @@ func (UnimplementedAttestationServiceServer) GetUploadCreds(context.Context, *At func (UnimplementedAttestationServiceServer) Cancel(context.Context, *AttestationServiceCancelRequest) (*AttestationServiceCancelResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method Cancel not implemented") } +func (UnimplementedAttestationServiceServer) RecordEvent(context.Context, *AttestationServiceRecordEventRequest) (*AttestationServiceRecordEventResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method RecordEvent not implemented") +} func (UnimplementedAttestationServiceServer) GetPolicy(context.Context, *AttestationServiceGetPolicyRequest) (*AttestationServiceGetPolicyResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method GetPolicy not implemented") } @@ -308,6 +325,24 @@ func _AttestationService_Cancel_Handler(srv interface{}, ctx context.Context, de return interceptor(ctx, in, info, handler) } +func _AttestationService_RecordEvent_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(AttestationServiceRecordEventRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(AttestationServiceServer).RecordEvent(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: AttestationService_RecordEvent_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(AttestationServiceServer).RecordEvent(ctx, req.(*AttestationServiceRecordEventRequest)) + } + return interceptor(ctx, in, info, handler) +} + func _AttestationService_GetPolicy_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(AttestationServiceGetPolicyRequest) if err := dec(in); err != nil { @@ -375,6 +410,10 @@ var AttestationService_ServiceDesc = grpc.ServiceDesc{ MethodName: "Cancel", Handler: _AttestationService_Cancel_Handler, }, + { + MethodName: "RecordEvent", + Handler: _AttestationService_RecordEvent_Handler, + }, { MethodName: "GetPolicy", Handler: _AttestationService_GetPolicy_Handler, @@ -389,8 +428,9 @@ var AttestationService_ServiceDesc = grpc.ServiceDesc{ } const ( - WorkflowRunService_List_FullMethodName = "/controlplane.v1.WorkflowRunService/List" - WorkflowRunService_View_FullMethodName = "/controlplane.v1.WorkflowRunService/View" + WorkflowRunService_List_FullMethodName = "/controlplane.v1.WorkflowRunService/List" + WorkflowRunService_View_FullMethodName = "/controlplane.v1.WorkflowRunService/View" + WorkflowRunService_GetProgress_FullMethodName = "/controlplane.v1.WorkflowRunService/GetProgress" ) // WorkflowRunServiceClient is the client API for WorkflowRunService service. @@ -399,6 +439,8 @@ const ( type WorkflowRunServiceClient interface { List(ctx context.Context, in *WorkflowRunServiceListRequest, opts ...grpc.CallOption) (*WorkflowRunServiceListResponse, error) View(ctx context.Context, in *WorkflowRunServiceViewRequest, opts ...grpc.CallOption) (*WorkflowRunServiceViewResponse, error) + // Progress and timeline of a run. Clients poll it while the run is in progress. + GetProgress(ctx context.Context, in *WorkflowRunServiceGetProgressRequest, opts ...grpc.CallOption) (*WorkflowRunServiceGetProgressResponse, error) } type workflowRunServiceClient struct { @@ -427,12 +469,23 @@ func (c *workflowRunServiceClient) View(ctx context.Context, in *WorkflowRunServ return out, nil } +func (c *workflowRunServiceClient) GetProgress(ctx context.Context, in *WorkflowRunServiceGetProgressRequest, opts ...grpc.CallOption) (*WorkflowRunServiceGetProgressResponse, error) { + out := new(WorkflowRunServiceGetProgressResponse) + err := c.cc.Invoke(ctx, WorkflowRunService_GetProgress_FullMethodName, in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + // WorkflowRunServiceServer is the server API for WorkflowRunService service. // All implementations must embed UnimplementedWorkflowRunServiceServer // for forward compatibility type WorkflowRunServiceServer interface { List(context.Context, *WorkflowRunServiceListRequest) (*WorkflowRunServiceListResponse, error) View(context.Context, *WorkflowRunServiceViewRequest) (*WorkflowRunServiceViewResponse, error) + // Progress and timeline of a run. Clients poll it while the run is in progress. + GetProgress(context.Context, *WorkflowRunServiceGetProgressRequest) (*WorkflowRunServiceGetProgressResponse, error) mustEmbedUnimplementedWorkflowRunServiceServer() } @@ -446,6 +499,9 @@ func (UnimplementedWorkflowRunServiceServer) List(context.Context, *WorkflowRunS func (UnimplementedWorkflowRunServiceServer) View(context.Context, *WorkflowRunServiceViewRequest) (*WorkflowRunServiceViewResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method View not implemented") } +func (UnimplementedWorkflowRunServiceServer) GetProgress(context.Context, *WorkflowRunServiceGetProgressRequest) (*WorkflowRunServiceGetProgressResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetProgress not implemented") +} func (UnimplementedWorkflowRunServiceServer) mustEmbedUnimplementedWorkflowRunServiceServer() {} // UnsafeWorkflowRunServiceServer may be embedded to opt out of forward compatibility for this service. @@ -495,6 +551,24 @@ func _WorkflowRunService_View_Handler(srv interface{}, ctx context.Context, dec return interceptor(ctx, in, info, handler) } +func _WorkflowRunService_GetProgress_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(WorkflowRunServiceGetProgressRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(WorkflowRunServiceServer).GetProgress(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: WorkflowRunService_GetProgress_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(WorkflowRunServiceServer).GetProgress(ctx, req.(*WorkflowRunServiceGetProgressRequest)) + } + return interceptor(ctx, in, info, handler) +} + // WorkflowRunService_ServiceDesc is the grpc.ServiceDesc for WorkflowRunService service. // It's only intended for direct use with grpc.RegisterService, // and not to be introspected or modified (even as a copy) @@ -510,6 +584,10 @@ var WorkflowRunService_ServiceDesc = grpc.ServiceDesc{ MethodName: "View", Handler: _WorkflowRunService_View_Handler, }, + { + MethodName: "GetProgress", + Handler: _WorkflowRunService_GetProgress_Handler, + }, }, Streams: []grpc.StreamDesc{}, Metadata: "controlplane/v1/workflow_run.proto", diff --git a/app/controlplane/api/controlplane/v1/workflow_run_test.go b/app/controlplane/api/controlplane/v1/workflow_run_test.go new file mode 100644 index 000000000..bbf29c860 --- /dev/null +++ b/app/controlplane/api/controlplane/v1/workflow_run_test.go @@ -0,0 +1,93 @@ +// +// Copyright 2026 The Chainloop Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package v1_test + +import ( + "strings" + "testing" + + "buf.build/go/protovalidate" + v1 "github.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// The size limits of a run event, so that a client cannot store large payloads +func TestAttestationServiceRecordEventRequestLimits(t *testing.T) { + names := func(n int) []string { + out := make([]string, n) + for i := range out { + out[i] = "policy" + } + return out + } + + testCases := []struct { + desc string + mutate func(ev *v1.WorkflowRunEvent) + wantErr bool + }{ + {desc: "a regular event", mutate: func(*v1.WorkflowRunEvent) {}}, + {desc: "a key of 128 characters", mutate: func(ev *v1.WorkflowRunEvent) { ev.Key = strings.Repeat("k", 128) }}, + {desc: "a key over 128 characters", mutate: func(ev *v1.WorkflowRunEvent) { ev.Key = strings.Repeat("k", 129) }, wantErr: true}, + {desc: "a message over 1 KB", mutate: func(ev *v1.WorkflowRunEvent) { ev.Message = strings.Repeat("m", 1025) }, wantErr: true}, + { + desc: "a material name over 256 characters", + mutate: func(ev *v1.WorkflowRunEvent) { + ev.GetMaterial().Name = strings.Repeat("n", 257) + }, + wantErr: true, + }, + { + desc: "100 violated policies", + mutate: func(ev *v1.WorkflowRunEvent) { + ev.GetMaterial().Policies = &v1.WorkflowRunEvent_PolicyCounts{ViolatedPolicies: names(100)} + }, + }, + { + desc: "over 100 violated policies", + mutate: func(ev *v1.WorkflowRunEvent) { + ev.GetMaterial().Policies = &v1.WorkflowRunEvent_PolicyCounts{ViolatedPolicies: names(101)} + }, + wantErr: true, + }, + } + + validator, err := protovalidate.New() + require.NoError(t, err) + + for _, tc := range testCases { + t.Run(tc.desc, func(t *testing.T) { + ev := &v1.WorkflowRunEvent{ + Type: v1.WorkflowRunEvent_TYPE_MATERIAL, + Key: "chainloop.material.sbom", + Status: v1.WorkflowRunEvent_STATUS_SUCCEEDED, + Attributes: &v1.WorkflowRunEvent_Material{Material: &v1.WorkflowRunEvent_MaterialAttributes{Name: "sbom"}}, + } + tc.mutate(ev) + + err := validator.Validate(&v1.AttestationServiceRecordEventRequest{ + WorkflowRunId: "1b4c6f8a-2d3e-4f5a-8b9c-0d1e2f3a4b5c", + Event: ev, + }) + if tc.wantErr { + assert.Error(t, err) + return + } + assert.NoError(t, err) + }) + } +} diff --git a/app/controlplane/api/gen/frontend/controlplane/v1/workflow_run.ts b/app/controlplane/api/gen/frontend/controlplane/v1/workflow_run.ts index 4412f4f3e..eb10c4afc 100644 --- a/app/controlplane/api/gen/frontend/controlplane/v1/workflow_run.ts +++ b/app/controlplane/api/gen/frontend/controlplane/v1/workflow_run.ts @@ -2,6 +2,7 @@ import { grpc } from "@improbable-eng/grpc-web"; import { BrowserHeaders } from "browser-headers"; import _m0 from "protobufjs/minimal"; +import { Timestamp } from "../../google/protobuf/timestamp"; import { CraftingSchema_Runner_RunnerType, craftingSchema_Runner_RunnerTypeFromJSON, @@ -223,6 +224,205 @@ export function attestationServiceCancelRequest_TriggerTypeToJSON( export interface AttestationServiceCancelResponse { } +export interface AttestationServiceRecordEventRequest { + workflowRunId: string; + /** id, created_at, and source are set by the server and ignored here. */ + event?: WorkflowRunEvent; +} + +export interface AttestationServiceRecordEventResponse { +} + +/** + * A progress event of a workflow run. Unsigned and informational only. + * It is never part of the attestation. + */ +export interface WorkflowRunEvent { + id: string; + /** Time the control plane received the event */ + createdAt?: Date; + source: WorkflowRunEvent_Source; + type: WorkflowRunEvent_Type; + /** Events with the same key are one step of the timeline */ + key: string; + status: WorkflowRunEvent_Status; + message: string; + attestation?: WorkflowRunEvent_AttestationAttributes | undefined; + material?: WorkflowRunEvent_MaterialAttributes | undefined; +} + +export enum WorkflowRunEvent_Source { + SOURCE_UNSPECIFIED = 0, + SOURCE_CLI = 1, + SOURCE_CONTROL_PLANE = 2, + UNRECOGNIZED = -1, +} + +export function workflowRunEvent_SourceFromJSON(object: any): WorkflowRunEvent_Source { + switch (object) { + case 0: + case "SOURCE_UNSPECIFIED": + return WorkflowRunEvent_Source.SOURCE_UNSPECIFIED; + case 1: + case "SOURCE_CLI": + return WorkflowRunEvent_Source.SOURCE_CLI; + case 2: + case "SOURCE_CONTROL_PLANE": + return WorkflowRunEvent_Source.SOURCE_CONTROL_PLANE; + case -1: + case "UNRECOGNIZED": + default: + return WorkflowRunEvent_Source.UNRECOGNIZED; + } +} + +export function workflowRunEvent_SourceToJSON(object: WorkflowRunEvent_Source): string { + switch (object) { + case WorkflowRunEvent_Source.SOURCE_UNSPECIFIED: + return "SOURCE_UNSPECIFIED"; + case WorkflowRunEvent_Source.SOURCE_CLI: + return "SOURCE_CLI"; + case WorkflowRunEvent_Source.SOURCE_CONTROL_PLANE: + return "SOURCE_CONTROL_PLANE"; + case WorkflowRunEvent_Source.UNRECOGNIZED: + default: + return "UNRECOGNIZED"; + } +} + +export enum WorkflowRunEvent_Type { + TYPE_UNSPECIFIED = 0, + TYPE_ATTESTATION = 1, + TYPE_MATERIAL = 2, + UNRECOGNIZED = -1, +} + +export function workflowRunEvent_TypeFromJSON(object: any): WorkflowRunEvent_Type { + switch (object) { + case 0: + case "TYPE_UNSPECIFIED": + return WorkflowRunEvent_Type.TYPE_UNSPECIFIED; + case 1: + case "TYPE_ATTESTATION": + return WorkflowRunEvent_Type.TYPE_ATTESTATION; + case 2: + case "TYPE_MATERIAL": + return WorkflowRunEvent_Type.TYPE_MATERIAL; + case -1: + case "UNRECOGNIZED": + default: + return WorkflowRunEvent_Type.UNRECOGNIZED; + } +} + +export function workflowRunEvent_TypeToJSON(object: WorkflowRunEvent_Type): string { + switch (object) { + case WorkflowRunEvent_Type.TYPE_UNSPECIFIED: + return "TYPE_UNSPECIFIED"; + case WorkflowRunEvent_Type.TYPE_ATTESTATION: + return "TYPE_ATTESTATION"; + case WorkflowRunEvent_Type.TYPE_MATERIAL: + return "TYPE_MATERIAL"; + case WorkflowRunEvent_Type.UNRECOGNIZED: + default: + return "UNRECOGNIZED"; + } +} + +export enum WorkflowRunEvent_Status { + STATUS_UNSPECIFIED = 0, + STATUS_STARTED = 1, + STATUS_SUCCEEDED = 2, + STATUS_FAILED = 3, + STATUS_CANCELED = 4, + UNRECOGNIZED = -1, +} + +export function workflowRunEvent_StatusFromJSON(object: any): WorkflowRunEvent_Status { + switch (object) { + case 0: + case "STATUS_UNSPECIFIED": + return WorkflowRunEvent_Status.STATUS_UNSPECIFIED; + case 1: + case "STATUS_STARTED": + return WorkflowRunEvent_Status.STATUS_STARTED; + case 2: + case "STATUS_SUCCEEDED": + return WorkflowRunEvent_Status.STATUS_SUCCEEDED; + case 3: + case "STATUS_FAILED": + return WorkflowRunEvent_Status.STATUS_FAILED; + case 4: + case "STATUS_CANCELED": + return WorkflowRunEvent_Status.STATUS_CANCELED; + case -1: + case "UNRECOGNIZED": + default: + return WorkflowRunEvent_Status.UNRECOGNIZED; + } +} + +export function workflowRunEvent_StatusToJSON(object: WorkflowRunEvent_Status): string { + switch (object) { + case WorkflowRunEvent_Status.STATUS_UNSPECIFIED: + return "STATUS_UNSPECIFIED"; + case WorkflowRunEvent_Status.STATUS_STARTED: + return "STATUS_STARTED"; + case WorkflowRunEvent_Status.STATUS_SUCCEEDED: + return "STATUS_SUCCEEDED"; + case WorkflowRunEvent_Status.STATUS_FAILED: + return "STATUS_FAILED"; + case WorkflowRunEvent_Status.STATUS_CANCELED: + return "STATUS_CANCELED"; + case WorkflowRunEvent_Status.UNRECOGNIZED: + default: + return "UNRECOGNIZED"; + } +} + +export interface WorkflowRunEvent_AttestationAttributes { + contractName: string; + contractRevision: number; + runnerType: string; + remoteState: boolean; + cliVersion: string; + attestationDigest: string; + /** results of the attestation policies evaluated at init */ + policies?: WorkflowRunEvent_PolicyCounts; + /** + * the materials that the attestation expects, from the contract and its policy groups, + * as init resolves them. Set on the start event. + */ + expectedMaterials: WorkflowRunEvent_ExpectedMaterial[]; +} + +export interface WorkflowRunEvent_ExpectedMaterial { + name: string; + materialType: string; + optional: boolean; + /** set when the material is one of a group, of which one is required */ + group: string; +} + +export interface WorkflowRunEvent_MaterialAttributes { + name: string; + materialType: string; + /** value shown by attestation status, cut to 256 characters */ + value: string; + digest: string; + inContract: boolean; + addedByCollector: boolean; + policies?: WorkflowRunEvent_PolicyCounts; +} + +export interface WorkflowRunEvent_PolicyCounts { + evaluated: number; + passed: number; + violated: number; + skipped: number; + violatedPolicies: string[]; +} + export interface WorkflowRunServiceListRequest { /** * Filters @@ -280,6 +480,145 @@ export interface WorkflowRunServiceViewRequest { verify: boolean; } +export interface WorkflowRunServiceGetProgressRequest { + workflowRunId: string; +} + +export interface WorkflowRunServiceGetProgressResponse { + /** + * Progress of a run in progress, built by the control plane from its events. + * Not set for a finished run: the signed attestation is the source then. + */ + progress?: WorkflowRunProgress; + /** Timeline of the run, oldest first. Reported data, never part of the attestation. */ + events: WorkflowRunEvent[]; +} + +/** The progress of a run in progress, ready to show */ +export interface WorkflowRunProgress { + /** One row for each expected material, in contract order, then the materials not in the contract */ + materials: WorkflowRunProgress_Material[]; + /** Required materials, where a group of materials counts once */ + requiredTotal: number; + requiredProvided: number; + /** Results of the attestation policies evaluated at init */ + attestationPolicies?: WorkflowRunEvent_PolicyCounts; +} + +export enum WorkflowRunProgress_Requirement { + REQUIREMENT_UNSPECIFIED = 0, + REQUIREMENT_REQUIRED = 1, + REQUIREMENT_OPTIONAL = 2, + REQUIREMENT_ONE_OF_GROUP = 3, + REQUIREMENT_NOT_IN_CONTRACT = 4, + UNRECOGNIZED = -1, +} + +export function workflowRunProgress_RequirementFromJSON(object: any): WorkflowRunProgress_Requirement { + switch (object) { + case 0: + case "REQUIREMENT_UNSPECIFIED": + return WorkflowRunProgress_Requirement.REQUIREMENT_UNSPECIFIED; + case 1: + case "REQUIREMENT_REQUIRED": + return WorkflowRunProgress_Requirement.REQUIREMENT_REQUIRED; + case 2: + case "REQUIREMENT_OPTIONAL": + return WorkflowRunProgress_Requirement.REQUIREMENT_OPTIONAL; + case 3: + case "REQUIREMENT_ONE_OF_GROUP": + return WorkflowRunProgress_Requirement.REQUIREMENT_ONE_OF_GROUP; + case 4: + case "REQUIREMENT_NOT_IN_CONTRACT": + return WorkflowRunProgress_Requirement.REQUIREMENT_NOT_IN_CONTRACT; + case -1: + case "UNRECOGNIZED": + default: + return WorkflowRunProgress_Requirement.UNRECOGNIZED; + } +} + +export function workflowRunProgress_RequirementToJSON(object: WorkflowRunProgress_Requirement): string { + switch (object) { + case WorkflowRunProgress_Requirement.REQUIREMENT_UNSPECIFIED: + return "REQUIREMENT_UNSPECIFIED"; + case WorkflowRunProgress_Requirement.REQUIREMENT_REQUIRED: + return "REQUIREMENT_REQUIRED"; + case WorkflowRunProgress_Requirement.REQUIREMENT_OPTIONAL: + return "REQUIREMENT_OPTIONAL"; + case WorkflowRunProgress_Requirement.REQUIREMENT_ONE_OF_GROUP: + return "REQUIREMENT_ONE_OF_GROUP"; + case WorkflowRunProgress_Requirement.REQUIREMENT_NOT_IN_CONTRACT: + return "REQUIREMENT_NOT_IN_CONTRACT"; + case WorkflowRunProgress_Requirement.UNRECOGNIZED: + default: + return "UNRECOGNIZED"; + } +} + +export enum WorkflowRunProgress_Status { + STATUS_UNSPECIFIED = 0, + /** STATUS_MISSING - No add of the material yet */ + STATUS_MISSING = 1, + /** STATUS_PROVIDED - An add of the material succeeded */ + STATUS_PROVIDED = 2, + /** STATUS_FAILED - Never provided, and the last add failed */ + STATUS_FAILED = 3, + UNRECOGNIZED = -1, +} + +export function workflowRunProgress_StatusFromJSON(object: any): WorkflowRunProgress_Status { + switch (object) { + case 0: + case "STATUS_UNSPECIFIED": + return WorkflowRunProgress_Status.STATUS_UNSPECIFIED; + case 1: + case "STATUS_MISSING": + return WorkflowRunProgress_Status.STATUS_MISSING; + case 2: + case "STATUS_PROVIDED": + return WorkflowRunProgress_Status.STATUS_PROVIDED; + case 3: + case "STATUS_FAILED": + return WorkflowRunProgress_Status.STATUS_FAILED; + case -1: + case "UNRECOGNIZED": + default: + return WorkflowRunProgress_Status.UNRECOGNIZED; + } +} + +export function workflowRunProgress_StatusToJSON(object: WorkflowRunProgress_Status): string { + switch (object) { + case WorkflowRunProgress_Status.STATUS_UNSPECIFIED: + return "STATUS_UNSPECIFIED"; + case WorkflowRunProgress_Status.STATUS_MISSING: + return "STATUS_MISSING"; + case WorkflowRunProgress_Status.STATUS_PROVIDED: + return "STATUS_PROVIDED"; + case WorkflowRunProgress_Status.STATUS_FAILED: + return "STATUS_FAILED"; + case WorkflowRunProgress_Status.UNRECOGNIZED: + default: + return "UNRECOGNIZED"; + } +} + +export interface WorkflowRunProgress_Material { + name: string; + materialType: string; + requirement: WorkflowRunProgress_Requirement; + /** Set when the requirement is ONE_OF_GROUP */ + group: string; + status: WorkflowRunProgress_Status; + /** Value and policy results of the last successful add */ + value: string; + policies?: WorkflowRunEvent_PolicyCounts; + /** Error of the last failed add, also after a successful one */ + lastError: string; + failedAttempts: number; +} + export interface WorkflowRunServiceViewResponse { result?: WorkflowRunServiceViewResponse_Result; } @@ -1964,56 +2303,25 @@ export const AttestationServiceCancelResponse = { }, }; -function createBaseWorkflowRunServiceListRequest(): WorkflowRunServiceListRequest { - return { - workflowName: "", - projectName: "", - status: 0, - projectVersion: "", - projectVersionName: "", - policyViolations: 0, - policyStatus: 0, - policyGates: 0, - pagination: undefined, - }; +function createBaseAttestationServiceRecordEventRequest(): AttestationServiceRecordEventRequest { + return { workflowRunId: "", event: undefined }; } -export const WorkflowRunServiceListRequest = { - encode(message: WorkflowRunServiceListRequest, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { - if (message.workflowName !== "") { - writer.uint32(10).string(message.workflowName); - } - if (message.projectName !== "") { - writer.uint32(34).string(message.projectName); - } - if (message.status !== 0) { - writer.uint32(24).int32(message.status); - } - if (message.projectVersion !== "") { - writer.uint32(42).string(message.projectVersion); - } - if (message.projectVersionName !== "") { - writer.uint32(74).string(message.projectVersionName); - } - if (message.policyViolations !== 0) { - writer.uint32(48).int32(message.policyViolations); - } - if (message.policyStatus !== 0) { - writer.uint32(56).int32(message.policyStatus); - } - if (message.policyGates !== 0) { - writer.uint32(64).int32(message.policyGates); +export const AttestationServiceRecordEventRequest = { + encode(message: AttestationServiceRecordEventRequest, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { + if (message.workflowRunId !== "") { + writer.uint32(10).string(message.workflowRunId); } - if (message.pagination !== undefined) { - CursorPaginationRequest.encode(message.pagination, writer.uint32(18).fork()).ldelim(); + if (message.event !== undefined) { + WorkflowRunEvent.encode(message.event, writer.uint32(18).fork()).ldelim(); } return writer; }, - decode(input: _m0.Reader | Uint8Array, length?: number): WorkflowRunServiceListRequest { + decode(input: _m0.Reader | Uint8Array, length?: number): AttestationServiceRecordEventRequest { const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input); let end = length === undefined ? reader.len : reader.pos + length; - const message = createBaseWorkflowRunServiceListRequest(); + const message = createBaseAttestationServiceRecordEventRequest(); while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { @@ -2022,63 +2330,14 @@ export const WorkflowRunServiceListRequest = { break; } - message.workflowName = reader.string(); - continue; - case 4: - if (tag !== 34) { - break; - } - - message.projectName = reader.string(); - continue; - case 3: - if (tag !== 24) { - break; - } - - message.status = reader.int32() as any; - continue; - case 5: - if (tag !== 42) { - break; - } - - message.projectVersion = reader.string(); - continue; - case 9: - if (tag !== 74) { - break; - } - - message.projectVersionName = reader.string(); - continue; - case 6: - if (tag !== 48) { - break; - } - - message.policyViolations = reader.int32() as any; - continue; - case 7: - if (tag !== 56) { - break; - } - - message.policyStatus = reader.int32() as any; - continue; - case 8: - if (tag !== 64) { - break; - } - - message.policyGates = reader.int32() as any; + message.workflowRunId = reader.string(); continue; case 2: if (tag !== 18) { break; } - message.pagination = CursorPaginationRequest.decode(reader, reader.uint32()); + message.event = WorkflowRunEvent.decode(reader, reader.uint32()); continue; } if ((tag & 7) === 4 || tag === 0) { @@ -2089,49 +2348,979 @@ export const WorkflowRunServiceListRequest = { return message; }, - fromJSON(object: any): WorkflowRunServiceListRequest { + fromJSON(object: any): AttestationServiceRecordEventRequest { return { - workflowName: isSet(object.workflowName) ? String(object.workflowName) : "", - projectName: isSet(object.projectName) ? String(object.projectName) : "", - status: isSet(object.status) ? runStatusFromJSON(object.status) : 0, - projectVersion: isSet(object.projectVersion) ? String(object.projectVersion) : "", - projectVersionName: isSet(object.projectVersionName) ? String(object.projectVersionName) : "", - policyViolations: isSet(object.policyViolations) ? policyViolationsFilterFromJSON(object.policyViolations) : 0, - policyStatus: isSet(object.policyStatus) ? policyStatusFilterFromJSON(object.policyStatus) : 0, - policyGates: isSet(object.policyGates) ? policyGatesFilterFromJSON(object.policyGates) : 0, - pagination: isSet(object.pagination) ? CursorPaginationRequest.fromJSON(object.pagination) : undefined, + workflowRunId: isSet(object.workflowRunId) ? String(object.workflowRunId) : "", + event: isSet(object.event) ? WorkflowRunEvent.fromJSON(object.event) : undefined, }; }, - toJSON(message: WorkflowRunServiceListRequest): unknown { + toJSON(message: AttestationServiceRecordEventRequest): unknown { const obj: any = {}; - message.workflowName !== undefined && (obj.workflowName = message.workflowName); - message.projectName !== undefined && (obj.projectName = message.projectName); - message.status !== undefined && (obj.status = runStatusToJSON(message.status)); - message.projectVersion !== undefined && (obj.projectVersion = message.projectVersion); - message.projectVersionName !== undefined && (obj.projectVersionName = message.projectVersionName); - message.policyViolations !== undefined && - (obj.policyViolations = policyViolationsFilterToJSON(message.policyViolations)); - message.policyStatus !== undefined && (obj.policyStatus = policyStatusFilterToJSON(message.policyStatus)); - message.policyGates !== undefined && (obj.policyGates = policyGatesFilterToJSON(message.policyGates)); - message.pagination !== undefined && - (obj.pagination = message.pagination ? CursorPaginationRequest.toJSON(message.pagination) : undefined); + message.workflowRunId !== undefined && (obj.workflowRunId = message.workflowRunId); + message.event !== undefined && (obj.event = message.event ? WorkflowRunEvent.toJSON(message.event) : undefined); return obj; }, - create, I>>(base?: I): WorkflowRunServiceListRequest { - return WorkflowRunServiceListRequest.fromPartial(base ?? {}); + create, I>>( + base?: I, + ): AttestationServiceRecordEventRequest { + return AttestationServiceRecordEventRequest.fromPartial(base ?? {}); }, - fromPartial, I>>( + fromPartial, I>>( object: I, - ): WorkflowRunServiceListRequest { - const message = createBaseWorkflowRunServiceListRequest(); - message.workflowName = object.workflowName ?? ""; - message.projectName = object.projectName ?? ""; - message.status = object.status ?? 0; - message.projectVersion = object.projectVersion ?? ""; - message.projectVersionName = object.projectVersionName ?? ""; + ): AttestationServiceRecordEventRequest { + const message = createBaseAttestationServiceRecordEventRequest(); + message.workflowRunId = object.workflowRunId ?? ""; + message.event = (object.event !== undefined && object.event !== null) + ? WorkflowRunEvent.fromPartial(object.event) + : undefined; + return message; + }, +}; + +function createBaseAttestationServiceRecordEventResponse(): AttestationServiceRecordEventResponse { + return {}; +} + +export const AttestationServiceRecordEventResponse = { + encode(_: AttestationServiceRecordEventResponse, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { + return writer; + }, + + decode(input: _m0.Reader | Uint8Array, length?: number): AttestationServiceRecordEventResponse { + const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input); + let end = length === undefined ? reader.len : reader.pos + length; + const message = createBaseAttestationServiceRecordEventResponse(); + while (reader.pos < end) { + const tag = reader.uint32(); + switch (tag >>> 3) { + } + if ((tag & 7) === 4 || tag === 0) { + break; + } + reader.skipType(tag & 7); + } + return message; + }, + + fromJSON(_: any): AttestationServiceRecordEventResponse { + return {}; + }, + + toJSON(_: AttestationServiceRecordEventResponse): unknown { + const obj: any = {}; + return obj; + }, + + create, I>>( + base?: I, + ): AttestationServiceRecordEventResponse { + return AttestationServiceRecordEventResponse.fromPartial(base ?? {}); + }, + + fromPartial, I>>( + _: I, + ): AttestationServiceRecordEventResponse { + const message = createBaseAttestationServiceRecordEventResponse(); + return message; + }, +}; + +function createBaseWorkflowRunEvent(): WorkflowRunEvent { + return { + id: "", + createdAt: undefined, + source: 0, + type: 0, + key: "", + status: 0, + message: "", + attestation: undefined, + material: undefined, + }; +} + +export const WorkflowRunEvent = { + encode(message: WorkflowRunEvent, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { + if (message.id !== "") { + writer.uint32(10).string(message.id); + } + if (message.createdAt !== undefined) { + Timestamp.encode(toTimestamp(message.createdAt), writer.uint32(18).fork()).ldelim(); + } + if (message.source !== 0) { + writer.uint32(24).int32(message.source); + } + if (message.type !== 0) { + writer.uint32(32).int32(message.type); + } + if (message.key !== "") { + writer.uint32(42).string(message.key); + } + if (message.status !== 0) { + writer.uint32(48).int32(message.status); + } + if (message.message !== "") { + writer.uint32(58).string(message.message); + } + if (message.attestation !== undefined) { + WorkflowRunEvent_AttestationAttributes.encode(message.attestation, writer.uint32(82).fork()).ldelim(); + } + if (message.material !== undefined) { + WorkflowRunEvent_MaterialAttributes.encode(message.material, writer.uint32(90).fork()).ldelim(); + } + return writer; + }, + + decode(input: _m0.Reader | Uint8Array, length?: number): WorkflowRunEvent { + const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input); + let end = length === undefined ? reader.len : reader.pos + length; + const message = createBaseWorkflowRunEvent(); + while (reader.pos < end) { + const tag = reader.uint32(); + switch (tag >>> 3) { + case 1: + if (tag !== 10) { + break; + } + + message.id = reader.string(); + continue; + case 2: + if (tag !== 18) { + break; + } + + message.createdAt = fromTimestamp(Timestamp.decode(reader, reader.uint32())); + continue; + case 3: + if (tag !== 24) { + break; + } + + message.source = reader.int32() as any; + continue; + case 4: + if (tag !== 32) { + break; + } + + message.type = reader.int32() as any; + continue; + case 5: + if (tag !== 42) { + break; + } + + message.key = reader.string(); + continue; + case 6: + if (tag !== 48) { + break; + } + + message.status = reader.int32() as any; + continue; + case 7: + if (tag !== 58) { + break; + } + + message.message = reader.string(); + continue; + case 10: + if (tag !== 82) { + break; + } + + message.attestation = WorkflowRunEvent_AttestationAttributes.decode(reader, reader.uint32()); + continue; + case 11: + if (tag !== 90) { + break; + } + + message.material = WorkflowRunEvent_MaterialAttributes.decode(reader, reader.uint32()); + continue; + } + if ((tag & 7) === 4 || tag === 0) { + break; + } + reader.skipType(tag & 7); + } + return message; + }, + + fromJSON(object: any): WorkflowRunEvent { + return { + id: isSet(object.id) ? String(object.id) : "", + createdAt: isSet(object.createdAt) ? fromJsonTimestamp(object.createdAt) : undefined, + source: isSet(object.source) ? workflowRunEvent_SourceFromJSON(object.source) : 0, + type: isSet(object.type) ? workflowRunEvent_TypeFromJSON(object.type) : 0, + key: isSet(object.key) ? String(object.key) : "", + status: isSet(object.status) ? workflowRunEvent_StatusFromJSON(object.status) : 0, + message: isSet(object.message) ? String(object.message) : "", + attestation: isSet(object.attestation) + ? WorkflowRunEvent_AttestationAttributes.fromJSON(object.attestation) + : undefined, + material: isSet(object.material) ? WorkflowRunEvent_MaterialAttributes.fromJSON(object.material) : undefined, + }; + }, + + toJSON(message: WorkflowRunEvent): unknown { + const obj: any = {}; + message.id !== undefined && (obj.id = message.id); + message.createdAt !== undefined && (obj.createdAt = message.createdAt.toISOString()); + message.source !== undefined && (obj.source = workflowRunEvent_SourceToJSON(message.source)); + message.type !== undefined && (obj.type = workflowRunEvent_TypeToJSON(message.type)); + message.key !== undefined && (obj.key = message.key); + message.status !== undefined && (obj.status = workflowRunEvent_StatusToJSON(message.status)); + message.message !== undefined && (obj.message = message.message); + message.attestation !== undefined && (obj.attestation = message.attestation + ? WorkflowRunEvent_AttestationAttributes.toJSON(message.attestation) + : undefined); + message.material !== undefined && + (obj.material = message.material ? WorkflowRunEvent_MaterialAttributes.toJSON(message.material) : undefined); + return obj; + }, + + create, I>>(base?: I): WorkflowRunEvent { + return WorkflowRunEvent.fromPartial(base ?? {}); + }, + + fromPartial, I>>(object: I): WorkflowRunEvent { + const message = createBaseWorkflowRunEvent(); + message.id = object.id ?? ""; + message.createdAt = object.createdAt ?? undefined; + message.source = object.source ?? 0; + message.type = object.type ?? 0; + message.key = object.key ?? ""; + message.status = object.status ?? 0; + message.message = object.message ?? ""; + message.attestation = (object.attestation !== undefined && object.attestation !== null) + ? WorkflowRunEvent_AttestationAttributes.fromPartial(object.attestation) + : undefined; + message.material = (object.material !== undefined && object.material !== null) + ? WorkflowRunEvent_MaterialAttributes.fromPartial(object.material) + : undefined; + return message; + }, +}; + +function createBaseWorkflowRunEvent_AttestationAttributes(): WorkflowRunEvent_AttestationAttributes { + return { + contractName: "", + contractRevision: 0, + runnerType: "", + remoteState: false, + cliVersion: "", + attestationDigest: "", + policies: undefined, + expectedMaterials: [], + }; +} + +export const WorkflowRunEvent_AttestationAttributes = { + encode(message: WorkflowRunEvent_AttestationAttributes, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { + if (message.contractName !== "") { + writer.uint32(10).string(message.contractName); + } + if (message.contractRevision !== 0) { + writer.uint32(16).int32(message.contractRevision); + } + if (message.runnerType !== "") { + writer.uint32(26).string(message.runnerType); + } + if (message.remoteState === true) { + writer.uint32(32).bool(message.remoteState); + } + if (message.cliVersion !== "") { + writer.uint32(42).string(message.cliVersion); + } + if (message.attestationDigest !== "") { + writer.uint32(50).string(message.attestationDigest); + } + if (message.policies !== undefined) { + WorkflowRunEvent_PolicyCounts.encode(message.policies, writer.uint32(58).fork()).ldelim(); + } + for (const v of message.expectedMaterials) { + WorkflowRunEvent_ExpectedMaterial.encode(v!, writer.uint32(66).fork()).ldelim(); + } + return writer; + }, + + decode(input: _m0.Reader | Uint8Array, length?: number): WorkflowRunEvent_AttestationAttributes { + const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input); + let end = length === undefined ? reader.len : reader.pos + length; + const message = createBaseWorkflowRunEvent_AttestationAttributes(); + while (reader.pos < end) { + const tag = reader.uint32(); + switch (tag >>> 3) { + case 1: + if (tag !== 10) { + break; + } + + message.contractName = reader.string(); + continue; + case 2: + if (tag !== 16) { + break; + } + + message.contractRevision = reader.int32(); + continue; + case 3: + if (tag !== 26) { + break; + } + + message.runnerType = reader.string(); + continue; + case 4: + if (tag !== 32) { + break; + } + + message.remoteState = reader.bool(); + continue; + case 5: + if (tag !== 42) { + break; + } + + message.cliVersion = reader.string(); + continue; + case 6: + if (tag !== 50) { + break; + } + + message.attestationDigest = reader.string(); + continue; + case 7: + if (tag !== 58) { + break; + } + + message.policies = WorkflowRunEvent_PolicyCounts.decode(reader, reader.uint32()); + continue; + case 8: + if (tag !== 66) { + break; + } + + message.expectedMaterials.push(WorkflowRunEvent_ExpectedMaterial.decode(reader, reader.uint32())); + continue; + } + if ((tag & 7) === 4 || tag === 0) { + break; + } + reader.skipType(tag & 7); + } + return message; + }, + + fromJSON(object: any): WorkflowRunEvent_AttestationAttributes { + return { + contractName: isSet(object.contractName) ? String(object.contractName) : "", + contractRevision: isSet(object.contractRevision) ? Number(object.contractRevision) : 0, + runnerType: isSet(object.runnerType) ? String(object.runnerType) : "", + remoteState: isSet(object.remoteState) ? Boolean(object.remoteState) : false, + cliVersion: isSet(object.cliVersion) ? String(object.cliVersion) : "", + attestationDigest: isSet(object.attestationDigest) ? String(object.attestationDigest) : "", + policies: isSet(object.policies) ? WorkflowRunEvent_PolicyCounts.fromJSON(object.policies) : undefined, + expectedMaterials: Array.isArray(object?.expectedMaterials) + ? object.expectedMaterials.map((e: any) => WorkflowRunEvent_ExpectedMaterial.fromJSON(e)) + : [], + }; + }, + + toJSON(message: WorkflowRunEvent_AttestationAttributes): unknown { + const obj: any = {}; + message.contractName !== undefined && (obj.contractName = message.contractName); + message.contractRevision !== undefined && (obj.contractRevision = Math.round(message.contractRevision)); + message.runnerType !== undefined && (obj.runnerType = message.runnerType); + message.remoteState !== undefined && (obj.remoteState = message.remoteState); + message.cliVersion !== undefined && (obj.cliVersion = message.cliVersion); + message.attestationDigest !== undefined && (obj.attestationDigest = message.attestationDigest); + message.policies !== undefined && + (obj.policies = message.policies ? WorkflowRunEvent_PolicyCounts.toJSON(message.policies) : undefined); + if (message.expectedMaterials) { + obj.expectedMaterials = message.expectedMaterials.map((e) => + e ? WorkflowRunEvent_ExpectedMaterial.toJSON(e) : undefined + ); + } else { + obj.expectedMaterials = []; + } + return obj; + }, + + create, I>>( + base?: I, + ): WorkflowRunEvent_AttestationAttributes { + return WorkflowRunEvent_AttestationAttributes.fromPartial(base ?? {}); + }, + + fromPartial, I>>( + object: I, + ): WorkflowRunEvent_AttestationAttributes { + const message = createBaseWorkflowRunEvent_AttestationAttributes(); + message.contractName = object.contractName ?? ""; + message.contractRevision = object.contractRevision ?? 0; + message.runnerType = object.runnerType ?? ""; + message.remoteState = object.remoteState ?? false; + message.cliVersion = object.cliVersion ?? ""; + message.attestationDigest = object.attestationDigest ?? ""; + message.policies = (object.policies !== undefined && object.policies !== null) + ? WorkflowRunEvent_PolicyCounts.fromPartial(object.policies) + : undefined; + message.expectedMaterials = + object.expectedMaterials?.map((e) => WorkflowRunEvent_ExpectedMaterial.fromPartial(e)) || []; + return message; + }, +}; + +function createBaseWorkflowRunEvent_ExpectedMaterial(): WorkflowRunEvent_ExpectedMaterial { + return { name: "", materialType: "", optional: false, group: "" }; +} + +export const WorkflowRunEvent_ExpectedMaterial = { + encode(message: WorkflowRunEvent_ExpectedMaterial, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { + if (message.name !== "") { + writer.uint32(10).string(message.name); + } + if (message.materialType !== "") { + writer.uint32(18).string(message.materialType); + } + if (message.optional === true) { + writer.uint32(24).bool(message.optional); + } + if (message.group !== "") { + writer.uint32(34).string(message.group); + } + return writer; + }, + + decode(input: _m0.Reader | Uint8Array, length?: number): WorkflowRunEvent_ExpectedMaterial { + const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input); + let end = length === undefined ? reader.len : reader.pos + length; + const message = createBaseWorkflowRunEvent_ExpectedMaterial(); + while (reader.pos < end) { + const tag = reader.uint32(); + switch (tag >>> 3) { + case 1: + if (tag !== 10) { + break; + } + + message.name = reader.string(); + continue; + case 2: + if (tag !== 18) { + break; + } + + message.materialType = reader.string(); + continue; + case 3: + if (tag !== 24) { + break; + } + + message.optional = reader.bool(); + continue; + case 4: + if (tag !== 34) { + break; + } + + message.group = reader.string(); + continue; + } + if ((tag & 7) === 4 || tag === 0) { + break; + } + reader.skipType(tag & 7); + } + return message; + }, + + fromJSON(object: any): WorkflowRunEvent_ExpectedMaterial { + return { + name: isSet(object.name) ? String(object.name) : "", + materialType: isSet(object.materialType) ? String(object.materialType) : "", + optional: isSet(object.optional) ? Boolean(object.optional) : false, + group: isSet(object.group) ? String(object.group) : "", + }; + }, + + toJSON(message: WorkflowRunEvent_ExpectedMaterial): unknown { + const obj: any = {}; + message.name !== undefined && (obj.name = message.name); + message.materialType !== undefined && (obj.materialType = message.materialType); + message.optional !== undefined && (obj.optional = message.optional); + message.group !== undefined && (obj.group = message.group); + return obj; + }, + + create, I>>( + base?: I, + ): WorkflowRunEvent_ExpectedMaterial { + return WorkflowRunEvent_ExpectedMaterial.fromPartial(base ?? {}); + }, + + fromPartial, I>>( + object: I, + ): WorkflowRunEvent_ExpectedMaterial { + const message = createBaseWorkflowRunEvent_ExpectedMaterial(); + message.name = object.name ?? ""; + message.materialType = object.materialType ?? ""; + message.optional = object.optional ?? false; + message.group = object.group ?? ""; + return message; + }, +}; + +function createBaseWorkflowRunEvent_MaterialAttributes(): WorkflowRunEvent_MaterialAttributes { + return { + name: "", + materialType: "", + value: "", + digest: "", + inContract: false, + addedByCollector: false, + policies: undefined, + }; +} + +export const WorkflowRunEvent_MaterialAttributes = { + encode(message: WorkflowRunEvent_MaterialAttributes, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { + if (message.name !== "") { + writer.uint32(10).string(message.name); + } + if (message.materialType !== "") { + writer.uint32(18).string(message.materialType); + } + if (message.value !== "") { + writer.uint32(26).string(message.value); + } + if (message.digest !== "") { + writer.uint32(34).string(message.digest); + } + if (message.inContract === true) { + writer.uint32(40).bool(message.inContract); + } + if (message.addedByCollector === true) { + writer.uint32(48).bool(message.addedByCollector); + } + if (message.policies !== undefined) { + WorkflowRunEvent_PolicyCounts.encode(message.policies, writer.uint32(58).fork()).ldelim(); + } + return writer; + }, + + decode(input: _m0.Reader | Uint8Array, length?: number): WorkflowRunEvent_MaterialAttributes { + const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input); + let end = length === undefined ? reader.len : reader.pos + length; + const message = createBaseWorkflowRunEvent_MaterialAttributes(); + while (reader.pos < end) { + const tag = reader.uint32(); + switch (tag >>> 3) { + case 1: + if (tag !== 10) { + break; + } + + message.name = reader.string(); + continue; + case 2: + if (tag !== 18) { + break; + } + + message.materialType = reader.string(); + continue; + case 3: + if (tag !== 26) { + break; + } + + message.value = reader.string(); + continue; + case 4: + if (tag !== 34) { + break; + } + + message.digest = reader.string(); + continue; + case 5: + if (tag !== 40) { + break; + } + + message.inContract = reader.bool(); + continue; + case 6: + if (tag !== 48) { + break; + } + + message.addedByCollector = reader.bool(); + continue; + case 7: + if (tag !== 58) { + break; + } + + message.policies = WorkflowRunEvent_PolicyCounts.decode(reader, reader.uint32()); + continue; + } + if ((tag & 7) === 4 || tag === 0) { + break; + } + reader.skipType(tag & 7); + } + return message; + }, + + fromJSON(object: any): WorkflowRunEvent_MaterialAttributes { + return { + name: isSet(object.name) ? String(object.name) : "", + materialType: isSet(object.materialType) ? String(object.materialType) : "", + value: isSet(object.value) ? String(object.value) : "", + digest: isSet(object.digest) ? String(object.digest) : "", + inContract: isSet(object.inContract) ? Boolean(object.inContract) : false, + addedByCollector: isSet(object.addedByCollector) ? Boolean(object.addedByCollector) : false, + policies: isSet(object.policies) ? WorkflowRunEvent_PolicyCounts.fromJSON(object.policies) : undefined, + }; + }, + + toJSON(message: WorkflowRunEvent_MaterialAttributes): unknown { + const obj: any = {}; + message.name !== undefined && (obj.name = message.name); + message.materialType !== undefined && (obj.materialType = message.materialType); + message.value !== undefined && (obj.value = message.value); + message.digest !== undefined && (obj.digest = message.digest); + message.inContract !== undefined && (obj.inContract = message.inContract); + message.addedByCollector !== undefined && (obj.addedByCollector = message.addedByCollector); + message.policies !== undefined && + (obj.policies = message.policies ? WorkflowRunEvent_PolicyCounts.toJSON(message.policies) : undefined); + return obj; + }, + + create, I>>( + base?: I, + ): WorkflowRunEvent_MaterialAttributes { + return WorkflowRunEvent_MaterialAttributes.fromPartial(base ?? {}); + }, + + fromPartial, I>>( + object: I, + ): WorkflowRunEvent_MaterialAttributes { + const message = createBaseWorkflowRunEvent_MaterialAttributes(); + message.name = object.name ?? ""; + message.materialType = object.materialType ?? ""; + message.value = object.value ?? ""; + message.digest = object.digest ?? ""; + message.inContract = object.inContract ?? false; + message.addedByCollector = object.addedByCollector ?? false; + message.policies = (object.policies !== undefined && object.policies !== null) + ? WorkflowRunEvent_PolicyCounts.fromPartial(object.policies) + : undefined; + return message; + }, +}; + +function createBaseWorkflowRunEvent_PolicyCounts(): WorkflowRunEvent_PolicyCounts { + return { evaluated: 0, passed: 0, violated: 0, skipped: 0, violatedPolicies: [] }; +} + +export const WorkflowRunEvent_PolicyCounts = { + encode(message: WorkflowRunEvent_PolicyCounts, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { + if (message.evaluated !== 0) { + writer.uint32(8).int32(message.evaluated); + } + if (message.passed !== 0) { + writer.uint32(16).int32(message.passed); + } + if (message.violated !== 0) { + writer.uint32(24).int32(message.violated); + } + if (message.skipped !== 0) { + writer.uint32(32).int32(message.skipped); + } + for (const v of message.violatedPolicies) { + writer.uint32(42).string(v!); + } + return writer; + }, + + decode(input: _m0.Reader | Uint8Array, length?: number): WorkflowRunEvent_PolicyCounts { + const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input); + let end = length === undefined ? reader.len : reader.pos + length; + const message = createBaseWorkflowRunEvent_PolicyCounts(); + while (reader.pos < end) { + const tag = reader.uint32(); + switch (tag >>> 3) { + case 1: + if (tag !== 8) { + break; + } + + message.evaluated = reader.int32(); + continue; + case 2: + if (tag !== 16) { + break; + } + + message.passed = reader.int32(); + continue; + case 3: + if (tag !== 24) { + break; + } + + message.violated = reader.int32(); + continue; + case 4: + if (tag !== 32) { + break; + } + + message.skipped = reader.int32(); + continue; + case 5: + if (tag !== 42) { + break; + } + + message.violatedPolicies.push(reader.string()); + continue; + } + if ((tag & 7) === 4 || tag === 0) { + break; + } + reader.skipType(tag & 7); + } + return message; + }, + + fromJSON(object: any): WorkflowRunEvent_PolicyCounts { + return { + evaluated: isSet(object.evaluated) ? Number(object.evaluated) : 0, + passed: isSet(object.passed) ? Number(object.passed) : 0, + violated: isSet(object.violated) ? Number(object.violated) : 0, + skipped: isSet(object.skipped) ? Number(object.skipped) : 0, + violatedPolicies: Array.isArray(object?.violatedPolicies) + ? object.violatedPolicies.map((e: any) => String(e)) + : [], + }; + }, + + toJSON(message: WorkflowRunEvent_PolicyCounts): unknown { + const obj: any = {}; + message.evaluated !== undefined && (obj.evaluated = Math.round(message.evaluated)); + message.passed !== undefined && (obj.passed = Math.round(message.passed)); + message.violated !== undefined && (obj.violated = Math.round(message.violated)); + message.skipped !== undefined && (obj.skipped = Math.round(message.skipped)); + if (message.violatedPolicies) { + obj.violatedPolicies = message.violatedPolicies.map((e) => e); + } else { + obj.violatedPolicies = []; + } + return obj; + }, + + create, I>>(base?: I): WorkflowRunEvent_PolicyCounts { + return WorkflowRunEvent_PolicyCounts.fromPartial(base ?? {}); + }, + + fromPartial, I>>( + object: I, + ): WorkflowRunEvent_PolicyCounts { + const message = createBaseWorkflowRunEvent_PolicyCounts(); + message.evaluated = object.evaluated ?? 0; + message.passed = object.passed ?? 0; + message.violated = object.violated ?? 0; + message.skipped = object.skipped ?? 0; + message.violatedPolicies = object.violatedPolicies?.map((e) => e) || []; + return message; + }, +}; + +function createBaseWorkflowRunServiceListRequest(): WorkflowRunServiceListRequest { + return { + workflowName: "", + projectName: "", + status: 0, + projectVersion: "", + projectVersionName: "", + policyViolations: 0, + policyStatus: 0, + policyGates: 0, + pagination: undefined, + }; +} + +export const WorkflowRunServiceListRequest = { + encode(message: WorkflowRunServiceListRequest, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { + if (message.workflowName !== "") { + writer.uint32(10).string(message.workflowName); + } + if (message.projectName !== "") { + writer.uint32(34).string(message.projectName); + } + if (message.status !== 0) { + writer.uint32(24).int32(message.status); + } + if (message.projectVersion !== "") { + writer.uint32(42).string(message.projectVersion); + } + if (message.projectVersionName !== "") { + writer.uint32(74).string(message.projectVersionName); + } + if (message.policyViolations !== 0) { + writer.uint32(48).int32(message.policyViolations); + } + if (message.policyStatus !== 0) { + writer.uint32(56).int32(message.policyStatus); + } + if (message.policyGates !== 0) { + writer.uint32(64).int32(message.policyGates); + } + if (message.pagination !== undefined) { + CursorPaginationRequest.encode(message.pagination, writer.uint32(18).fork()).ldelim(); + } + return writer; + }, + + decode(input: _m0.Reader | Uint8Array, length?: number): WorkflowRunServiceListRequest { + const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input); + let end = length === undefined ? reader.len : reader.pos + length; + const message = createBaseWorkflowRunServiceListRequest(); + while (reader.pos < end) { + const tag = reader.uint32(); + switch (tag >>> 3) { + case 1: + if (tag !== 10) { + break; + } + + message.workflowName = reader.string(); + continue; + case 4: + if (tag !== 34) { + break; + } + + message.projectName = reader.string(); + continue; + case 3: + if (tag !== 24) { + break; + } + + message.status = reader.int32() as any; + continue; + case 5: + if (tag !== 42) { + break; + } + + message.projectVersion = reader.string(); + continue; + case 9: + if (tag !== 74) { + break; + } + + message.projectVersionName = reader.string(); + continue; + case 6: + if (tag !== 48) { + break; + } + + message.policyViolations = reader.int32() as any; + continue; + case 7: + if (tag !== 56) { + break; + } + + message.policyStatus = reader.int32() as any; + continue; + case 8: + if (tag !== 64) { + break; + } + + message.policyGates = reader.int32() as any; + continue; + case 2: + if (tag !== 18) { + break; + } + + message.pagination = CursorPaginationRequest.decode(reader, reader.uint32()); + continue; + } + if ((tag & 7) === 4 || tag === 0) { + break; + } + reader.skipType(tag & 7); + } + return message; + }, + + fromJSON(object: any): WorkflowRunServiceListRequest { + return { + workflowName: isSet(object.workflowName) ? String(object.workflowName) : "", + projectName: isSet(object.projectName) ? String(object.projectName) : "", + status: isSet(object.status) ? runStatusFromJSON(object.status) : 0, + projectVersion: isSet(object.projectVersion) ? String(object.projectVersion) : "", + projectVersionName: isSet(object.projectVersionName) ? String(object.projectVersionName) : "", + policyViolations: isSet(object.policyViolations) ? policyViolationsFilterFromJSON(object.policyViolations) : 0, + policyStatus: isSet(object.policyStatus) ? policyStatusFilterFromJSON(object.policyStatus) : 0, + policyGates: isSet(object.policyGates) ? policyGatesFilterFromJSON(object.policyGates) : 0, + pagination: isSet(object.pagination) ? CursorPaginationRequest.fromJSON(object.pagination) : undefined, + }; + }, + + toJSON(message: WorkflowRunServiceListRequest): unknown { + const obj: any = {}; + message.workflowName !== undefined && (obj.workflowName = message.workflowName); + message.projectName !== undefined && (obj.projectName = message.projectName); + message.status !== undefined && (obj.status = runStatusToJSON(message.status)); + message.projectVersion !== undefined && (obj.projectVersion = message.projectVersion); + message.projectVersionName !== undefined && (obj.projectVersionName = message.projectVersionName); + message.policyViolations !== undefined && + (obj.policyViolations = policyViolationsFilterToJSON(message.policyViolations)); + message.policyStatus !== undefined && (obj.policyStatus = policyStatusFilterToJSON(message.policyStatus)); + message.policyGates !== undefined && (obj.policyGates = policyGatesFilterToJSON(message.policyGates)); + message.pagination !== undefined && + (obj.pagination = message.pagination ? CursorPaginationRequest.toJSON(message.pagination) : undefined); + return obj; + }, + + create, I>>(base?: I): WorkflowRunServiceListRequest { + return WorkflowRunServiceListRequest.fromPartial(base ?? {}); + }, + + fromPartial, I>>( + object: I, + ): WorkflowRunServiceListRequest { + const message = createBaseWorkflowRunServiceListRequest(); + message.workflowName = object.workflowName ?? ""; + message.projectName = object.projectName ?? ""; + message.status = object.status ?? 0; + message.projectVersion = object.projectVersion ?? ""; + message.projectVersionName = object.projectVersionName ?? ""; message.policyViolations = object.policyViolations ?? 0; message.policyStatus = object.policyStatus ?? 0; message.policyGates = object.policyGates ?? 0; @@ -2142,25 +3331,251 @@ export const WorkflowRunServiceListRequest = { }, }; -function createBaseWorkflowRunServiceListResponse(): WorkflowRunServiceListResponse { - return { result: [], pagination: undefined }; +function createBaseWorkflowRunServiceListResponse(): WorkflowRunServiceListResponse { + return { result: [], pagination: undefined }; +} + +export const WorkflowRunServiceListResponse = { + encode(message: WorkflowRunServiceListResponse, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { + for (const v of message.result) { + WorkflowRunItem.encode(v!, writer.uint32(10).fork()).ldelim(); + } + if (message.pagination !== undefined) { + CursorPaginationResponse.encode(message.pagination, writer.uint32(18).fork()).ldelim(); + } + return writer; + }, + + decode(input: _m0.Reader | Uint8Array, length?: number): WorkflowRunServiceListResponse { + const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input); + let end = length === undefined ? reader.len : reader.pos + length; + const message = createBaseWorkflowRunServiceListResponse(); + while (reader.pos < end) { + const tag = reader.uint32(); + switch (tag >>> 3) { + case 1: + if (tag !== 10) { + break; + } + + message.result.push(WorkflowRunItem.decode(reader, reader.uint32())); + continue; + case 2: + if (tag !== 18) { + break; + } + + message.pagination = CursorPaginationResponse.decode(reader, reader.uint32()); + continue; + } + if ((tag & 7) === 4 || tag === 0) { + break; + } + reader.skipType(tag & 7); + } + return message; + }, + + fromJSON(object: any): WorkflowRunServiceListResponse { + return { + result: Array.isArray(object?.result) ? object.result.map((e: any) => WorkflowRunItem.fromJSON(e)) : [], + pagination: isSet(object.pagination) ? CursorPaginationResponse.fromJSON(object.pagination) : undefined, + }; + }, + + toJSON(message: WorkflowRunServiceListResponse): unknown { + const obj: any = {}; + if (message.result) { + obj.result = message.result.map((e) => e ? WorkflowRunItem.toJSON(e) : undefined); + } else { + obj.result = []; + } + message.pagination !== undefined && + (obj.pagination = message.pagination ? CursorPaginationResponse.toJSON(message.pagination) : undefined); + return obj; + }, + + create, I>>(base?: I): WorkflowRunServiceListResponse { + return WorkflowRunServiceListResponse.fromPartial(base ?? {}); + }, + + fromPartial, I>>( + object: I, + ): WorkflowRunServiceListResponse { + const message = createBaseWorkflowRunServiceListResponse(); + message.result = object.result?.map((e) => WorkflowRunItem.fromPartial(e)) || []; + message.pagination = (object.pagination !== undefined && object.pagination !== null) + ? CursorPaginationResponse.fromPartial(object.pagination) + : undefined; + return message; + }, +}; + +function createBaseWorkflowRunServiceViewRequest(): WorkflowRunServiceViewRequest { + return { id: undefined, digest: undefined, verify: false }; +} + +export const WorkflowRunServiceViewRequest = { + encode(message: WorkflowRunServiceViewRequest, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { + if (message.id !== undefined) { + writer.uint32(10).string(message.id); + } + if (message.digest !== undefined) { + writer.uint32(18).string(message.digest); + } + if (message.verify === true) { + writer.uint32(24).bool(message.verify); + } + return writer; + }, + + decode(input: _m0.Reader | Uint8Array, length?: number): WorkflowRunServiceViewRequest { + const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input); + let end = length === undefined ? reader.len : reader.pos + length; + const message = createBaseWorkflowRunServiceViewRequest(); + while (reader.pos < end) { + const tag = reader.uint32(); + switch (tag >>> 3) { + case 1: + if (tag !== 10) { + break; + } + + message.id = reader.string(); + continue; + case 2: + if (tag !== 18) { + break; + } + + message.digest = reader.string(); + continue; + case 3: + if (tag !== 24) { + break; + } + + message.verify = reader.bool(); + continue; + } + if ((tag & 7) === 4 || tag === 0) { + break; + } + reader.skipType(tag & 7); + } + return message; + }, + + fromJSON(object: any): WorkflowRunServiceViewRequest { + return { + id: isSet(object.id) ? String(object.id) : undefined, + digest: isSet(object.digest) ? String(object.digest) : undefined, + verify: isSet(object.verify) ? Boolean(object.verify) : false, + }; + }, + + toJSON(message: WorkflowRunServiceViewRequest): unknown { + const obj: any = {}; + message.id !== undefined && (obj.id = message.id); + message.digest !== undefined && (obj.digest = message.digest); + message.verify !== undefined && (obj.verify = message.verify); + return obj; + }, + + create, I>>(base?: I): WorkflowRunServiceViewRequest { + return WorkflowRunServiceViewRequest.fromPartial(base ?? {}); + }, + + fromPartial, I>>( + object: I, + ): WorkflowRunServiceViewRequest { + const message = createBaseWorkflowRunServiceViewRequest(); + message.id = object.id ?? undefined; + message.digest = object.digest ?? undefined; + message.verify = object.verify ?? false; + return message; + }, +}; + +function createBaseWorkflowRunServiceGetProgressRequest(): WorkflowRunServiceGetProgressRequest { + return { workflowRunId: "" }; +} + +export const WorkflowRunServiceGetProgressRequest = { + encode(message: WorkflowRunServiceGetProgressRequest, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { + if (message.workflowRunId !== "") { + writer.uint32(10).string(message.workflowRunId); + } + return writer; + }, + + decode(input: _m0.Reader | Uint8Array, length?: number): WorkflowRunServiceGetProgressRequest { + const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input); + let end = length === undefined ? reader.len : reader.pos + length; + const message = createBaseWorkflowRunServiceGetProgressRequest(); + while (reader.pos < end) { + const tag = reader.uint32(); + switch (tag >>> 3) { + case 1: + if (tag !== 10) { + break; + } + + message.workflowRunId = reader.string(); + continue; + } + if ((tag & 7) === 4 || tag === 0) { + break; + } + reader.skipType(tag & 7); + } + return message; + }, + + fromJSON(object: any): WorkflowRunServiceGetProgressRequest { + return { workflowRunId: isSet(object.workflowRunId) ? String(object.workflowRunId) : "" }; + }, + + toJSON(message: WorkflowRunServiceGetProgressRequest): unknown { + const obj: any = {}; + message.workflowRunId !== undefined && (obj.workflowRunId = message.workflowRunId); + return obj; + }, + + create, I>>( + base?: I, + ): WorkflowRunServiceGetProgressRequest { + return WorkflowRunServiceGetProgressRequest.fromPartial(base ?? {}); + }, + + fromPartial, I>>( + object: I, + ): WorkflowRunServiceGetProgressRequest { + const message = createBaseWorkflowRunServiceGetProgressRequest(); + message.workflowRunId = object.workflowRunId ?? ""; + return message; + }, +}; + +function createBaseWorkflowRunServiceGetProgressResponse(): WorkflowRunServiceGetProgressResponse { + return { progress: undefined, events: [] }; } -export const WorkflowRunServiceListResponse = { - encode(message: WorkflowRunServiceListResponse, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { - for (const v of message.result) { - WorkflowRunItem.encode(v!, writer.uint32(10).fork()).ldelim(); +export const WorkflowRunServiceGetProgressResponse = { + encode(message: WorkflowRunServiceGetProgressResponse, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { + if (message.progress !== undefined) { + WorkflowRunProgress.encode(message.progress, writer.uint32(10).fork()).ldelim(); } - if (message.pagination !== undefined) { - CursorPaginationResponse.encode(message.pagination, writer.uint32(18).fork()).ldelim(); + for (const v of message.events) { + WorkflowRunEvent.encode(v!, writer.uint32(18).fork()).ldelim(); } return writer; }, - decode(input: _m0.Reader | Uint8Array, length?: number): WorkflowRunServiceListResponse { + decode(input: _m0.Reader | Uint8Array, length?: number): WorkflowRunServiceGetProgressResponse { const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input); let end = length === undefined ? reader.len : reader.pos + length; - const message = createBaseWorkflowRunServiceListResponse(); + const message = createBaseWorkflowRunServiceGetProgressResponse(); while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { @@ -2169,14 +3584,14 @@ export const WorkflowRunServiceListResponse = { break; } - message.result.push(WorkflowRunItem.decode(reader, reader.uint32())); + message.progress = WorkflowRunProgress.decode(reader, reader.uint32()); continue; case 2: if (tag !== 18) { break; } - message.pagination = CursorPaginationResponse.decode(reader, reader.uint32()); + message.events.push(WorkflowRunEvent.decode(reader, reader.uint32())); continue; } if ((tag & 7) === 4 || tag === 0) { @@ -2187,63 +3602,68 @@ export const WorkflowRunServiceListResponse = { return message; }, - fromJSON(object: any): WorkflowRunServiceListResponse { + fromJSON(object: any): WorkflowRunServiceGetProgressResponse { return { - result: Array.isArray(object?.result) ? object.result.map((e: any) => WorkflowRunItem.fromJSON(e)) : [], - pagination: isSet(object.pagination) ? CursorPaginationResponse.fromJSON(object.pagination) : undefined, + progress: isSet(object.progress) ? WorkflowRunProgress.fromJSON(object.progress) : undefined, + events: Array.isArray(object?.events) ? object.events.map((e: any) => WorkflowRunEvent.fromJSON(e)) : [], }; }, - toJSON(message: WorkflowRunServiceListResponse): unknown { + toJSON(message: WorkflowRunServiceGetProgressResponse): unknown { const obj: any = {}; - if (message.result) { - obj.result = message.result.map((e) => e ? WorkflowRunItem.toJSON(e) : undefined); + message.progress !== undefined && + (obj.progress = message.progress ? WorkflowRunProgress.toJSON(message.progress) : undefined); + if (message.events) { + obj.events = message.events.map((e) => e ? WorkflowRunEvent.toJSON(e) : undefined); } else { - obj.result = []; + obj.events = []; } - message.pagination !== undefined && - (obj.pagination = message.pagination ? CursorPaginationResponse.toJSON(message.pagination) : undefined); return obj; }, - create, I>>(base?: I): WorkflowRunServiceListResponse { - return WorkflowRunServiceListResponse.fromPartial(base ?? {}); + create, I>>( + base?: I, + ): WorkflowRunServiceGetProgressResponse { + return WorkflowRunServiceGetProgressResponse.fromPartial(base ?? {}); }, - fromPartial, I>>( + fromPartial, I>>( object: I, - ): WorkflowRunServiceListResponse { - const message = createBaseWorkflowRunServiceListResponse(); - message.result = object.result?.map((e) => WorkflowRunItem.fromPartial(e)) || []; - message.pagination = (object.pagination !== undefined && object.pagination !== null) - ? CursorPaginationResponse.fromPartial(object.pagination) + ): WorkflowRunServiceGetProgressResponse { + const message = createBaseWorkflowRunServiceGetProgressResponse(); + message.progress = (object.progress !== undefined && object.progress !== null) + ? WorkflowRunProgress.fromPartial(object.progress) : undefined; + message.events = object.events?.map((e) => WorkflowRunEvent.fromPartial(e)) || []; return message; }, }; -function createBaseWorkflowRunServiceViewRequest(): WorkflowRunServiceViewRequest { - return { id: undefined, digest: undefined, verify: false }; +function createBaseWorkflowRunProgress(): WorkflowRunProgress { + return { materials: [], requiredTotal: 0, requiredProvided: 0, attestationPolicies: undefined }; } -export const WorkflowRunServiceViewRequest = { - encode(message: WorkflowRunServiceViewRequest, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { - if (message.id !== undefined) { - writer.uint32(10).string(message.id); +export const WorkflowRunProgress = { + encode(message: WorkflowRunProgress, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { + for (const v of message.materials) { + WorkflowRunProgress_Material.encode(v!, writer.uint32(10).fork()).ldelim(); } - if (message.digest !== undefined) { - writer.uint32(18).string(message.digest); + if (message.requiredTotal !== 0) { + writer.uint32(16).int32(message.requiredTotal); } - if (message.verify === true) { - writer.uint32(24).bool(message.verify); + if (message.requiredProvided !== 0) { + writer.uint32(24).int32(message.requiredProvided); + } + if (message.attestationPolicies !== undefined) { + WorkflowRunEvent_PolicyCounts.encode(message.attestationPolicies, writer.uint32(34).fork()).ldelim(); } return writer; }, - decode(input: _m0.Reader | Uint8Array, length?: number): WorkflowRunServiceViewRequest { + decode(input: _m0.Reader | Uint8Array, length?: number): WorkflowRunProgress { const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input); let end = length === undefined ? reader.len : reader.pos + length; - const message = createBaseWorkflowRunServiceViewRequest(); + const message = createBaseWorkflowRunProgress(); while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { @@ -2252,21 +3672,197 @@ export const WorkflowRunServiceViewRequest = { break; } - message.id = reader.string(); + message.materials.push(WorkflowRunProgress_Material.decode(reader, reader.uint32())); + continue; + case 2: + if (tag !== 16) { + break; + } + + message.requiredTotal = reader.int32(); + continue; + case 3: + if (tag !== 24) { + break; + } + + message.requiredProvided = reader.int32(); + continue; + case 4: + if (tag !== 34) { + break; + } + + message.attestationPolicies = WorkflowRunEvent_PolicyCounts.decode(reader, reader.uint32()); + continue; + } + if ((tag & 7) === 4 || tag === 0) { + break; + } + reader.skipType(tag & 7); + } + return message; + }, + + fromJSON(object: any): WorkflowRunProgress { + return { + materials: Array.isArray(object?.materials) + ? object.materials.map((e: any) => WorkflowRunProgress_Material.fromJSON(e)) + : [], + requiredTotal: isSet(object.requiredTotal) ? Number(object.requiredTotal) : 0, + requiredProvided: isSet(object.requiredProvided) ? Number(object.requiredProvided) : 0, + attestationPolicies: isSet(object.attestationPolicies) + ? WorkflowRunEvent_PolicyCounts.fromJSON(object.attestationPolicies) + : undefined, + }; + }, + + toJSON(message: WorkflowRunProgress): unknown { + const obj: any = {}; + if (message.materials) { + obj.materials = message.materials.map((e) => e ? WorkflowRunProgress_Material.toJSON(e) : undefined); + } else { + obj.materials = []; + } + message.requiredTotal !== undefined && (obj.requiredTotal = Math.round(message.requiredTotal)); + message.requiredProvided !== undefined && (obj.requiredProvided = Math.round(message.requiredProvided)); + message.attestationPolicies !== undefined && (obj.attestationPolicies = message.attestationPolicies + ? WorkflowRunEvent_PolicyCounts.toJSON(message.attestationPolicies) + : undefined); + return obj; + }, + + create, I>>(base?: I): WorkflowRunProgress { + return WorkflowRunProgress.fromPartial(base ?? {}); + }, + + fromPartial, I>>(object: I): WorkflowRunProgress { + const message = createBaseWorkflowRunProgress(); + message.materials = object.materials?.map((e) => WorkflowRunProgress_Material.fromPartial(e)) || []; + message.requiredTotal = object.requiredTotal ?? 0; + message.requiredProvided = object.requiredProvided ?? 0; + message.attestationPolicies = (object.attestationPolicies !== undefined && object.attestationPolicies !== null) + ? WorkflowRunEvent_PolicyCounts.fromPartial(object.attestationPolicies) + : undefined; + return message; + }, +}; + +function createBaseWorkflowRunProgress_Material(): WorkflowRunProgress_Material { + return { + name: "", + materialType: "", + requirement: 0, + group: "", + status: 0, + value: "", + policies: undefined, + lastError: "", + failedAttempts: 0, + }; +} + +export const WorkflowRunProgress_Material = { + encode(message: WorkflowRunProgress_Material, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { + if (message.name !== "") { + writer.uint32(10).string(message.name); + } + if (message.materialType !== "") { + writer.uint32(18).string(message.materialType); + } + if (message.requirement !== 0) { + writer.uint32(24).int32(message.requirement); + } + if (message.group !== "") { + writer.uint32(34).string(message.group); + } + if (message.status !== 0) { + writer.uint32(40).int32(message.status); + } + if (message.value !== "") { + writer.uint32(50).string(message.value); + } + if (message.policies !== undefined) { + WorkflowRunEvent_PolicyCounts.encode(message.policies, writer.uint32(58).fork()).ldelim(); + } + if (message.lastError !== "") { + writer.uint32(66).string(message.lastError); + } + if (message.failedAttempts !== 0) { + writer.uint32(72).int32(message.failedAttempts); + } + return writer; + }, + + decode(input: _m0.Reader | Uint8Array, length?: number): WorkflowRunProgress_Material { + const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input); + let end = length === undefined ? reader.len : reader.pos + length; + const message = createBaseWorkflowRunProgress_Material(); + while (reader.pos < end) { + const tag = reader.uint32(); + switch (tag >>> 3) { + case 1: + if (tag !== 10) { + break; + } + + message.name = reader.string(); continue; case 2: if (tag !== 18) { break; } - message.digest = reader.string(); + message.materialType = reader.string(); continue; case 3: if (tag !== 24) { break; } - message.verify = reader.bool(); + message.requirement = reader.int32() as any; + continue; + case 4: + if (tag !== 34) { + break; + } + + message.group = reader.string(); + continue; + case 5: + if (tag !== 40) { + break; + } + + message.status = reader.int32() as any; + continue; + case 6: + if (tag !== 50) { + break; + } + + message.value = reader.string(); + continue; + case 7: + if (tag !== 58) { + break; + } + + message.policies = WorkflowRunEvent_PolicyCounts.decode(reader, reader.uint32()); + continue; + case 8: + if (tag !== 66) { + break; + } + + message.lastError = reader.string(); + continue; + case 9: + if (tag !== 72) { + break; + } + + message.failedAttempts = reader.int32(); continue; } if ((tag & 7) === 4 || tag === 0) { @@ -2277,33 +3873,52 @@ export const WorkflowRunServiceViewRequest = { return message; }, - fromJSON(object: any): WorkflowRunServiceViewRequest { + fromJSON(object: any): WorkflowRunProgress_Material { return { - id: isSet(object.id) ? String(object.id) : undefined, - digest: isSet(object.digest) ? String(object.digest) : undefined, - verify: isSet(object.verify) ? Boolean(object.verify) : false, + name: isSet(object.name) ? String(object.name) : "", + materialType: isSet(object.materialType) ? String(object.materialType) : "", + requirement: isSet(object.requirement) ? workflowRunProgress_RequirementFromJSON(object.requirement) : 0, + group: isSet(object.group) ? String(object.group) : "", + status: isSet(object.status) ? workflowRunProgress_StatusFromJSON(object.status) : 0, + value: isSet(object.value) ? String(object.value) : "", + policies: isSet(object.policies) ? WorkflowRunEvent_PolicyCounts.fromJSON(object.policies) : undefined, + lastError: isSet(object.lastError) ? String(object.lastError) : "", + failedAttempts: isSet(object.failedAttempts) ? Number(object.failedAttempts) : 0, }; }, - toJSON(message: WorkflowRunServiceViewRequest): unknown { + toJSON(message: WorkflowRunProgress_Material): unknown { const obj: any = {}; - message.id !== undefined && (obj.id = message.id); - message.digest !== undefined && (obj.digest = message.digest); - message.verify !== undefined && (obj.verify = message.verify); + message.name !== undefined && (obj.name = message.name); + message.materialType !== undefined && (obj.materialType = message.materialType); + message.requirement !== undefined && (obj.requirement = workflowRunProgress_RequirementToJSON(message.requirement)); + message.group !== undefined && (obj.group = message.group); + message.status !== undefined && (obj.status = workflowRunProgress_StatusToJSON(message.status)); + message.value !== undefined && (obj.value = message.value); + message.policies !== undefined && + (obj.policies = message.policies ? WorkflowRunEvent_PolicyCounts.toJSON(message.policies) : undefined); + message.lastError !== undefined && (obj.lastError = message.lastError); + message.failedAttempts !== undefined && (obj.failedAttempts = Math.round(message.failedAttempts)); return obj; }, - create, I>>(base?: I): WorkflowRunServiceViewRequest { - return WorkflowRunServiceViewRequest.fromPartial(base ?? {}); + create, I>>(base?: I): WorkflowRunProgress_Material { + return WorkflowRunProgress_Material.fromPartial(base ?? {}); }, - fromPartial, I>>( - object: I, - ): WorkflowRunServiceViewRequest { - const message = createBaseWorkflowRunServiceViewRequest(); - message.id = object.id ?? undefined; - message.digest = object.digest ?? undefined; - message.verify = object.verify ?? false; + fromPartial, I>>(object: I): WorkflowRunProgress_Material { + const message = createBaseWorkflowRunProgress_Material(); + message.name = object.name ?? ""; + message.materialType = object.materialType ?? ""; + message.requirement = object.requirement ?? 0; + message.group = object.group ?? ""; + message.status = object.status ?? 0; + message.value = object.value ?? ""; + message.policies = (object.policies !== undefined && object.policies !== null) + ? WorkflowRunEvent_PolicyCounts.fromPartial(object.policies) + : undefined; + message.lastError = object.lastError ?? ""; + message.failedAttempts = object.failedAttempts ?? 0; return message; }, }; @@ -2800,6 +4415,11 @@ export interface AttestationService { request: DeepPartial, metadata?: grpc.Metadata, ): Promise; + /** Record a progress event on a run that is in progress. Informational only. */ + RecordEvent( + request: DeepPartial, + metadata?: grpc.Metadata, + ): Promise; /** Get policies from remote providers */ GetPolicy( request: DeepPartial, @@ -2822,6 +4442,7 @@ export class AttestationServiceClientImpl implements AttestationService { this.Store = this.Store.bind(this); this.GetUploadCreds = this.GetUploadCreds.bind(this); this.Cancel = this.Cancel.bind(this); + this.RecordEvent = this.RecordEvent.bind(this); this.GetPolicy = this.GetPolicy.bind(this); this.GetPolicyGroup = this.GetPolicyGroup.bind(this); } @@ -2880,6 +4501,17 @@ export class AttestationServiceClientImpl implements AttestationService { return this.rpc.unary(AttestationServiceCancelDesc, AttestationServiceCancelRequest.fromPartial(request), metadata); } + RecordEvent( + request: DeepPartial, + metadata?: grpc.Metadata, + ): Promise { + return this.rpc.unary( + AttestationServiceRecordEventDesc, + AttestationServiceRecordEventRequest.fromPartial(request), + metadata, + ); + } + GetPolicy( request: DeepPartial, metadata?: grpc.Metadata, @@ -3043,6 +4675,29 @@ export const AttestationServiceCancelDesc: UnaryMethodDefinitionish = { } as any, }; +export const AttestationServiceRecordEventDesc: UnaryMethodDefinitionish = { + methodName: "RecordEvent", + service: AttestationServiceDesc, + requestStream: false, + responseStream: false, + requestType: { + serializeBinary() { + return AttestationServiceRecordEventRequest.encode(this).finish(); + }, + } as any, + responseType: { + deserializeBinary(data: Uint8Array) { + const value = AttestationServiceRecordEventResponse.decode(data); + return { + ...value, + toObject() { + return value; + }, + }; + }, + } as any, +}; + export const AttestationServiceGetPolicyDesc: UnaryMethodDefinitionish = { methodName: "GetPolicy", service: AttestationServiceDesc, @@ -3099,6 +4754,11 @@ export interface WorkflowRunService { request: DeepPartial, metadata?: grpc.Metadata, ): Promise; + /** Progress and timeline of a run. Clients poll it while the run is in progress. */ + GetProgress( + request: DeepPartial, + metadata?: grpc.Metadata, + ): Promise; } export class WorkflowRunServiceClientImpl implements WorkflowRunService { @@ -3108,6 +4768,7 @@ export class WorkflowRunServiceClientImpl implements WorkflowRunService { this.rpc = rpc; this.List = this.List.bind(this); this.View = this.View.bind(this); + this.GetProgress = this.GetProgress.bind(this); } List( @@ -3123,6 +4784,17 @@ export class WorkflowRunServiceClientImpl implements WorkflowRunService { ): Promise { return this.rpc.unary(WorkflowRunServiceViewDesc, WorkflowRunServiceViewRequest.fromPartial(request), metadata); } + + GetProgress( + request: DeepPartial, + metadata?: grpc.Metadata, + ): Promise { + return this.rpc.unary( + WorkflowRunServiceGetProgressDesc, + WorkflowRunServiceGetProgressRequest.fromPartial(request), + metadata, + ); + } } export const WorkflowRunServiceDesc = { serviceName: "controlplane.v1.WorkflowRunService" }; @@ -3173,6 +4845,29 @@ export const WorkflowRunServiceViewDesc: UnaryMethodDefinitionish = { } as any, }; +export const WorkflowRunServiceGetProgressDesc: UnaryMethodDefinitionish = { + methodName: "GetProgress", + service: WorkflowRunServiceDesc, + requestStream: false, + responseStream: false, + requestType: { + serializeBinary() { + return WorkflowRunServiceGetProgressRequest.encode(this).finish(); + }, + } as any, + responseType: { + deserializeBinary(data: Uint8Array) { + const value = WorkflowRunServiceGetProgressResponse.decode(data); + return { + ...value, + toObject() { + return value; + }, + }; + }, + } as any, +}; + interface UnaryMethodDefinitionishR extends grpc.UnaryMethodDefinition { requestStream: any; responseStream: any; @@ -3296,6 +4991,28 @@ type KeysOfUnion = T extends T ? keyof T : never; export type Exact = P extends Builtin ? P : P & { [K in keyof P]: Exact } & { [K in Exclude>]: never }; +function toTimestamp(date: Date): Timestamp { + const seconds = date.getTime() / 1_000; + const nanos = (date.getTime() % 1_000) * 1_000_000; + return { seconds, nanos }; +} + +function fromTimestamp(t: Timestamp): Date { + let millis = (t.seconds || 0) * 1_000; + millis += (t.nanos || 0) / 1_000_000; + return new Date(millis); +} + +function fromJsonTimestamp(o: any): Date { + if (o instanceof Date) { + return o; + } else if (typeof o === "string") { + return new Date(o); + } else { + return fromTimestamp(Timestamp.fromJSON(o)); + } +} + function isSet(value: any): boolean { return value !== null && value !== undefined; } diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.AttestationServiceRecordEventRequest.jsonschema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.AttestationServiceRecordEventRequest.jsonschema.json new file mode 100644 index 000000000..649967229 --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.AttestationServiceRecordEventRequest.jsonschema.json @@ -0,0 +1,26 @@ +{ + "$id": "controlplane.v1.AttestationServiceRecordEventRequest.jsonschema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "patternProperties": { + "^(workflow_run_id)$": { + "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$", + "type": "string" + } + }, + "properties": { + "event": { + "$ref": "controlplane.v1.WorkflowRunEvent.jsonschema.json", + "description": "id, created_at, and source are set by the server and ignored here." + }, + "workflowRunId": { + "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$", + "type": "string" + } + }, + "required": [ + "event" + ], + "title": "Attestation Service Record Event Request", + "type": "object" +} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.AttestationServiceRecordEventRequest.schema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.AttestationServiceRecordEventRequest.schema.json new file mode 100644 index 000000000..a9746d24b --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.AttestationServiceRecordEventRequest.schema.json @@ -0,0 +1,26 @@ +{ + "$id": "controlplane.v1.AttestationServiceRecordEventRequest.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "patternProperties": { + "^(workflowRunId)$": { + "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$", + "type": "string" + } + }, + "properties": { + "event": { + "$ref": "controlplane.v1.WorkflowRunEvent.schema.json", + "description": "id, created_at, and source are set by the server and ignored here." + }, + "workflow_run_id": { + "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$", + "type": "string" + } + }, + "required": [ + "event" + ], + "title": "Attestation Service Record Event Request", + "type": "object" +} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.AttestationServiceRecordEventResponse.jsonschema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.AttestationServiceRecordEventResponse.jsonschema.json new file mode 100644 index 000000000..b1f1e9d09 --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.AttestationServiceRecordEventResponse.jsonschema.json @@ -0,0 +1,8 @@ +{ + "$id": "controlplane.v1.AttestationServiceRecordEventResponse.jsonschema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": {}, + "title": "Attestation Service Record Event Response", + "type": "object" +} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.AttestationServiceRecordEventResponse.schema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.AttestationServiceRecordEventResponse.schema.json new file mode 100644 index 000000000..f71c84a52 --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.AttestationServiceRecordEventResponse.schema.json @@ -0,0 +1,8 @@ +{ + "$id": "controlplane.v1.AttestationServiceRecordEventResponse.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": {}, + "title": "Attestation Service Record Event Response", + "type": "object" +} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.AttestationAttributes.jsonschema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.AttestationAttributes.jsonschema.json new file mode 100644 index 000000000..ba098aec5 --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.AttestationAttributes.jsonschema.json @@ -0,0 +1,77 @@ +{ + "$id": "controlplane.v1.WorkflowRunEvent.AttestationAttributes.jsonschema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "patternProperties": { + "^(attestation_digest)$": { + "maxLength": 256, + "type": "string" + }, + "^(cli_version)$": { + "maxLength": 256, + "type": "string" + }, + "^(contract_name)$": { + "maxLength": 256, + "type": "string" + }, + "^(contract_revision)$": { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + "^(expected_materials)$": { + "description": "the materials that the attestation expects, from the contract and its policy groups,\n as init resolves them. Set on the start event.", + "items": { + "$ref": "controlplane.v1.WorkflowRunEvent.ExpectedMaterial.jsonschema.json" + }, + "type": "array" + }, + "^(remote_state)$": { + "type": "boolean" + }, + "^(runner_type)$": { + "maxLength": 256, + "type": "string" + } + }, + "properties": { + "attestationDigest": { + "maxLength": 256, + "type": "string" + }, + "cliVersion": { + "maxLength": 256, + "type": "string" + }, + "contractName": { + "maxLength": 256, + "type": "string" + }, + "contractRevision": { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + "expectedMaterials": { + "description": "the materials that the attestation expects, from the contract and its policy groups,\n as init resolves them. Set on the start event.", + "items": { + "$ref": "controlplane.v1.WorkflowRunEvent.ExpectedMaterial.jsonschema.json" + }, + "type": "array" + }, + "policies": { + "$ref": "controlplane.v1.WorkflowRunEvent.PolicyCounts.jsonschema.json", + "description": "results of the attestation policies evaluated at init" + }, + "remoteState": { + "type": "boolean" + }, + "runnerType": { + "maxLength": 256, + "type": "string" + } + }, + "title": "Attestation Attributes", + "type": "object" +} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.AttestationAttributes.schema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.AttestationAttributes.schema.json new file mode 100644 index 000000000..1fb51db33 --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.AttestationAttributes.schema.json @@ -0,0 +1,77 @@ +{ + "$id": "controlplane.v1.WorkflowRunEvent.AttestationAttributes.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "patternProperties": { + "^(attestationDigest)$": { + "maxLength": 256, + "type": "string" + }, + "^(cliVersion)$": { + "maxLength": 256, + "type": "string" + }, + "^(contractName)$": { + "maxLength": 256, + "type": "string" + }, + "^(contractRevision)$": { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + "^(expectedMaterials)$": { + "description": "the materials that the attestation expects, from the contract and its policy groups,\n as init resolves them. Set on the start event.", + "items": { + "$ref": "controlplane.v1.WorkflowRunEvent.ExpectedMaterial.schema.json" + }, + "type": "array" + }, + "^(remoteState)$": { + "type": "boolean" + }, + "^(runnerType)$": { + "maxLength": 256, + "type": "string" + } + }, + "properties": { + "attestation_digest": { + "maxLength": 256, + "type": "string" + }, + "cli_version": { + "maxLength": 256, + "type": "string" + }, + "contract_name": { + "maxLength": 256, + "type": "string" + }, + "contract_revision": { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + "expected_materials": { + "description": "the materials that the attestation expects, from the contract and its policy groups,\n as init resolves them. Set on the start event.", + "items": { + "$ref": "controlplane.v1.WorkflowRunEvent.ExpectedMaterial.schema.json" + }, + "type": "array" + }, + "policies": { + "$ref": "controlplane.v1.WorkflowRunEvent.PolicyCounts.schema.json", + "description": "results of the attestation policies evaluated at init" + }, + "remote_state": { + "type": "boolean" + }, + "runner_type": { + "maxLength": 256, + "type": "string" + } + }, + "title": "Attestation Attributes", + "type": "object" +} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.ExpectedMaterial.jsonschema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.ExpectedMaterial.jsonschema.json new file mode 100644 index 000000000..261a5862a --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.ExpectedMaterial.jsonschema.json @@ -0,0 +1,31 @@ +{ + "$id": "controlplane.v1.WorkflowRunEvent.ExpectedMaterial.jsonschema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "patternProperties": { + "^(material_type)$": { + "maxLength": 256, + "type": "string" + } + }, + "properties": { + "group": { + "description": "set when the material is one of a group, of which one is required", + "maxLength": 256, + "type": "string" + }, + "materialType": { + "maxLength": 256, + "type": "string" + }, + "name": { + "maxLength": 256, + "type": "string" + }, + "optional": { + "type": "boolean" + } + }, + "title": "Expected Material", + "type": "object" +} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.ExpectedMaterial.schema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.ExpectedMaterial.schema.json new file mode 100644 index 000000000..f2df517c1 --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.ExpectedMaterial.schema.json @@ -0,0 +1,31 @@ +{ + "$id": "controlplane.v1.WorkflowRunEvent.ExpectedMaterial.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "patternProperties": { + "^(materialType)$": { + "maxLength": 256, + "type": "string" + } + }, + "properties": { + "group": { + "description": "set when the material is one of a group, of which one is required", + "maxLength": 256, + "type": "string" + }, + "material_type": { + "maxLength": 256, + "type": "string" + }, + "name": { + "maxLength": 256, + "type": "string" + }, + "optional": { + "type": "boolean" + } + }, + "title": "Expected Material", + "type": "object" +} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.MaterialAttributes.jsonschema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.MaterialAttributes.jsonschema.json new file mode 100644 index 000000000..3ff751bbb --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.MaterialAttributes.jsonschema.json @@ -0,0 +1,47 @@ +{ + "$id": "controlplane.v1.WorkflowRunEvent.MaterialAttributes.jsonschema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "patternProperties": { + "^(added_by_collector)$": { + "type": "boolean" + }, + "^(in_contract)$": { + "type": "boolean" + }, + "^(material_type)$": { + "maxLength": 256, + "type": "string" + } + }, + "properties": { + "addedByCollector": { + "type": "boolean" + }, + "digest": { + "maxLength": 256, + "type": "string" + }, + "inContract": { + "type": "boolean" + }, + "materialType": { + "maxLength": 256, + "type": "string" + }, + "name": { + "maxLength": 256, + "type": "string" + }, + "policies": { + "$ref": "controlplane.v1.WorkflowRunEvent.PolicyCounts.jsonschema.json" + }, + "value": { + "description": "value shown by attestation status, cut to 256 characters", + "maxLength": 256, + "type": "string" + } + }, + "title": "Material Attributes", + "type": "object" +} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.MaterialAttributes.schema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.MaterialAttributes.schema.json new file mode 100644 index 000000000..eb4562d1e --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.MaterialAttributes.schema.json @@ -0,0 +1,47 @@ +{ + "$id": "controlplane.v1.WorkflowRunEvent.MaterialAttributes.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "patternProperties": { + "^(addedByCollector)$": { + "type": "boolean" + }, + "^(inContract)$": { + "type": "boolean" + }, + "^(materialType)$": { + "maxLength": 256, + "type": "string" + } + }, + "properties": { + "added_by_collector": { + "type": "boolean" + }, + "digest": { + "maxLength": 256, + "type": "string" + }, + "in_contract": { + "type": "boolean" + }, + "material_type": { + "maxLength": 256, + "type": "string" + }, + "name": { + "maxLength": 256, + "type": "string" + }, + "policies": { + "$ref": "controlplane.v1.WorkflowRunEvent.PolicyCounts.schema.json" + }, + "value": { + "description": "value shown by attestation status, cut to 256 characters", + "maxLength": 256, + "type": "string" + } + }, + "title": "Material Attributes", + "type": "object" +} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PolicyCounts.jsonschema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PolicyCounts.jsonschema.json new file mode 100644 index 000000000..cefc1f7d8 --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PolicyCounts.jsonschema.json @@ -0,0 +1,45 @@ +{ + "$id": "controlplane.v1.WorkflowRunEvent.PolicyCounts.jsonschema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "patternProperties": { + "^(violated_policies)$": { + "items": { + "maxLength": 256, + "type": "string" + }, + "type": "array" + } + }, + "properties": { + "evaluated": { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + "passed": { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + "skipped": { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + "violated": { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + "violatedPolicies": { + "items": { + "maxLength": 256, + "type": "string" + }, + "type": "array" + } + }, + "title": "Policy Counts", + "type": "object" +} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PolicyCounts.schema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PolicyCounts.schema.json new file mode 100644 index 000000000..f2efede98 --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PolicyCounts.schema.json @@ -0,0 +1,45 @@ +{ + "$id": "controlplane.v1.WorkflowRunEvent.PolicyCounts.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "patternProperties": { + "^(violatedPolicies)$": { + "items": { + "maxLength": 256, + "type": "string" + }, + "type": "array" + } + }, + "properties": { + "evaluated": { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + "passed": { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + "skipped": { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + "violated": { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + "violated_policies": { + "items": { + "maxLength": 256, + "type": "string" + }, + "type": "array" + } + }, + "title": "Policy Counts", + "type": "object" +} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.jsonschema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.jsonschema.json new file mode 100644 index 000000000..0a9901f11 --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.jsonschema.json @@ -0,0 +1,95 @@ +{ + "$id": "controlplane.v1.WorkflowRunEvent.jsonschema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "A progress event of a workflow run. Unsigned and informational only.\n It is never part of the attestation.", + "patternProperties": { + "^(created_at)$": { + "$ref": "google.protobuf.Timestamp.jsonschema.json", + "description": "Time the control plane received the event" + } + }, + "properties": { + "attestation": { + "$ref": "controlplane.v1.WorkflowRunEvent.AttestationAttributes.jsonschema.json" + }, + "createdAt": { + "$ref": "google.protobuf.Timestamp.jsonschema.json", + "description": "Time the control plane received the event" + }, + "id": { + "type": "string" + }, + "key": { + "description": "Events with the same key are one step of the timeline", + "maxLength": 128, + "minLength": 1, + "type": "string" + }, + "material": { + "$ref": "controlplane.v1.WorkflowRunEvent.MaterialAttributes.jsonschema.json" + }, + "message": { + "maxLength": 1024, + "type": "string" + }, + "source": { + "anyOf": [ + { + "enum": [ + "SOURCE_UNSPECIFIED", + "SOURCE_CLI", + "SOURCE_CONTROL_PLANE" + ], + "title": "Source", + "type": "string" + }, + { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + } + ] + }, + "status": { + "anyOf": [ + { + "enum": [ + "STATUS_UNSPECIFIED", + "STATUS_STARTED", + "STATUS_SUCCEEDED", + "STATUS_FAILED", + "STATUS_CANCELED" + ], + "title": "Status", + "type": "string" + }, + { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + } + ] + }, + "type": { + "anyOf": [ + { + "enum": [ + "TYPE_UNSPECIFIED", + "TYPE_ATTESTATION", + "TYPE_MATERIAL" + ], + "title": "Type", + "type": "string" + }, + { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + } + ] + } + }, + "title": "Workflow Run Event", + "type": "object" +} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.schema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.schema.json new file mode 100644 index 000000000..0f335e9c3 --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.schema.json @@ -0,0 +1,95 @@ +{ + "$id": "controlplane.v1.WorkflowRunEvent.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "A progress event of a workflow run. Unsigned and informational only.\n It is never part of the attestation.", + "patternProperties": { + "^(createdAt)$": { + "$ref": "google.protobuf.Timestamp.schema.json", + "description": "Time the control plane received the event" + } + }, + "properties": { + "attestation": { + "$ref": "controlplane.v1.WorkflowRunEvent.AttestationAttributes.schema.json" + }, + "created_at": { + "$ref": "google.protobuf.Timestamp.schema.json", + "description": "Time the control plane received the event" + }, + "id": { + "type": "string" + }, + "key": { + "description": "Events with the same key are one step of the timeline", + "maxLength": 128, + "minLength": 1, + "type": "string" + }, + "material": { + "$ref": "controlplane.v1.WorkflowRunEvent.MaterialAttributes.schema.json" + }, + "message": { + "maxLength": 1024, + "type": "string" + }, + "source": { + "anyOf": [ + { + "enum": [ + "SOURCE_UNSPECIFIED", + "SOURCE_CLI", + "SOURCE_CONTROL_PLANE" + ], + "title": "Source", + "type": "string" + }, + { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + } + ] + }, + "status": { + "anyOf": [ + { + "enum": [ + "STATUS_UNSPECIFIED", + "STATUS_STARTED", + "STATUS_SUCCEEDED", + "STATUS_FAILED", + "STATUS_CANCELED" + ], + "title": "Status", + "type": "string" + }, + { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + } + ] + }, + "type": { + "anyOf": [ + { + "enum": [ + "TYPE_UNSPECIFIED", + "TYPE_ATTESTATION", + "TYPE_MATERIAL" + ], + "title": "Type", + "type": "string" + }, + { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + } + ] + } + }, + "title": "Workflow Run Event", + "type": "object" +} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunProgress.Material.jsonschema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunProgress.Material.jsonschema.json new file mode 100644 index 000000000..9c44d3532 --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunProgress.Material.jsonschema.json @@ -0,0 +1,88 @@ +{ + "$id": "controlplane.v1.WorkflowRunProgress.Material.jsonschema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "patternProperties": { + "^(failed_attempts)$": { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + "^(last_error)$": { + "description": "Error of the last failed add, also after a successful one", + "type": "string" + }, + "^(material_type)$": { + "type": "string" + } + }, + "properties": { + "failedAttempts": { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + "group": { + "description": "Set when the requirement is ONE_OF_GROUP", + "type": "string" + }, + "lastError": { + "description": "Error of the last failed add, also after a successful one", + "type": "string" + }, + "materialType": { + "type": "string" + }, + "name": { + "type": "string" + }, + "policies": { + "$ref": "controlplane.v1.WorkflowRunEvent.PolicyCounts.jsonschema.json" + }, + "requirement": { + "anyOf": [ + { + "enum": [ + "REQUIREMENT_UNSPECIFIED", + "REQUIREMENT_REQUIRED", + "REQUIREMENT_OPTIONAL", + "REQUIREMENT_ONE_OF_GROUP", + "REQUIREMENT_NOT_IN_CONTRACT" + ], + "title": "Requirement", + "type": "string" + }, + { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + } + ] + }, + "status": { + "anyOf": [ + { + "enum": [ + "STATUS_UNSPECIFIED", + "STATUS_MISSING", + "STATUS_PROVIDED", + "STATUS_FAILED" + ], + "title": "Status", + "type": "string" + }, + { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + } + ] + }, + "value": { + "description": "Value and policy results of the last successful add", + "type": "string" + } + }, + "title": "Material", + "type": "object" +} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunProgress.Material.schema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunProgress.Material.schema.json new file mode 100644 index 000000000..353940ff0 --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunProgress.Material.schema.json @@ -0,0 +1,88 @@ +{ + "$id": "controlplane.v1.WorkflowRunProgress.Material.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "patternProperties": { + "^(failedAttempts)$": { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + "^(lastError)$": { + "description": "Error of the last failed add, also after a successful one", + "type": "string" + }, + "^(materialType)$": { + "type": "string" + } + }, + "properties": { + "failed_attempts": { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + "group": { + "description": "Set when the requirement is ONE_OF_GROUP", + "type": "string" + }, + "last_error": { + "description": "Error of the last failed add, also after a successful one", + "type": "string" + }, + "material_type": { + "type": "string" + }, + "name": { + "type": "string" + }, + "policies": { + "$ref": "controlplane.v1.WorkflowRunEvent.PolicyCounts.schema.json" + }, + "requirement": { + "anyOf": [ + { + "enum": [ + "REQUIREMENT_UNSPECIFIED", + "REQUIREMENT_REQUIRED", + "REQUIREMENT_OPTIONAL", + "REQUIREMENT_ONE_OF_GROUP", + "REQUIREMENT_NOT_IN_CONTRACT" + ], + "title": "Requirement", + "type": "string" + }, + { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + } + ] + }, + "status": { + "anyOf": [ + { + "enum": [ + "STATUS_UNSPECIFIED", + "STATUS_MISSING", + "STATUS_PROVIDED", + "STATUS_FAILED" + ], + "title": "Status", + "type": "string" + }, + { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + } + ] + }, + "value": { + "description": "Value and policy results of the last successful add", + "type": "string" + } + }, + "title": "Material", + "type": "object" +} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunProgress.jsonschema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunProgress.jsonschema.json new file mode 100644 index 000000000..aef88894e --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunProgress.jsonschema.json @@ -0,0 +1,49 @@ +{ + "$id": "controlplane.v1.WorkflowRunProgress.jsonschema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "The progress of a run in progress, ready to show", + "patternProperties": { + "^(attestation_policies)$": { + "$ref": "controlplane.v1.WorkflowRunEvent.PolicyCounts.jsonschema.json", + "description": "Results of the attestation policies evaluated at init" + }, + "^(required_provided)$": { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + "^(required_total)$": { + "description": "Required materials, where a group of materials counts once", + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + } + }, + "properties": { + "attestationPolicies": { + "$ref": "controlplane.v1.WorkflowRunEvent.PolicyCounts.jsonschema.json", + "description": "Results of the attestation policies evaluated at init" + }, + "materials": { + "description": "One row for each expected material, in contract order, then the materials not in the contract", + "items": { + "$ref": "controlplane.v1.WorkflowRunProgress.Material.jsonschema.json" + }, + "type": "array" + }, + "requiredProvided": { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + "requiredTotal": { + "description": "Required materials, where a group of materials counts once", + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + } + }, + "title": "Workflow Run Progress", + "type": "object" +} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunProgress.schema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunProgress.schema.json new file mode 100644 index 000000000..83ee910fe --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunProgress.schema.json @@ -0,0 +1,49 @@ +{ + "$id": "controlplane.v1.WorkflowRunProgress.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "The progress of a run in progress, ready to show", + "patternProperties": { + "^(attestationPolicies)$": { + "$ref": "controlplane.v1.WorkflowRunEvent.PolicyCounts.schema.json", + "description": "Results of the attestation policies evaluated at init" + }, + "^(requiredProvided)$": { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + "^(requiredTotal)$": { + "description": "Required materials, where a group of materials counts once", + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + } + }, + "properties": { + "attestation_policies": { + "$ref": "controlplane.v1.WorkflowRunEvent.PolicyCounts.schema.json", + "description": "Results of the attestation policies evaluated at init" + }, + "materials": { + "description": "One row for each expected material, in contract order, then the materials not in the contract", + "items": { + "$ref": "controlplane.v1.WorkflowRunProgress.Material.schema.json" + }, + "type": "array" + }, + "required_provided": { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + "required_total": { + "description": "Required materials, where a group of materials counts once", + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + } + }, + "title": "Workflow Run Progress", + "type": "object" +} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceGetProgressRequest.jsonschema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceGetProgressRequest.jsonschema.json new file mode 100644 index 000000000..39b504b1f --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceGetProgressRequest.jsonschema.json @@ -0,0 +1,19 @@ +{ + "$id": "controlplane.v1.WorkflowRunServiceGetProgressRequest.jsonschema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "patternProperties": { + "^(workflow_run_id)$": { + "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$", + "type": "string" + } + }, + "properties": { + "workflowRunId": { + "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$", + "type": "string" + } + }, + "title": "Workflow Run Service Get Progress Request", + "type": "object" +} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceGetProgressRequest.schema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceGetProgressRequest.schema.json new file mode 100644 index 000000000..e876b4a2f --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceGetProgressRequest.schema.json @@ -0,0 +1,19 @@ +{ + "$id": "controlplane.v1.WorkflowRunServiceGetProgressRequest.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "patternProperties": { + "^(workflowRunId)$": { + "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$", + "type": "string" + } + }, + "properties": { + "workflow_run_id": { + "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$", + "type": "string" + } + }, + "title": "Workflow Run Service Get Progress Request", + "type": "object" +} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceGetProgressResponse.jsonschema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceGetProgressResponse.jsonschema.json new file mode 100644 index 000000000..6fc23604a --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceGetProgressResponse.jsonschema.json @@ -0,0 +1,20 @@ +{ + "$id": "controlplane.v1.WorkflowRunServiceGetProgressResponse.jsonschema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "events": { + "description": "Timeline of the run, oldest first. Reported data, never part of the attestation.", + "items": { + "$ref": "controlplane.v1.WorkflowRunEvent.jsonschema.json" + }, + "type": "array" + }, + "progress": { + "$ref": "controlplane.v1.WorkflowRunProgress.jsonschema.json", + "description": "Progress of a run in progress, built by the control plane from its events.\n Not set for a finished run: the signed attestation is the source then." + } + }, + "title": "Workflow Run Service Get Progress Response", + "type": "object" +} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceGetProgressResponse.schema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceGetProgressResponse.schema.json new file mode 100644 index 000000000..1a1aa7ff0 --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceGetProgressResponse.schema.json @@ -0,0 +1,20 @@ +{ + "$id": "controlplane.v1.WorkflowRunServiceGetProgressResponse.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "events": { + "description": "Timeline of the run, oldest first. Reported data, never part of the attestation.", + "items": { + "$ref": "controlplane.v1.WorkflowRunEvent.schema.json" + }, + "type": "array" + }, + "progress": { + "$ref": "controlplane.v1.WorkflowRunProgress.schema.json", + "description": "Progress of a run in progress, built by the control plane from its events.\n Not set for a finished run: the signed attestation is the source then." + } + }, + "title": "Workflow Run Service Get Progress Response", + "type": "object" +} diff --git a/app/controlplane/cmd/main.go b/app/controlplane/cmd/main.go index 631c7c488..c8091d8df 100644 --- a/app/controlplane/cmd/main.go +++ b/app/controlplane/cmd/main.go @@ -221,6 +221,9 @@ func workflowRunExpirerOpts(c *conf.Bootstrap) *biz.WorkflowRunExpirerOpts { if configured := c.GetAttestations().GetWorkflowRunExpirationCheckInterval(); configured != nil { opts.CheckInterval = configured.AsDuration() } + if configured := c.GetAttestations().GetWorkflowRunEventsRetention(); configured != nil { + opts.EventsRetention = configured.AsDuration() + } return opts } diff --git a/app/controlplane/cmd/main_test.go b/app/controlplane/cmd/main_test.go index 243ca7105..50ddb8391 100644 --- a/app/controlplane/cmd/main_test.go +++ b/app/controlplane/cmd/main_test.go @@ -36,6 +36,7 @@ func TestWorkflowRunExpirerOptsMapping(t *testing.T) { config *conf.Bootstrap want time.Duration wantCheckInterval time.Duration + wantRetention time.Duration }{ { name: "missing attestations configuration", @@ -55,10 +56,12 @@ func TestWorkflowRunExpirerOptsMapping(t *testing.T) { Attestations: &conf.Attestations{ WorkflowRunExpirationWindow: durationpb.New(2 * time.Hour), WorkflowRunExpirationCheckInterval: durationpb.New(30 * time.Second), + WorkflowRunEventsRetention: durationpb.New(24 * time.Hour), }, }, wantCheckInterval: 30 * time.Second, want: 2 * time.Hour, + wantRetention: 24 * time.Hour, }, } @@ -67,6 +70,7 @@ func TestWorkflowRunExpirerOptsMapping(t *testing.T) { opts := workflowRunExpirerOpts(tt.config) assert.Equal(t, tt.want, opts.ExpirationWindow) assert.Equal(t, tt.wantCheckInterval, opts.CheckInterval) + assert.Equal(t, tt.wantRetention, opts.EventsRetention) }) } } @@ -177,6 +181,7 @@ func TestHelmChartWorkflowRunExpirationDefaults(t *testing.T) { Attestations struct { WorkflowRunExpirationWindow string `json:"workflowRunExpirationWindow"` WorkflowRunExpirationCheckInterval string `json:"workflowRunExpirationCheckInterval"` + WorkflowRunEventsRetention string `json:"workflowRunEventsRetention"` } `json:"attestations"` } `json:"controlplane"` } @@ -187,8 +192,8 @@ func TestHelmChartWorkflowRunExpirationDefaults(t *testing.T) { attestations := values.Controlplane.Attestations // Same shape as templates/controlplane/configmap.yaml - rendered := fmt.Sprintf("attestations:\n workflow_run_expiration_window: %q\n workflow_run_expiration_check_interval: %q\n", - attestations.WorkflowRunExpirationWindow, attestations.WorkflowRunExpirationCheckInterval) + rendered := fmt.Sprintf("attestations:\n workflow_run_expiration_window: %q\n workflow_run_expiration_check_interval: %q\n workflow_run_events_retention: %q\n", + attestations.WorkflowRunExpirationWindow, attestations.WorkflowRunExpirationCheckInterval, attestations.WorkflowRunEventsRetention) configPath := filepath.Join(t.TempDir(), "config.yaml") require.NoError(t, os.WriteFile(configPath, []byte(rendered), 0o600)) @@ -197,6 +202,7 @@ func TestHelmChartWorkflowRunExpirationDefaults(t *testing.T) { require.NoError(t, err) assert.Equal(t, time.Hour, bootstrap.GetAttestations().GetWorkflowRunExpirationWindow().AsDuration()) assert.Equal(t, time.Minute, bootstrap.GetAttestations().GetWorkflowRunExpirationCheckInterval().AsDuration()) + assert.Equal(t, 90*24*time.Hour, bootstrap.GetAttestations().GetWorkflowRunEventsRetention().AsDuration()) } // loadBootstrap loads a configuration file the same way as main. diff --git a/app/controlplane/cmd/wire_gen.go b/app/controlplane/cmd/wire_gen.go index 1775e07b6..d7d6c05c3 100644 --- a/app/controlplane/cmd/wire_gen.go +++ b/app/controlplane/cmd/wire_gen.go @@ -233,6 +233,8 @@ func wireApp(contextContext context.Context, bootstrap *conf.Bootstrap, readerWr cleanup() return nil, nil, err } + workflowRunEventRepo := data.NewWorkflowRunEventRepo(dataData, logger) + workflowRunEventUseCase := biz.NewWorkflowRunEventUseCase(workflowRunEventRepo, logger) newWorkflowRunServiceOpts := &service.NewWorkflowRunServiceOpts{ WorkflowRunUC: workflowRunUseCase, WorkflowUC: workflowUseCase, @@ -243,6 +245,7 @@ func wireApp(contextContext context.Context, bootstrap *conf.Bootstrap, readerWr CASClient: casClientUseCase, CASMappingUC: casMappingUseCase, PolicyEvalCache: policyevalbundleCache, + RunEventUC: workflowRunEventUseCase, BootstrapConfig: bootstrap, Opts: v5, } @@ -277,6 +280,7 @@ func wireApp(contextContext context.Context, bootstrap *conf.Bootstrap, readerWr ProjectVersionUC: projectVersionUseCase, SigningUseCase: signingUseCase, UserUC: userUseCase, + RunEventUC: workflowRunEventUseCase, BootstrapConfig: bootstrap, MembershipsCache: cache, Opts: v5, @@ -401,7 +405,7 @@ func wireApp(contextContext context.Context, bootstrap *conf.Bootstrap, readerWr cleanup() return nil, nil, err } - workflowRunExpirerUseCase := biz.NewWorkflowRunExpirerUseCase(workflowRunRepo, prometheusUseCase, logger) + workflowRunExpirerUseCase := biz.NewWorkflowRunExpirerUseCase(workflowRunRepo, prometheusUseCase, workflowRunEventUseCase, logger) distributedLock := data.NewPostgresLock(dataData, logger) casBackendChecker := biz.NewCASBackendChecker(logger, casBackendRepo, casBackendUseCase, distributedLock) apiTokenStaleRevoker := biz.NewAPITokenStaleRevoker(organizationRepo, apiTokenRepo, apiTokenUseCase, logger) diff --git a/app/controlplane/internal/conf/controlplane/config/v1/conf.pb.go b/app/controlplane/internal/conf/controlplane/config/v1/conf.pb.go index 43cf11e54..615a0d25b 100644 --- a/app/controlplane/internal/conf/controlplane/config/v1/conf.pb.go +++ b/app/controlplane/internal/conf/controlplane/config/v1/conf.pb.go @@ -362,8 +362,13 @@ type Attestations struct { // also accept attestations signed with other methods, for example cosign keys // or KMS. When unset, it defaults to true. ForceVerification *bool `protobuf:"varint,5,opt,name=force_verification,json=forceVerification,proto3,oneof" json:"force_verification,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Age after which the progress events of the workflow runs are deleted. The + // runs and their attestations stay. When unset, the control plane defaults + // to 90 days. + // In YAML configuration, use seconds with an "s" suffix, for example "7776000s". + WorkflowRunEventsRetention *durationpb.Duration `protobuf:"bytes,6,opt,name=workflow_run_events_retention,json=workflowRunEventsRetention,proto3" json:"workflow_run_events_retention,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *Attestations) Reset() { @@ -431,6 +436,13 @@ func (x *Attestations) GetForceVerification() bool { return false } +func (x *Attestations) GetWorkflowRunEventsRetention() *durationpb.Duration { + if x != nil { + return x.WorkflowRunEventsRetention + } + return nil +} + type OperationAuthorizationProvider struct { state protoimpl.MessageState `protogen:"open.v1"` // URL of the authorization endpoint @@ -1945,13 +1957,14 @@ const file_controlplane_config_v1_conf_proto_rawDesc = "" + "\breplicas\x18\x03 \x01(\x05R\breplicasB\x10\n" + "\x0eauthenticationJ\x04\b\b\x10\tR\x15referrer_shared_index\"J\n" + "\x14PluginsNetworkPolicy\x122\n" + - "\x15block_private_targets\x18\x01 \x01(\bR\x13blockPrivateTargets\"\xb2\x03\n" + + "\x15block_private_targets\x18\x01 \x01(\bR\x13blockPrivateTargets\"\x9a\x04\n" + "\fAttestations\x12&\n" + "\x0fskip_db_storage\x18\x01 \x01(\bR\rskipDbStorage\x12L\n" + "#policy_evaluations_max_inline_bytes\x18\x02 \x01(\x03R\x1fpolicyEvaluationsMaxInlineBytes\x12h\n" + "\x1eworkflow_run_expiration_window\x18\x03 \x01(\v2\x19.google.protobuf.DurationB\b\xbaH\x05\xaa\x01\x02*\x00R\x1bworkflowRunExpirationWindow\x12w\n" + "&workflow_run_expiration_check_interval\x18\x04 \x01(\v2\x19.google.protobuf.DurationB\b\xbaH\x05\xaa\x01\x02*\x00R\"workflowRunExpirationCheckInterval\x122\n" + - "\x12force_verification\x18\x05 \x01(\bH\x00R\x11forceVerification\x88\x01\x01B\x15\n" + + "\x12force_verification\x18\x05 \x01(\bH\x00R\x11forceVerification\x88\x01\x01\x12f\n" + + "\x1dworkflow_run_events_retention\x18\x06 \x01(\v2\x19.google.protobuf.DurationB\b\xbaH\x05\xaa\x01\x02*\x00R\x1aworkflowRunEventsRetentionB\x15\n" + "\x13_force_verification\"v\n" + "\x1eOperationAuthorizationProvider\x12\x1a\n" + "\x03url\x18\x01 \x01(\tB\b\xbaH\x05r\x03\x88\x01\x01R\x03url\x12\x18\n" + @@ -2103,27 +2116,28 @@ var file_controlplane_config_v1_conf_proto_depIdxs = []int32{ 1, // 16: controlplane.config.v1.Bootstrap.plugins_network_policy:type_name -> controlplane.config.v1.PluginsNetworkPolicy 26, // 17: controlplane.config.v1.Attestations.workflow_run_expiration_window:type_name -> google.protobuf.Duration 26, // 18: controlplane.config.v1.Attestations.workflow_run_expiration_check_interval:type_name -> google.protobuf.Duration - 17, // 19: controlplane.config.v1.Server.http:type_name -> controlplane.config.v1.Server.HTTP - 19, // 20: controlplane.config.v1.Server.grpc:type_name -> controlplane.config.v1.Server.GRPC - 17, // 21: controlplane.config.v1.Server.http_metrics:type_name -> controlplane.config.v1.Server.HTTP - 20, // 22: controlplane.config.v1.Data.database:type_name -> controlplane.config.v1.Data.Database - 27, // 23: controlplane.config.v1.Auth.allow_list:type_name -> controlplane.config.v1.AllowList - 21, // 24: controlplane.config.v1.Auth.oidc:type_name -> controlplane.config.v1.Auth.OIDC - 22, // 25: controlplane.config.v1.CA.file_ca:type_name -> controlplane.config.v1.CA.FileCA - 23, // 26: controlplane.config.v1.CA.ejbca_ca:type_name -> controlplane.config.v1.CA.EJBCA - 15, // 27: controlplane.config.v1.Bootstrap.Observability.sentry:type_name -> controlplane.config.v1.Bootstrap.Observability.Sentry - 16, // 28: controlplane.config.v1.Bootstrap.Observability.tracing:type_name -> controlplane.config.v1.Bootstrap.Observability.Tracing - 19, // 29: controlplane.config.v1.Bootstrap.CASServer.grpc:type_name -> controlplane.config.v1.Server.GRPC - 26, // 30: controlplane.config.v1.Server.HTTP.timeout:type_name -> google.protobuf.Duration - 18, // 31: controlplane.config.v1.Server.HTTP.tls_config:type_name -> controlplane.config.v1.Server.TLS - 26, // 32: controlplane.config.v1.Server.GRPC.timeout:type_name -> google.protobuf.Duration - 18, // 33: controlplane.config.v1.Server.GRPC.tls_config:type_name -> controlplane.config.v1.Server.TLS - 26, // 34: controlplane.config.v1.Data.Database.max_conn_idle_time:type_name -> google.protobuf.Duration - 35, // [35:35] is the sub-list for method output_type - 35, // [35:35] is the sub-list for method input_type - 35, // [35:35] is the sub-list for extension type_name - 35, // [35:35] is the sub-list for extension extendee - 0, // [0:35] is the sub-list for field type_name + 26, // 19: controlplane.config.v1.Attestations.workflow_run_events_retention:type_name -> google.protobuf.Duration + 17, // 20: controlplane.config.v1.Server.http:type_name -> controlplane.config.v1.Server.HTTP + 19, // 21: controlplane.config.v1.Server.grpc:type_name -> controlplane.config.v1.Server.GRPC + 17, // 22: controlplane.config.v1.Server.http_metrics:type_name -> controlplane.config.v1.Server.HTTP + 20, // 23: controlplane.config.v1.Data.database:type_name -> controlplane.config.v1.Data.Database + 27, // 24: controlplane.config.v1.Auth.allow_list:type_name -> controlplane.config.v1.AllowList + 21, // 25: controlplane.config.v1.Auth.oidc:type_name -> controlplane.config.v1.Auth.OIDC + 22, // 26: controlplane.config.v1.CA.file_ca:type_name -> controlplane.config.v1.CA.FileCA + 23, // 27: controlplane.config.v1.CA.ejbca_ca:type_name -> controlplane.config.v1.CA.EJBCA + 15, // 28: controlplane.config.v1.Bootstrap.Observability.sentry:type_name -> controlplane.config.v1.Bootstrap.Observability.Sentry + 16, // 29: controlplane.config.v1.Bootstrap.Observability.tracing:type_name -> controlplane.config.v1.Bootstrap.Observability.Tracing + 19, // 30: controlplane.config.v1.Bootstrap.CASServer.grpc:type_name -> controlplane.config.v1.Server.GRPC + 26, // 31: controlplane.config.v1.Server.HTTP.timeout:type_name -> google.protobuf.Duration + 18, // 32: controlplane.config.v1.Server.HTTP.tls_config:type_name -> controlplane.config.v1.Server.TLS + 26, // 33: controlplane.config.v1.Server.GRPC.timeout:type_name -> google.protobuf.Duration + 18, // 34: controlplane.config.v1.Server.GRPC.tls_config:type_name -> controlplane.config.v1.Server.TLS + 26, // 35: controlplane.config.v1.Data.Database.max_conn_idle_time:type_name -> google.protobuf.Duration + 36, // [36:36] is the sub-list for method output_type + 36, // [36:36] is the sub-list for method input_type + 36, // [36:36] is the sub-list for extension type_name + 36, // [36:36] is the sub-list for extension extendee + 0, // [0:36] is the sub-list for field type_name } func init() { file_controlplane_config_v1_conf_proto_init() } diff --git a/app/controlplane/internal/conf/controlplane/config/v1/conf.proto b/app/controlplane/internal/conf/controlplane/config/v1/conf.proto index 40e36c69e..f804efed2 100644 --- a/app/controlplane/internal/conf/controlplane/config/v1/conf.proto +++ b/app/controlplane/internal/conf/controlplane/config/v1/conf.proto @@ -184,6 +184,12 @@ message Attestations { // also accept attestations signed with other methods, for example cosign keys // or KMS. When unset, it defaults to true. optional bool force_verification = 5; + + // Age after which the progress events of the workflow runs are deleted. The + // runs and their attestations stay. When unset, the control plane defaults + // to 90 days. + // In YAML configuration, use seconds with an "s" suffix, for example "7776000s". + google.protobuf.Duration workflow_run_events_retention = 6 [(buf.validate.field).duration.gt = {}]; } message OperationAuthorizationProvider { diff --git a/app/controlplane/internal/service/attestation.go b/app/controlplane/internal/service/attestation.go index 0698416d9..c1030f1a9 100644 --- a/app/controlplane/internal/service/attestation.go +++ b/app/controlplane/internal/service/attestation.go @@ -65,6 +65,7 @@ type AttestationService struct { projectUseCase *biz.ProjectUseCase signingUseCase *biz.SigningUseCase userUseCase *biz.UserUseCase + runEventUseCase *biz.WorkflowRunEventUseCase bootstrapConfig *conf.Bootstrap membershipsCache cache.Cache[*entities.Membership] } @@ -87,6 +88,7 @@ type NewAttestationServiceOpts struct { ProjectVersionUC *biz.ProjectVersionUseCase SigningUseCase *biz.SigningUseCase UserUC *biz.UserUseCase + RunEventUC *biz.WorkflowRunEventUseCase BootstrapConfig *conf.Bootstrap MembershipsCache cache.Cache[*entities.Membership] Opts []NewOpt @@ -112,6 +114,7 @@ func NewAttestationService(opts *NewAttestationServiceOpts) *AttestationService projectVersionUseCase: opts.ProjectVersionUC, signingUseCase: opts.SigningUseCase, userUseCase: opts.UserUC, + runEventUseCase: opts.RunEventUC, bootstrapConfig: opts.BootstrapConfig, membershipsCache: opts.MembershipsCache, } @@ -474,6 +477,43 @@ func (s *AttestationService) Cancel(ctx context.Context, req *cpAPI.AttestationS return &cpAPI.AttestationServiceCancelResponse{}, nil } +// RecordEvent records a progress event on a run in progress. It applies the same checks as Store. +func (s *AttestationService) RecordEvent(ctx context.Context, req *cpAPI.AttestationServiceRecordEventRequest) (*cpAPI.AttestationServiceRecordEventResponse, error) { + robotAccount := usercontext.CurrentRobotAccount(ctx) + if robotAccount == nil { + return nil, errors.NotFound("not found", "robot account not found") + } + + // This will make sure the provided workflowRunID belongs to the org encoded in the robot account + wf, err := s.findWorkflowFromTokenOrNameOrRunID(ctx, robotAccount.OrgID, "", "", req.WorkflowRunId) + if err != nil { + return nil, handleUseCaseErr(ctx, err, s.log) + } + + // Apply RBAC on the project + if _, err = s.userHasPermissionOnProject(ctx, robotAccount.OrgID, &cpAPI.IdentityReference{Name: &wf.Project}, authz.PolicyWorkflowRunCreate); err != nil { + return nil, err + } + + wRun, err := s.wrUseCase.GetByIDInOrg(ctx, robotAccount.OrgID, req.WorkflowRunId) + if err != nil { + return nil, handleUseCaseErr(ctx, err, s.log) + } else if wRun == nil { + return nil, errors.NotFound("not found", "workflow run not found") + } + + event, err := pbWorkflowRunEventToBiz(req.GetEvent()) + if err != nil { + return nil, handleUseCaseErr(ctx, err, s.log) + } + + if _, err := s.runEventUseCase.Record(ctx, wRun.ID.String(), event); err != nil { + return nil, handleUseCaseErr(ctx, err, s.log) + } + + return &cpAPI.AttestationServiceRecordEventResponse{}, nil +} + // There is another endpoint to get credentials via casCredentialsService.Get // This one is kept since it leverages robot-accounts in the context of a workflow func (s *AttestationService) GetUploadCreds(ctx context.Context, req *cpAPI.AttestationServiceGetUploadCredsRequest) (*cpAPI.AttestationServiceGetUploadCredsResponse, error) { diff --git a/app/controlplane/internal/service/service.go b/app/controlplane/internal/service/service.go index 240ec46d1..78a915244 100644 --- a/app/controlplane/internal/service/service.go +++ b/app/controlplane/internal/service/service.go @@ -545,7 +545,7 @@ func handleUseCaseErr(ctx context.Context, err error, l *log.Helper) error { return status.Error(codes.Unimplemented, err.Error()) case biz.IsErrAlreadyExists(err): return status.Error(codes.AlreadyExists, err.Error()) - case biz.IsErrReleasedVersionImmutable(err): + case biz.IsErrReleasedVersionImmutable(err) || biz.IsErrFailedPrecondition(err): return status.Error(codes.FailedPrecondition, err.Error()) case biz.IsErrInvalidPassphrase(err): // Client-side condition: the state was encrypted with a different token diff --git a/app/controlplane/internal/service/service_test.go b/app/controlplane/internal/service/service_test.go index 40beba66d..3ff5e05e5 100644 --- a/app/controlplane/internal/service/service_test.go +++ b/app/controlplane/internal/service/service_test.go @@ -142,6 +142,13 @@ func TestHandleUseCaseErr(t *testing.T) { wantCode: codes.FailedPrecondition, wantMessage: "failed to decrypt attestation state: " + biz.NewErrInvalidPassphrase().Error(), }, + { + // A run event for a run that is no longer in progress, or over the limit + name: "failed precondition maps to failed precondition", + err: fmt.Errorf("recording event: %w", biz.NewErrFailedPreconditionStr("the workflow run is not in progress")), + wantCode: codes.FailedPrecondition, + wantMessage: "recording event: the workflow run is not in progress", + }, } for _, tc := range testCases { diff --git a/app/controlplane/internal/service/workflowrun.go b/app/controlplane/internal/service/workflowrun.go index 052f8ef8c..17923e26a 100644 --- a/app/controlplane/internal/service/workflowrun.go +++ b/app/controlplane/internal/service/workflowrun.go @@ -48,6 +48,7 @@ type WorkflowRunService struct { casClient biz.CASClient casMappingUC *biz.CASMappingUseCase policyEvalCache *policyevalbundle.Cache + runEventUseCase *biz.WorkflowRunEventUseCase bootstrapConfig *conf.Bootstrap } @@ -61,6 +62,7 @@ type NewWorkflowRunServiceOpts struct { CASClient biz.CASClient CASMappingUC *biz.CASMappingUseCase PolicyEvalCache *policyevalbundle.Cache + RunEventUC *biz.WorkflowRunEventUseCase BootstrapConfig *conf.Bootstrap Opts []NewOpt } @@ -77,6 +79,7 @@ func NewWorkflowRunService(opts *NewWorkflowRunServiceOpts) *WorkflowRunService casClient: opts.CASClient, casMappingUC: opts.CASMappingUC, policyEvalCache: opts.PolicyEvalCache, + runEventUseCase: opts.RunEventUC, bootstrapConfig: opts.BootstrapConfig, } } @@ -583,6 +586,48 @@ func pbPolicyStatusFilterToBiz(f pb.PolicyStatusFilter) chainloop.PolicyStatus { } } +// GetProgress returns the events of a run and, while the run is in progress, its progress. +// It applies the same checks as View. +func (s *WorkflowRunService) GetProgress(ctx context.Context, req *pb.WorkflowRunServiceGetProgressRequest) (*pb.WorkflowRunServiceGetProgressResponse, error) { + currentOrg, err := requireCurrentOrg(ctx) + if err != nil { + return nil, err + } + + run, err := s.wrUseCase.GetByIDInOrg(ctx, currentOrg.ID, req.GetWorkflowRunId()) + if err != nil { + return nil, handleUseCaseErr(ctx, err, s.log) + } + + // Enforce project-scoped RBAC on the workflow run + if err = s.authorizeResource(ctx, authz.PolicyWorkflowRunRead, authz.ResourceTypeProject, run.Workflow.ProjectID); err != nil { + return nil, err + } + + events, err := s.runEventUseCase.List(ctx, run.ID.String()) + if err != nil { + return nil, handleUseCaseErr(ctx, err, s.log) + } + + res := &pb.WorkflowRunServiceGetProgressResponse{Events: make([]*pb.WorkflowRunEvent, 0, len(events))} + for _, e := range events { + res.Events = append(res.Events, bizWorkflowRunEventToPb(e)) + } + + // A finished run shows its signed attestation instead + if run.State != string(biz.WorkflowRunInitialized) { + return res, nil + } + + contractAndVersion, err := s.workflowContractUseCase.FindVersionByID(ctx, run.ContractVersionID.String()) + if err != nil { + return nil, handleUseCaseErr(ctx, err, s.log) + } + res.Progress = bizWorkflowRunProgressToPb(biz.BuildWorkflowRunProgress(contractAndVersion.Version.Schema, events)) + + return res, nil +} + // validateAndGetProjectID finds a project by name and verifies it's in the visible projects list func (s *WorkflowRunService) validateAndGetProjectID(ctx context.Context, orgID, projectName string, visibleProjectIDs []uuid.UUID) (uuid.UUID, error) { project, err := s.projectUseCase.FindProjectByReference(ctx, orgID, &biz.IdentityReference{Name: &projectName}) @@ -600,3 +645,220 @@ func (s *WorkflowRunService) validateAndGetProjectID(ctx context.Context, orgID, return project.ID, nil } + +var ( + pbToBizRunEventType = map[pb.WorkflowRunEvent_Type]biz.WorkflowRunEventType{ + pb.WorkflowRunEvent_TYPE_ATTESTATION: biz.WorkflowRunEventTypeAttestation, + pb.WorkflowRunEvent_TYPE_MATERIAL: biz.WorkflowRunEventTypeMaterial, + } + bizToPbRunEventType = map[biz.WorkflowRunEventType]pb.WorkflowRunEvent_Type{ + biz.WorkflowRunEventTypeAttestation: pb.WorkflowRunEvent_TYPE_ATTESTATION, + biz.WorkflowRunEventTypeMaterial: pb.WorkflowRunEvent_TYPE_MATERIAL, + } + pbToBizRunEventStatus = map[pb.WorkflowRunEvent_Status]biz.WorkflowRunEventStatus{ + pb.WorkflowRunEvent_STATUS_STARTED: biz.WorkflowRunEventStatusStarted, + pb.WorkflowRunEvent_STATUS_SUCCEEDED: biz.WorkflowRunEventStatusSucceeded, + pb.WorkflowRunEvent_STATUS_FAILED: biz.WorkflowRunEventStatusFailed, + pb.WorkflowRunEvent_STATUS_CANCELED: biz.WorkflowRunEventStatusCanceled, + } + bizToPbRunEventStatus = map[biz.WorkflowRunEventStatus]pb.WorkflowRunEvent_Status{ + biz.WorkflowRunEventStatusStarted: pb.WorkflowRunEvent_STATUS_STARTED, + biz.WorkflowRunEventStatusSucceeded: pb.WorkflowRunEvent_STATUS_SUCCEEDED, + biz.WorkflowRunEventStatusFailed: pb.WorkflowRunEvent_STATUS_FAILED, + biz.WorkflowRunEventStatusCanceled: pb.WorkflowRunEvent_STATUS_CANCELED, + } + bizToPbRunEventSource = map[biz.WorkflowRunEventSource]pb.WorkflowRunEvent_Source{ + biz.WorkflowRunEventSourceCLI: pb.WorkflowRunEvent_SOURCE_CLI, + biz.WorkflowRunEventSourceControlPlane: pb.WorkflowRunEvent_SOURCE_CONTROL_PLANE, + } +) + +// pbWorkflowRunEventToBiz converts an event that a client sent. The server sets the +// id, the time, and the source, so they are ignored. +func pbWorkflowRunEventToBiz(in *pb.WorkflowRunEvent) (*biz.WorkflowRunEvent, error) { + // a missing event has no type, so it is rejected below + eventType, ok := pbToBizRunEventType[in.GetType()] + if !ok { + return nil, biz.NewErrValidationStr(fmt.Sprintf("unsupported event type %s", in.GetType())) + } + + status, ok := pbToBizRunEventStatus[in.GetStatus()] + if !ok { + return nil, biz.NewErrValidationStr(fmt.Sprintf("unsupported event status %s", in.GetStatus())) + } + + out := &biz.WorkflowRunEvent{ + Type: eventType, + Key: in.GetKey(), + Status: status, + Message: in.GetMessage(), + } + + switch attrs := in.GetAttributes().(type) { + case *pb.WorkflowRunEvent_Attestation: + a := attrs.Attestation + out.Attributes = &biz.WorkflowRunEventAttributes{Attestation: &biz.WorkflowRunEventAttestationAttributes{ + ContractName: a.GetContractName(), + ContractRevision: a.GetContractRevision(), + RunnerType: a.GetRunnerType(), + RemoteState: a.GetRemoteState(), + CLIVersion: a.GetCliVersion(), + AttestationDigest: a.GetAttestationDigest(), + Policies: pbPolicyCountsToBiz(a.GetPolicies()), + ExpectedMaterials: pbExpectedMaterialsToBiz(a.GetExpectedMaterials()), + }} + case *pb.WorkflowRunEvent_Material: + m := attrs.Material + out.Attributes = &biz.WorkflowRunEventAttributes{Material: &biz.WorkflowRunEventMaterialAttributes{ + Name: m.GetName(), + MaterialType: m.GetMaterialType(), + Value: m.GetValue(), + Digest: m.GetDigest(), + InContract: m.GetInContract(), + AddedByCollector: m.GetAddedByCollector(), + Policies: pbPolicyCountsToBiz(m.GetPolicies()), + }} + } + + return out, nil +} + +func pbPolicyCountsToBiz(in *pb.WorkflowRunEvent_PolicyCounts) *biz.WorkflowRunEventPolicyCounts { + if in == nil { + return nil + } + + return &biz.WorkflowRunEventPolicyCounts{ + Evaluated: in.GetEvaluated(), + Passed: in.GetPassed(), + Violated: in.GetViolated(), + Skipped: in.GetSkipped(), + ViolatedPolicies: in.GetViolatedPolicies(), + } +} + +func bizPolicyCountsToPb(in *biz.WorkflowRunEventPolicyCounts) *pb.WorkflowRunEvent_PolicyCounts { + if in == nil { + return nil + } + + return &pb.WorkflowRunEvent_PolicyCounts{ + Evaluated: in.Evaluated, + Passed: in.Passed, + Violated: in.Violated, + Skipped: in.Skipped, + ViolatedPolicies: in.ViolatedPolicies, + } +} + +func bizWorkflowRunEventToPb(in *biz.WorkflowRunEvent) *pb.WorkflowRunEvent { + out := &pb.WorkflowRunEvent{ + Id: in.ID.String(), + Source: bizToPbRunEventSource[in.Source], + Type: bizToPbRunEventType[in.Type], + Key: in.Key, + Status: bizToPbRunEventStatus[in.Status], + Message: in.Message, + } + + if in.CreatedAt != nil { + out.CreatedAt = timestamppb.New(*in.CreatedAt) + } + + attrs := in.Attributes + switch { + case attrs == nil: + case attrs.Attestation != nil: + a := attrs.Attestation + out.Attributes = &pb.WorkflowRunEvent_Attestation{Attestation: &pb.WorkflowRunEvent_AttestationAttributes{ + ContractName: a.ContractName, + ContractRevision: a.ContractRevision, + RunnerType: a.RunnerType, + RemoteState: a.RemoteState, + CliVersion: a.CLIVersion, + AttestationDigest: a.AttestationDigest, + Policies: bizPolicyCountsToPb(a.Policies), + ExpectedMaterials: bizExpectedMaterialsToPb(a.ExpectedMaterials), + }} + case attrs.Material != nil: + m := attrs.Material + out.Attributes = &pb.WorkflowRunEvent_Material{Material: &pb.WorkflowRunEvent_MaterialAttributes{ + Name: m.Name, + MaterialType: m.MaterialType, + Value: m.Value, + Digest: m.Digest, + InContract: m.InContract, + AddedByCollector: m.AddedByCollector, + Policies: bizPolicyCountsToPb(m.Policies), + }} + } + + return out +} + +func pbExpectedMaterialsToBiz(in []*pb.WorkflowRunEvent_ExpectedMaterial) []*biz.WorkflowRunEventExpectedMaterial { + if len(in) == 0 { + return nil + } + + out := make([]*biz.WorkflowRunEventExpectedMaterial, 0, len(in)) + for _, m := range in { + out = append(out, &biz.WorkflowRunEventExpectedMaterial{ + Name: m.GetName(), MaterialType: m.GetMaterialType(), Optional: m.GetOptional(), Group: m.GetGroup(), + }) + } + + return out +} + +func bizExpectedMaterialsToPb(in []*biz.WorkflowRunEventExpectedMaterial) []*pb.WorkflowRunEvent_ExpectedMaterial { + if len(in) == 0 { + return nil + } + + out := make([]*pb.WorkflowRunEvent_ExpectedMaterial, 0, len(in)) + for _, m := range in { + out = append(out, &pb.WorkflowRunEvent_ExpectedMaterial{ + Name: m.Name, MaterialType: m.MaterialType, Optional: m.Optional, Group: m.Group, + }) + } + + return out +} + +var ( + bizToPbRunMaterialRequirement = map[biz.WorkflowRunMaterialRequirement]pb.WorkflowRunProgress_Requirement{ + biz.WorkflowRunMaterialRequired: pb.WorkflowRunProgress_REQUIREMENT_REQUIRED, + biz.WorkflowRunMaterialOptional: pb.WorkflowRunProgress_REQUIREMENT_OPTIONAL, + biz.WorkflowRunMaterialOneOfGroup: pb.WorkflowRunProgress_REQUIREMENT_ONE_OF_GROUP, + biz.WorkflowRunMaterialNotInContract: pb.WorkflowRunProgress_REQUIREMENT_NOT_IN_CONTRACT, + } + bizToPbRunMaterialStatus = map[biz.WorkflowRunMaterialStatus]pb.WorkflowRunProgress_Status{ + biz.WorkflowRunMaterialMissing: pb.WorkflowRunProgress_STATUS_MISSING, + biz.WorkflowRunMaterialProvided: pb.WorkflowRunProgress_STATUS_PROVIDED, + biz.WorkflowRunMaterialFailed: pb.WorkflowRunProgress_STATUS_FAILED, + } +) + +func bizWorkflowRunProgressToPb(in *biz.WorkflowRunProgress) *pb.WorkflowRunProgress { + if in == nil { + return nil + } + + out := &pb.WorkflowRunProgress{ + RequiredTotal: in.RequiredTotal, + RequiredProvided: in.RequiredProvided, + AttestationPolicies: bizPolicyCountsToPb(in.AttestationPolicies), + Materials: make([]*pb.WorkflowRunProgress_Material, 0, len(in.Materials)), + } + for _, m := range in.Materials { + out.Materials = append(out.Materials, &pb.WorkflowRunProgress_Material{ + Name: m.Name, MaterialType: m.MaterialType, + Requirement: bizToPbRunMaterialRequirement[m.Requirement], Group: m.Group, + Status: bizToPbRunMaterialStatus[m.Status], Value: m.Value, Policies: bizPolicyCountsToPb(m.Policies), + LastError: m.LastError, FailedAttempts: m.FailedAttempts, + }) + } + + return out +} diff --git a/app/controlplane/internal/service/workflowrunevent_integration_test.go b/app/controlplane/internal/service/workflowrunevent_integration_test.go new file mode 100644 index 000000000..fad838121 --- /dev/null +++ b/app/controlplane/internal/service/workflowrunevent_integration_test.go @@ -0,0 +1,408 @@ +// +// Copyright 2026 The Chainloop Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package service + +import ( + "context" + "testing" + + pb "github.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1" + "github.com/chainloop-dev/chainloop/app/controlplane/internal/usercontext" + "github.com/chainloop-dev/chainloop/app/controlplane/internal/usercontext/attjwtmiddleware" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/authz" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/biz" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/biz/testhelpers" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/usercontext/entities" + "github.com/chainloop-dev/chainloop/pkg/blobmanager/oci" + creds "github.com/chainloop-dev/chainloop/pkg/credentials/mocks" + kerrors "github.com/go-kratos/kratos/v2/errors" + "github.com/google/uuid" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/suite" +) + +// RecordEvent copies the checks of Store, and GetProgress copies the checks of View. No new +// policy is involved, so every caller keeps the access it has to the run itself. +type workflowRunEventRBACIntegrationSuite struct { + testhelpers.UseCasesEachTestSuite + org, otherOrg *biz.Organization + projectA, projectB *biz.Project + workflowA, workflowC *biz.Workflow // both in project A + runA, runOtherOrg *biz.WorkflowRun + orgToken *biz.APIToken + workflowCToken *biz.APIToken + projectBToken *biz.APIToken + attSvc *AttestationService + runSvc *WorkflowRunService +} + +func TestWorkflowRunEventRBACIntegration(t *testing.T) { + suite.Run(t, new(workflowRunEventRBACIntegrationSuite)) +} + +func (s *workflowRunEventRBACIntegrationSuite) SetupTest() { + credsWriter := creds.NewReaderWriter(s.T()) + credsWriter.On("SaveCredentials", mock.Anything, mock.Anything, mock.Anything).Return("stored-secret", nil) + s.TestingUseCases = testhelpers.NewTestingUseCases(s.T(), testhelpers.WithCredsReaderWriter(credsWriter)) + + ctx := context.Background() + var err error + + s.org, err = s.Organization.Create(ctx, "run-events-org") + s.Require().NoError(err) + s.otherOrg, err = s.Organization.Create(ctx, "run-events-other-org") + s.Require().NoError(err) + + s.workflowA, err = s.Workflow.Create(ctx, &biz.WorkflowCreateOpts{Name: workflowAName, OrgID: s.org.ID, Project: projectAName}) + s.Require().NoError(err) + s.workflowC, err = s.Workflow.Create(ctx, &biz.WorkflowCreateOpts{Name: "workflow-c", OrgID: s.org.ID, Project: projectAName}) + s.Require().NoError(err) + _, err = s.Workflow.Create(ctx, &biz.WorkflowCreateOpts{Name: workflowBName, OrgID: s.org.ID, Project: projectBName}) + s.Require().NoError(err) + otherWorkflow, err := s.Workflow.Create(ctx, &biz.WorkflowCreateOpts{Name: workflowAName, OrgID: s.otherOrg.ID, Project: projectAName}) + s.Require().NoError(err) + + s.projectA, err = s.Project.FindProjectByReference(ctx, s.org.ID, &biz.IdentityReference{Name: ptr(projectAName)}) + s.Require().NoError(err) + s.projectB, err = s.Project.FindProjectByReference(ctx, s.org.ID, &biz.IdentityReference{Name: ptr(projectBName)}) + s.Require().NoError(err) + + s.runA = s.newRun(s.org.ID, s.workflowA) + s.runOtherOrg = s.newRun(s.otherOrg.ID, otherWorkflow) + + s.orgToken, err = s.APIToken.Create(ctx, "token-org", nil, nil, &s.org.ID) + s.Require().NoError(err) + s.workflowCToken, err = s.APIToken.Create(ctx, "token-workflow-c", nil, nil, &s.org.ID, biz.APITokenWithProject(s.projectA), biz.APITokenWithWorkflow(s.workflowC)) + s.Require().NoError(err) + s.projectBToken, err = s.APIToken.Create(ctx, "token-project-b", nil, nil, &s.org.ID, biz.APITokenWithProject(s.projectB)) + s.Require().NoError(err) + + authzUC := biz.NewAuthzUseCase(&biz.AuthzUseCaseConfig{ + CasbinEnforcer: s.Enforcer, + APITokenRepo: s.Repos.APITokenRepo, + Logger: s.L, + }) + + s.attSvc = NewAttestationService(&NewAttestationServiceOpts{ + WorkflowRunUC: s.WorkflowRun, + WorkflowUC: s.Workflow, + WorkflowContractUC: s.WorkflowContract, + OrgUC: s.Organization, + ProjectUC: s.Project, + ProjectVersionUC: s.ProjectVersion, + RunEventUC: s.WorkflowRunEvent, + Opts: []NewOpt{WithProjectUseCase(s.Project), WithEnforcer(authzUC)}, + }) + + s.runSvc = NewWorkflowRunService(&NewWorkflowRunServiceOpts{ + WorkflowRunUC: s.WorkflowRun, + WorkflowUC: s.Workflow, + WorkflowContractUC: s.WorkflowContract, + ProjectUC: s.Project, + ProjectVersionUC: s.ProjectVersion, + RunEventUC: s.WorkflowRunEvent, + Opts: []NewOpt{WithProjectUseCase(s.Project), WithEnforcer(authzUC)}, + }) +} + +const ( + projectAName = "project-a" + projectBName = "project-b" + workflowBName = "workflow-b" + workflowAName = "workflow-a" + sbomMaterial = "sbom" +) + +func ptr[T any](v T) *T { return &v } + +func (s *workflowRunEventRBACIntegrationSuite) newRun(orgID string, wf *biz.Workflow) *biz.WorkflowRun { + ctx := context.Background() + contractVersion, err := s.WorkflowContract.Describe(ctx, orgID, wf.ContractID.String(), 0) + s.Require().NoError(err) + //nolint:staticcheck // the run tests create their CAS backend with this helper + backend, err := s.CASBackend.CreateOrUpdate(ctx, orgID, "repo", "username", "pass", oci.ProviderID, true) + s.Require().NoError(err) + + run, err := s.WorkflowRun.Create(ctx, &biz.WorkflowRunCreateOpts{ + WorkflowID: wf.ID.String(), ContractRevision: contractVersion, CASBackendID: backend.ID, + }) + s.Require().NoError(err) + + return run +} + +func materialEventRequest(runID string) *pb.AttestationServiceRecordEventRequest { + return &pb.AttestationServiceRecordEventRequest{ + WorkflowRunId: runID, + Event: &pb.WorkflowRunEvent{ + Type: pb.WorkflowRunEvent_TYPE_MATERIAL, + Key: "chainloop.material.sbom", + Status: pb.WorkflowRunEvent_STATUS_SUCCEEDED, + Attributes: &pb.WorkflowRunEvent_Material{Material: &pb.WorkflowRunEvent_MaterialAttributes{ + Name: sbomMaterial, MaterialType: "SBOM_CYCLONEDX_JSON", Value: "sbom.json", + }}, + }, + } +} + +type runEventOutcome int + +const ( + allowed runEventOutcome = iota + forbidden + notFound +) + +func (s *workflowRunEventRBACIntegrationSuite) assertOutcome(want runEventOutcome, err error) { + s.T().Helper() + switch want { + case allowed: + s.Require().NoError(err) + case forbidden: + s.Require().Error(err) + s.True(kerrors.IsForbidden(err), "expected forbidden, got %v", err) + case notFound: + s.Require().Error(err) + s.True(kerrors.IsNotFound(err), "expected not found, got %v", err) + } +} + +// The caller table of plan step 04 +func (s *workflowRunEventRBACIntegrationSuite) TestCallerTable() { + testCases := []struct { + name string + // attestation context, as the attestation middlewares build it + attCtx func() context.Context + // regular API context, as the authn middlewares build it + apiCtx func() context.Context + runID func() string + wantRecord runEventOutcome + wantView runEventOutcome + }{ + { + name: "org API token, accepted by Store", + attCtx: func() context.Context { return s.attCtxForToken(s.org, s.orgToken) }, + apiCtx: func() context.Context { return s.apiCtxForToken(s.org, s.orgToken) }, + runID: func() string { return s.runA.ID.String() }, + wantRecord: allowed, + wantView: allowed, + }, + { + name: "project admin user, accepted by Store", + attCtx: func() context.Context { return s.attCtxForUser(s.org, authz.RoleProjectAdmin) }, + apiCtx: func() context.Context { return s.apiCtxForUser(s.org, authz.RoleProjectAdmin) }, + runID: func() string { return s.runA.ID.String() }, + wantRecord: allowed, + wantView: allowed, + }, + { + name: "token pinned to another workflow of the same project", + attCtx: func() context.Context { return s.attCtxForToken(s.org, s.workflowCToken) }, + apiCtx: func() context.Context { return s.apiCtxForToken(s.org, s.workflowCToken) }, + runID: func() string { return s.runA.ID.String() }, + wantRecord: forbidden, + // as for View, which allows the project of the token + wantView: allowed, + }, + { + name: "API token scoped to another project", + attCtx: func() context.Context { return s.attCtxForToken(s.org, s.projectBToken) }, + apiCtx: func() context.Context { return s.apiCtxForToken(s.org, s.projectBToken) }, + runID: func() string { return s.runA.ID.String() }, + wantRecord: forbidden, + wantView: forbidden, + }, + { + name: "user who can only view the project", + attCtx: func() context.Context { return s.attCtxForUser(s.org, authz.RoleProjectViewer) }, + apiCtx: func() context.Context { return s.apiCtxForUser(s.org, authz.RoleProjectViewer) }, + runID: func() string { return s.runA.ID.String() }, + wantRecord: forbidden, + wantView: allowed, + }, + { + name: "user with no access to the project", + attCtx: func() context.Context { return s.attCtxForUser(s.org, "") }, + apiCtx: func() context.Context { return s.apiCtxForUser(s.org, "") }, + runID: func() string { return s.runA.ID.String() }, + wantRecord: forbidden, + wantView: forbidden, + }, + { + name: "org API token, run in another organization", + attCtx: func() context.Context { return s.attCtxForToken(s.org, s.orgToken) }, + apiCtx: func() context.Context { return s.apiCtxForToken(s.org, s.orgToken) }, + runID: func() string { return s.runOtherOrg.ID.String() }, + wantRecord: notFound, + wantView: notFound, + }, + { + name: "project admin user, run in another organization", + attCtx: func() context.Context { return s.attCtxForUser(s.org, authz.RoleProjectAdmin) }, + apiCtx: func() context.Context { return s.apiCtxForUser(s.org, authz.RoleProjectAdmin) }, + runID: func() string { return s.runOtherOrg.ID.String() }, + wantRecord: notFound, + wantView: notFound, + }, + } + + for _, tc := range testCases { + s.Run(tc.name, func() { + _, err := s.attSvc.RecordEvent(tc.attCtx(), materialEventRequest(tc.runID())) + s.assertOutcome(tc.wantRecord, err) + + // Store applies the same checks before it looks at the bundle + _, storeErr := s.attSvc.Store(tc.attCtx(), &pb.AttestationServiceStoreRequest{WorkflowRunId: tc.runID(), AttestationBundle: []byte("{}")}) + if tc.wantRecord == allowed { + s.Error(storeErr, "an invalid bundle never stores") + s.False(kerrors.IsForbidden(storeErr) || kerrors.IsNotFound(storeErr), "Store must accept this caller, got %v", storeErr) + } else { + s.assertOutcome(tc.wantRecord, storeErr) + } + + _, err = s.runSvc.GetProgress(tc.apiCtx(), &pb.WorkflowRunServiceGetProgressRequest{WorkflowRunId: tc.runID()}) + s.assertOutcome(tc.wantView, err) + + _, viewErr := s.runSvc.View(tc.apiCtx(), &pb.WorkflowRunServiceViewRequest{Ref: &pb.WorkflowRunServiceViewRequest_Id{Id: tc.runID()}}) + s.assertOutcome(tc.wantView, viewErr) + }) + } +} + +func (s *workflowRunEventRBACIntegrationSuite) TestRecordAndGetProgress() { + ctx := s.attCtxForToken(s.org, s.orgToken) + runID := s.runA.ID.String() + + _, err := s.attSvc.RecordEvent(ctx, materialEventRequest(runID)) + s.Require().NoError(err) + + view := func() *pb.WorkflowRunServiceGetProgressResponse { + resp, err := s.runSvc.GetProgress(s.apiCtxForToken(s.org, s.orgToken), &pb.WorkflowRunServiceGetProgressRequest{WorkflowRunId: runID}) + s.Require().NoError(err) + return resp + } + + res := view() + s.Require().Len(res.GetEvents(), 1) + + got := res.GetEvents()[0] + s.Equal(pb.WorkflowRunEvent_SOURCE_CLI, got.GetSource(), "the server sets the source") + s.NotEmpty(got.GetId()) + s.NotNil(got.GetCreatedAt()) + s.Equal(sbomMaterial, got.GetMaterial().GetName()) + s.Equal("sbom.json", got.GetMaterial().GetValue()) + + // a run in progress has its progress, built from the events + s.Require().NotNil(res.GetProgress()) + var provided bool + for _, m := range res.GetProgress().GetMaterials() { + if m.GetName() == sbomMaterial { + provided = m.GetStatus() == pb.WorkflowRunProgress_STATUS_PROVIDED + } + } + s.True(provided, "the added material shows as provided") + + // a store closes the timeline, and the run accepts no more events + s.Require().NoError(s.WorkflowRun.MarkAsFinished(context.Background(), runID, biz.WorkflowRunSuccess, "")) + _, err = s.attSvc.RecordEvent(ctx, materialEventRequest(runID)) + s.Require().Error(err) + s.Contains(err.Error(), "not in progress") + + // a finished run keeps its timeline, and has no progress + res = view() + s.Nil(res.GetProgress()) + s.Require().Len(res.GetEvents(), 2) + closing := res.GetEvents()[1] + s.Equal(pb.WorkflowRunEvent_SOURCE_CONTROL_PLANE, closing.GetSource()) + s.Equal(pb.WorkflowRunEvent_STATUS_SUCCEEDED, closing.GetStatus()) +} + +func (s *workflowRunEventRBACIntegrationSuite) TestRecordEventValidation() { + ctx := s.attCtxForToken(s.org, s.orgToken) + runID := s.runA.ID.String() + + testCases := []struct { + name string + event *pb.WorkflowRunEvent + }{ + { + name: "attributes that do not match the type", + event: &pb.WorkflowRunEvent{ + Type: pb.WorkflowRunEvent_TYPE_ATTESTATION, Key: "chainloop.attestation", Status: pb.WorkflowRunEvent_STATUS_SUCCEEDED, + Attributes: &pb.WorkflowRunEvent_Material{Material: &pb.WorkflowRunEvent_MaterialAttributes{Name: sbomMaterial}}, + }, + }, + { + name: "key that is not automatic", + event: &pb.WorkflowRunEvent{ + Type: pb.WorkflowRunEvent_TYPE_MATERIAL, Key: "sbom", Status: pb.WorkflowRunEvent_STATUS_SUCCEEDED, + }, + }, + } + + for _, tc := range testCases { + s.Run(tc.name, func() { + _, err := s.attSvc.RecordEvent(ctx, &pb.AttestationServiceRecordEventRequest{WorkflowRunId: runID, Event: tc.event}) + s.Require().Error(err) + s.True(kerrors.IsBadRequest(err), "expected bad request, got %v", err) + }) + } +} + +// attCtxForToken mirrors the context the API-token attestation middleware produces +func (s *workflowRunEventRBACIntegrationSuite) attCtxForToken(org *biz.Organization, token *biz.APIToken) context.Context { + ctx := s.apiCtxForToken(org, token) + return usercontext.WithRobotAccount(ctx, &usercontext.RobotAccount{OrgID: org.ID, ProviderKey: attjwtmiddleware.APITokenProviderKey}) +} + +// apiCtxForToken mirrors the context of a regular API call authenticated with an API token +func (s *workflowRunEventRBACIntegrationSuite) apiCtxForToken(org *biz.Organization, token *biz.APIToken) context.Context { + ctx := entities.WithCurrentOrg(context.Background(), &entities.Org{ID: org.ID, Name: org.Name}) + ctx = entities.WithCurrentAPIToken(ctx, &entities.APIToken{ + ID: token.ID.String(), + Name: token.Name, + ProjectID: token.ProjectID, + ProjectName: token.ProjectName, + WorkflowID: token.WorkflowID, + WorkflowName: token.WorkflowName, + Scope: token.Scope, + ScopeID: token.ScopeID, + ProjectIDs: token.ProjectIDs, + }) + return usercontext.WithAuthzSubject(ctx, (&authz.SubjectAPIToken{ID: token.ID.String()}).String()) +} + +// attCtxForUser mirrors the context WithAttestationContextFromUser produces for an org member +func (s *workflowRunEventRBACIntegrationSuite) attCtxForUser(org *biz.Organization, projectRole authz.Role) context.Context { + ctx := s.apiCtxForUser(org, projectRole) + return usercontext.WithRobotAccount(ctx, &usercontext.RobotAccount{OrgID: org.ID, ProviderKey: attjwtmiddleware.UserTokenProviderKey}) +} + +// apiCtxForUser builds an org member with the given role on project A, or no project role when empty +func (s *workflowRunEventRBACIntegrationSuite) apiCtxForUser(org *biz.Organization, projectRole authz.Role) context.Context { + ctx := entities.WithCurrentOrg(context.Background(), &entities.Org{ID: org.ID, Name: org.Name}) + ctx = entities.WithCurrentUser(ctx, &entities.User{ID: uuid.NewString()}) + ctx = usercontext.WithAuthzSubject(ctx, string(authz.RoleOrgMember)) + + membership := &entities.Membership{UserID: uuid.New()} + if projectRole != "" { + membership.Resources = []*entities.ResourceMembership{ + {Role: projectRole, ResourceType: authz.ResourceTypeProject, ResourceID: s.projectA.ID}, + } + } + + return entities.WithMembership(ctx, membership) +} diff --git a/app/controlplane/pkg/authz/authz.go b/app/controlplane/pkg/authz/authz.go index 89ab52bf3..470ace9cf 100644 --- a/app/controlplane/pkg/authz/authz.go +++ b/app/controlplane/pkg/authz/authz.go @@ -394,8 +394,9 @@ var ServerOperationsMap = map[string]*OperationPolicy{ "/controlplane.v1.WorkflowService/Update": {Policies: []*Policy{PolicyWorkflowUpdate}}, "/controlplane.v1.WorkflowService/Delete": {Policies: []*Policy{PolicyWorkflowDelete}}, // WorkflowRun - "/controlplane.v1.WorkflowRunService/List": {Policies: []*Policy{PolicyWorkflowRunList}}, - "/controlplane.v1.WorkflowRunService/View": {Policies: []*Policy{PolicyWorkflowRunRead}}, + "/controlplane.v1.WorkflowRunService/List": {Policies: []*Policy{PolicyWorkflowRunList}}, + "/controlplane.v1.WorkflowRunService/View": {Policies: []*Policy{PolicyWorkflowRunRead}}, + "/controlplane.v1.WorkflowRunService/GetProgress": {Policies: []*Policy{PolicyWorkflowRunRead}}, // Workflow Contracts "/controlplane.v1.WorkflowContractService/List": {Policies: []*Policy{PolicyWorkflowContractList}}, "/controlplane.v1.WorkflowContractService/Describe": {Policies: []*Policy{PolicyWorkflowContractRead}}, diff --git a/app/controlplane/pkg/authz/authz_consistency_test.go b/app/controlplane/pkg/authz/authz_consistency_test.go index a1c78d916..4caa92e46 100644 --- a/app/controlplane/pkg/authz/authz_consistency_test.go +++ b/app/controlplane/pkg/authz/authz_consistency_test.go @@ -61,6 +61,7 @@ var authzExemptProcedures = map[string]struct{}{ "/controlplane.v1.AttestationService/GetPolicyGroup": {}, "/controlplane.v1.AttestationService/GetUploadCreds": {}, "/controlplane.v1.AttestationService/Init": {}, + "/controlplane.v1.AttestationService/RecordEvent": {}, "/controlplane.v1.AttestationService/Store": {}, "/controlplane.v1.AttestationStateService/Initialized": {}, "/controlplane.v1.AttestationStateService/Read": {}, diff --git a/app/controlplane/pkg/biz/.mockery.yml b/app/controlplane/pkg/biz/.mockery.yml index b717cccb1..ddac4fa3a 100644 --- a/app/controlplane/pkg/biz/.mockery.yml +++ b/app/controlplane/pkg/biz/.mockery.yml @@ -20,3 +20,4 @@ packages: CASMappingRepo: OrganizationRepo: WorkflowRunRepo: + WorkflowRunEventRepo: diff --git a/app/controlplane/pkg/biz/attestationstate_integration_test.go b/app/controlplane/pkg/biz/attestationstate_integration_test.go index bb52af53c..406633b6a 100644 --- a/app/controlplane/pkg/biz/attestationstate_integration_test.go +++ b/app/controlplane/pkg/biz/attestationstate_integration_test.go @@ -195,13 +195,19 @@ func (s *attestationStateTestSuite) TestWorkflowRunLifecycle() { }) s.T().Run("or it expires", func(t *testing.T) { - _, err := s.AttestationState.Save(ctx, s.workflowOrg1.ID.String(), s.runOrg1.ID.String(), s.testState, s.passphrase) + // Expiry applies only to a run in progress, so it uses a new run + run, err := s.WorkflowRun.Create(ctx, &biz.WorkflowRunCreateOpts{ + WorkflowID: s.workflowOrg1.ID.String(), ContractRevision: s.contractVersion, CASBackendID: s.casBackend.ID, + }) + s.Require().NoError(err) + + _, err = s.AttestationState.Save(ctx, s.workflowOrg1.ID.String(), run.ID.String(), s.testState, s.passphrase) s.NoError(err) - err = s.Repos.WorkflowRunRepo.Expire(ctx, s.runOrg1.ID) + err = s.Repos.WorkflowRunRepo.Expire(ctx, run.ID) s.NoError(err) - _, err = s.AttestationState.Read(ctx, s.workflowOrg1.ID.String(), s.runOrg1.ID.String(), s.passphrase) + _, err = s.AttestationState.Read(ctx, s.workflowOrg1.ID.String(), run.ID.String(), s.passphrase) s.Error(err) s.True(biz.IsNotFound(err)) }) diff --git a/app/controlplane/pkg/biz/biz.go b/app/controlplane/pkg/biz/biz.go index a299fdbf5..2e2eb47a2 100644 --- a/app/controlplane/pkg/biz/biz.go +++ b/app/controlplane/pkg/biz/biz.go @@ -46,6 +46,7 @@ var ProviderSet = wire.NewSet( NewOrgInvitationUseCase, NewAttestationUseCase, NewWorkflowRunExpirerUseCase, + NewWorkflowRunEventUseCase, NewCASMappingUseCase, NewReferrerUseCase, NewAPITokenUseCase, diff --git a/app/controlplane/pkg/biz/errors.go b/app/controlplane/pkg/biz/errors.go index b6b2cdc54..b43a12d6b 100644 --- a/app/controlplane/pkg/biz/errors.go +++ b/app/controlplane/pkg/biz/errors.go @@ -219,3 +219,21 @@ func (e ErrInvalidPassphrase) Error() string { func IsErrInvalidPassphrase(err error) bool { return errors.As(err, &ErrInvalidPassphrase{}) } + +// ErrFailedPrecondition is returned when the request is valid but the state of the +// resource does not allow it, for example an event for a run that is no longer in progress. +type ErrFailedPrecondition struct { + msg string +} + +func NewErrFailedPreconditionStr(msg string) ErrFailedPrecondition { + return ErrFailedPrecondition{msg} +} + +func (e ErrFailedPrecondition) Error() string { + return e.msg +} + +func IsErrFailedPrecondition(err error) bool { + return errors.As(err, &ErrFailedPrecondition{}) +} diff --git a/app/controlplane/pkg/biz/mocks/WorkflowRunEventRepo.go b/app/controlplane/pkg/biz/mocks/WorkflowRunEventRepo.go new file mode 100644 index 000000000..1fbb8af29 --- /dev/null +++ b/app/controlplane/pkg/biz/mocks/WorkflowRunEventRepo.go @@ -0,0 +1,264 @@ +// Code generated by mockery; DO NOT EDIT. +// github.com/vektra/mockery +// template: testify + +package mocks + +import ( + "context" + "time" + + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/biz" + "github.com/google/uuid" + mock "github.com/stretchr/testify/mock" +) + +// NewWorkflowRunEventRepo creates a new instance of WorkflowRunEventRepo. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewWorkflowRunEventRepo(t interface { + mock.TestingT + Cleanup(func()) +}) *WorkflowRunEventRepo { + if helper, ok := t.(interface{ Helper() }); ok { + helper.Helper() + } + + mock := &WorkflowRunEventRepo{} + mock.Mock.Test(t) + + t.Cleanup(func() { + if helper, ok := t.(interface{ Helper() }); ok { + helper.Helper() + } + mock.AssertExpectations(t) + }) + + return mock +} + +// WorkflowRunEventRepo is an autogenerated mock type for the WorkflowRunEventRepo type +type WorkflowRunEventRepo struct { + mock.Mock +} + +type WorkflowRunEventRepo_Expecter struct { + mock *mock.Mock +} + +func (_m *WorkflowRunEventRepo) EXPECT() *WorkflowRunEventRepo_Expecter { + return &WorkflowRunEventRepo_Expecter{mock: &_m.Mock} +} + +// Create provides a mock function for the type WorkflowRunEventRepo +func (_mock *WorkflowRunEventRepo) Create(ctx context.Context, event *biz.WorkflowRunEvent, maxEvents int) (*biz.WorkflowRunEvent, error) { + ret := _mock.Called(ctx, event, maxEvents) + + if len(ret) == 0 { + panic("no return value specified for Create") + } + + var r0 *biz.WorkflowRunEvent + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, *biz.WorkflowRunEvent, int) (*biz.WorkflowRunEvent, error)); ok { + return returnFunc(ctx, event, maxEvents) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, *biz.WorkflowRunEvent, int) *biz.WorkflowRunEvent); ok { + r0 = returnFunc(ctx, event, maxEvents) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*biz.WorkflowRunEvent) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, *biz.WorkflowRunEvent, int) error); ok { + r1 = returnFunc(ctx, event, maxEvents) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// WorkflowRunEventRepo_Create_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Create' +type WorkflowRunEventRepo_Create_Call struct { + *mock.Call +} + +// Create is a helper method to define mock.On call +// - ctx context.Context +// - event *biz.WorkflowRunEvent +// - maxEvents int +func (_e *WorkflowRunEventRepo_Expecter) Create(ctx any, event any, maxEvents any) *WorkflowRunEventRepo_Create_Call { + return &WorkflowRunEventRepo_Create_Call{Call: _e.mock.On("Create", ctx, event, maxEvents)} +} + +func (_c *WorkflowRunEventRepo_Create_Call) Run(run func(ctx context.Context, event *biz.WorkflowRunEvent, maxEvents int)) *WorkflowRunEventRepo_Create_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 *biz.WorkflowRunEvent + if args[1] != nil { + arg1 = args[1].(*biz.WorkflowRunEvent) + } + var arg2 int + if args[2] != nil { + arg2 = args[2].(int) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *WorkflowRunEventRepo_Create_Call) Return(workflowRunEvent *biz.WorkflowRunEvent, err error) *WorkflowRunEventRepo_Create_Call { + _c.Call.Return(workflowRunEvent, err) + return _c +} + +func (_c *WorkflowRunEventRepo_Create_Call) RunAndReturn(run func(ctx context.Context, event *biz.WorkflowRunEvent, maxEvents int) (*biz.WorkflowRunEvent, error)) *WorkflowRunEventRepo_Create_Call { + _c.Call.Return(run) + return _c +} + +// DeleteOlderThan provides a mock function for the type WorkflowRunEventRepo +func (_mock *WorkflowRunEventRepo) DeleteOlderThan(ctx context.Context, t time.Time, limit int) (int, error) { + ret := _mock.Called(ctx, t, limit) + + if len(ret) == 0 { + panic("no return value specified for DeleteOlderThan") + } + + var r0 int + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, time.Time, int) (int, error)); ok { + return returnFunc(ctx, t, limit) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, time.Time, int) int); ok { + r0 = returnFunc(ctx, t, limit) + } else { + r0 = ret.Get(0).(int) + } + if returnFunc, ok := ret.Get(1).(func(context.Context, time.Time, int) error); ok { + r1 = returnFunc(ctx, t, limit) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// WorkflowRunEventRepo_DeleteOlderThan_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeleteOlderThan' +type WorkflowRunEventRepo_DeleteOlderThan_Call struct { + *mock.Call +} + +// DeleteOlderThan is a helper method to define mock.On call +// - ctx context.Context +// - t time.Time +// - limit int +func (_e *WorkflowRunEventRepo_Expecter) DeleteOlderThan(ctx any, t any, limit any) *WorkflowRunEventRepo_DeleteOlderThan_Call { + return &WorkflowRunEventRepo_DeleteOlderThan_Call{Call: _e.mock.On("DeleteOlderThan", ctx, t, limit)} +} + +func (_c *WorkflowRunEventRepo_DeleteOlderThan_Call) Run(run func(ctx context.Context, t time.Time, limit int)) *WorkflowRunEventRepo_DeleteOlderThan_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 time.Time + if args[1] != nil { + arg1 = args[1].(time.Time) + } + var arg2 int + if args[2] != nil { + arg2 = args[2].(int) + } + run( + arg0, + arg1, + arg2, + ) + }) + return _c +} + +func (_c *WorkflowRunEventRepo_DeleteOlderThan_Call) Return(n int, err error) *WorkflowRunEventRepo_DeleteOlderThan_Call { + _c.Call.Return(n, err) + return _c +} + +func (_c *WorkflowRunEventRepo_DeleteOlderThan_Call) RunAndReturn(run func(ctx context.Context, t time.Time, limit int) (int, error)) *WorkflowRunEventRepo_DeleteOlderThan_Call { + _c.Call.Return(run) + return _c +} + +// List provides a mock function for the type WorkflowRunEventRepo +func (_mock *WorkflowRunEventRepo) List(ctx context.Context, runID uuid.UUID) ([]*biz.WorkflowRunEvent, error) { + ret := _mock.Called(ctx, runID) + + if len(ret) == 0 { + panic("no return value specified for List") + } + + var r0 []*biz.WorkflowRunEvent + var r1 error + if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID) ([]*biz.WorkflowRunEvent, error)); ok { + return returnFunc(ctx, runID) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID) []*biz.WorkflowRunEvent); ok { + r0 = returnFunc(ctx, runID) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]*biz.WorkflowRunEvent) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID) error); ok { + r1 = returnFunc(ctx, runID) + } else { + r1 = ret.Error(1) + } + return r0, r1 +} + +// WorkflowRunEventRepo_List_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'List' +type WorkflowRunEventRepo_List_Call struct { + *mock.Call +} + +// List is a helper method to define mock.On call +// - ctx context.Context +// - runID uuid.UUID +func (_e *WorkflowRunEventRepo_Expecter) List(ctx any, runID any) *WorkflowRunEventRepo_List_Call { + return &WorkflowRunEventRepo_List_Call{Call: _e.mock.On("List", ctx, runID)} +} + +func (_c *WorkflowRunEventRepo_List_Call) Run(run func(ctx context.Context, runID uuid.UUID)) *WorkflowRunEventRepo_List_Call { + _c.Call.Run(func(args mock.Arguments) { + var arg0 context.Context + if args[0] != nil { + arg0 = args[0].(context.Context) + } + var arg1 uuid.UUID + if args[1] != nil { + arg1 = args[1].(uuid.UUID) + } + run( + arg0, + arg1, + ) + }) + return _c +} + +func (_c *WorkflowRunEventRepo_List_Call) Return(workflowRunEvents []*biz.WorkflowRunEvent, err error) *WorkflowRunEventRepo_List_Call { + _c.Call.Return(workflowRunEvents, err) + return _c +} + +func (_c *WorkflowRunEventRepo_List_Call) RunAndReturn(run func(ctx context.Context, runID uuid.UUID) ([]*biz.WorkflowRunEvent, error)) *WorkflowRunEventRepo_List_Call { + _c.Call.Return(run) + return _c +} diff --git a/app/controlplane/pkg/biz/testhelpers/database.go b/app/controlplane/pkg/biz/testhelpers/database.go index d6dbfb36b..0549222f6 100644 --- a/app/controlplane/pkg/biz/testhelpers/database.go +++ b/app/controlplane/pkg/biz/testhelpers/database.go @@ -63,6 +63,7 @@ type TestingUseCases struct { WorkflowContract *biz.WorkflowContractUseCase Workflow *biz.WorkflowUseCase WorkflowRun *biz.WorkflowRunUseCase + WorkflowRunEvent *biz.WorkflowRunEventUseCase Prometheus *biz.PrometheusUseCase User *biz.UserUseCase RobotAccount *biz.RobotAccountUseCase @@ -87,6 +88,7 @@ type TestingRepos struct { Referrer biz.ReferrerRepo Workflow biz.WorkflowRepo WorkflowRunRepo biz.WorkflowRunRepo + WorkflowRunEvent biz.WorkflowRunEventRepo AttestationState biz.AttestationStateRepo OrganizationRepo biz.OrganizationRepo GroupRepo biz.GroupRepo diff --git a/app/controlplane/pkg/biz/testhelpers/wire_gen.go b/app/controlplane/pkg/biz/testhelpers/wire_gen.go index 75bbabf80..cfa0c9367 100644 --- a/app/controlplane/pkg/biz/testhelpers/wire_gen.go +++ b/app/controlplane/pkg/biz/testhelpers/wire_gen.go @@ -120,6 +120,8 @@ func WireTestData(contextContext context.Context, testDatabase *TestDatabase, t cleanup() return nil, nil, err } + workflowRunEventRepo := data.NewWorkflowRunEventRepo(dataData, logger) + workflowRunEventUseCase := biz.NewWorkflowRunEventUseCase(workflowRunEventRepo, logger) v2 := NewPromSpec() orgMetricsRepo := data.NewOrgMetricsRepo(dataData, logger) orgMetricsUseCase, err := biz.NewOrgMetricsUseCase(orgMetricsRepo, organizationRepo, workflowUseCase, logger) @@ -177,6 +179,7 @@ func WireTestData(contextContext context.Context, testDatabase *TestDatabase, t Referrer: referrerRepo, Workflow: workflowRepo, WorkflowRunRepo: workflowRunRepo, + WorkflowRunEvent: workflowRunEventRepo, AttestationState: attestationStateRepo, OrganizationRepo: organizationRepo, GroupRepo: groupRepo, @@ -195,6 +198,7 @@ func WireTestData(contextContext context.Context, testDatabase *TestDatabase, t WorkflowContract: workflowContractUseCase, Workflow: workflowUseCase, WorkflowRun: workflowRunUseCase, + WorkflowRunEvent: workflowRunEventUseCase, Prometheus: prometheusUseCase, User: userUseCase, RobotAccount: robotAccountUseCase, diff --git a/app/controlplane/pkg/biz/workflowrun.go b/app/controlplane/pkg/biz/workflowrun.go index 521319b25..53c163cbb 100644 --- a/app/controlplane/pkg/biz/workflowrun.go +++ b/app/controlplane/pkg/biz/workflowrun.go @@ -120,7 +120,7 @@ type WorkflowRunRepo interface { List(ctx context.Context, orgID uuid.UUID, f *RunListFilters, p *pagination.CursorOptions) ([]*WorkflowRun, string, error) // List the runs that have not finished and are older than a given time ListNotFinishedOlderThan(ctx context.Context, olderThan time.Time, limit int) ([]*WorkflowRun, error) - // Set run as expired + // Set run as expired. It returns ErrFailedPrecondition when the run is no longer in progress Expire(ctx context.Context, id uuid.UUID) error } @@ -178,12 +178,16 @@ type PromObservable interface { type WorkflowRunExpirerUseCase struct { wfRunRepo WorkflowRunRepo PromObservable PromObservable + runEvents *WorkflowRunEventUseCase logger *log.Helper } const ( defaultWorkflowRunExpirationWindow = time.Hour defaultWorkflowRunExpirationCheckInterval = time.Minute + defaultWorkflowRunEventsRetention = 90 * 24 * time.Hour + // number of old run events deleted in each batch of a sweep + workflowRunEventsDeleteBatchSize = 1000 ) type WorkflowRunExpirerOpts struct { @@ -191,17 +195,20 @@ type WorkflowRunExpirerOpts struct { ExpirationWindow time.Duration // Interval between expiration sweeps. Defaults to 1 minute. CheckInterval time.Duration + // Age after which the progress events of the runs are deleted. Defaults to 90 days. + EventsRetention time.Duration } -func NewWorkflowRunExpirerUseCase(wfrRepo WorkflowRunRepo, po PromObservable, logger log.Logger) *WorkflowRunExpirerUseCase { +func NewWorkflowRunExpirerUseCase(wfrRepo WorkflowRunRepo, po PromObservable, runEvents *WorkflowRunEventUseCase, logger log.Logger) *WorkflowRunExpirerUseCase { logger = log.With(logger, "component", "biz.WorkflowRunExpirer") - return &WorkflowRunExpirerUseCase{wfrRepo, po, log.NewHelper(logger)} + return &WorkflowRunExpirerUseCase{wfRunRepo: wfrRepo, PromObservable: po, runEvents: runEvents, logger: log.NewHelper(logger)} } func resolveWorkflowRunExpirerOpts(opts *WorkflowRunExpirerOpts) WorkflowRunExpirerOpts { resolved := WorkflowRunExpirerOpts{ ExpirationWindow: defaultWorkflowRunExpirationWindow, CheckInterval: defaultWorkflowRunExpirationCheckInterval, + EventsRetention: defaultWorkflowRunEventsRetention, } if opts == nil { return resolved @@ -212,6 +219,9 @@ func resolveWorkflowRunExpirerOpts(opts *WorkflowRunExpirerOpts) WorkflowRunExpi if opts.CheckInterval > 0 { resolved.CheckInterval = opts.CheckInterval } + if opts.EventsRetention > 0 { + resolved.EventsRetention = opts.EventsRetention + } return resolved } @@ -232,13 +242,38 @@ func (uc *WorkflowRunExpirerUseCase) Run(ctx context.Context, opts *WorkflowRunE if err := uc.ExpirationSweep(ctx, threshold); err != nil { uc.logger.Error(err) } + + if err := uc.EventsRetentionSweep(ctx, time.Now().Add(-resolvedOpts.EventsRetention)); err != nil { + uc.logger.Error(err) + } } timer.Reset(resolvedOpts.CheckInterval) } }() - uc.logger.Infof("periodic check enabled. interval=%s, expirationWindow=%s", resolvedOpts.CheckInterval, resolvedOpts.ExpirationWindow) + uc.logger.Infof("periodic check enabled. interval=%s, expirationWindow=%s, eventsRetention=%s", resolvedOpts.CheckInterval, resolvedOpts.ExpirationWindow, resolvedOpts.EventsRetention) +} + +// EventsRetentionSweep deletes the progress events created before olderThan. The runs stay. +func (uc *WorkflowRunExpirerUseCase) EventsRetentionSweep(ctx context.Context, olderThan time.Time) error { + ctx, span := otelx.Start(ctx, workflowRunTracer, "WorkflowRunExpirerUseCase.EventsRetentionSweep") + defer span.End() + + if uc.runEvents == nil { + return nil + } + + n, err := uc.runEvents.DeleteOlderThan(ctx, olderThan, workflowRunEventsDeleteBatchSize) + if err != nil { + return err + } + + if n > 0 { + uc.logger.Debugf("deleted %d workflow run events older than %s", n, olderThan.Format(time.RFC822)) + } + + return nil } // ExpirationSweep looks for runs older than the provider time and marks them as expired @@ -256,6 +291,10 @@ func (uc *WorkflowRunExpirerUseCase) ExpirationSweep(ctx context.Context, olderT for _, r := range toExpire { if err := uc.wfRunRepo.Expire(ctx, r.ID); err != nil { + // The run finished during the sweep, so it did not expire + if IsErrFailedPrecondition(err) { + continue + } return err } diff --git a/app/controlplane/pkg/biz/workflowrun_options_test.go b/app/controlplane/pkg/biz/workflowrun_options_test.go index 5b108c43d..732986dd2 100644 --- a/app/controlplane/pkg/biz/workflowrun_options_test.go +++ b/app/controlplane/pkg/biz/workflowrun_options_test.go @@ -27,6 +27,7 @@ func TestResolveWorkflowRunExpirerOpts(t *testing.T) { opts *WorkflowRunExpirerOpts wantExpirationWindow time.Duration wantCheckInterval time.Duration + wantEventsRetention time.Duration }{ { name: "nil options use defaults", @@ -71,9 +72,17 @@ func TestResolveWorkflowRunExpirerOpts(t *testing.T) { opts: &WorkflowRunExpirerOpts{ ExpirationWindow: 2 * time.Hour, CheckInterval: 5 * time.Minute, + EventsRetention: 24 * time.Hour, }, wantExpirationWindow: 2 * time.Hour, wantCheckInterval: 5 * time.Minute, + wantEventsRetention: 24 * time.Hour, + }, + { + name: "non-positive events retention uses the default", + opts: &WorkflowRunExpirerOpts{EventsRetention: -time.Hour}, + wantExpirationWindow: time.Hour, + wantCheckInterval: time.Minute, }, } @@ -82,6 +91,11 @@ func TestResolveWorkflowRunExpirerOpts(t *testing.T) { got := resolveWorkflowRunExpirerOpts(tt.opts) assert.Equal(t, tt.wantExpirationWindow, got.ExpirationWindow) assert.Equal(t, tt.wantCheckInterval, got.CheckInterval) + wantRetention := tt.wantEventsRetention + if wantRetention == 0 { + wantRetention = 90 * 24 * time.Hour + } + assert.Equal(t, wantRetention, got.EventsRetention) }) } } diff --git a/app/controlplane/pkg/biz/workflowrun_test.go b/app/controlplane/pkg/biz/workflowrun_test.go index ce6aea118..d38f8fc9b 100644 --- a/app/controlplane/pkg/biz/workflowrun_test.go +++ b/app/controlplane/pkg/biz/workflowrun_test.go @@ -38,6 +38,7 @@ type workflowrunExpirerTestSuite struct { useCase *biz.WorkflowRunExpirerUseCase repo *repoM.WorkflowRunRepo prometheusRepo *repoM.PromObservable + eventRepo *repoM.WorkflowRunEventRepo ctx context.Context err error toExpire []*biz.WorkflowRun @@ -64,7 +65,9 @@ func (s *workflowrunExpirerTestSuite) SetupTest() { s.repo = repoM.NewWorkflowRunRepo(s.T()) s.prometheusRepo = repoM.NewPromObservable(s.T()) - s.useCase = biz.NewWorkflowRunExpirerUseCase(s.repo, s.prometheusRepo, log.NewStdLogger(io.Discard)) + s.eventRepo = repoM.NewWorkflowRunEventRepo(s.T()) + logger := log.NewStdLogger(io.Discard) + s.useCase = biz.NewWorkflowRunExpirerUseCase(s.repo, s.prometheusRepo, biz.NewWorkflowRunEventUseCase(s.eventRepo, logger), logger) s.ctx = context.TODO() s.err = errors.New("an error") s.threshold = now @@ -103,6 +106,34 @@ func (s *workflowrunExpirerTestSuite) TestSweepExpireOK() { assert.NoError(err) } +// A run that finished during the sweep is skipped: no expiry metric, and the sweep goes on +func (s *workflowrunExpirerTestSuite) TestSweepSkipsRunFinishedDuringSweep() { + s.repo.On("ListNotFinishedOlderThan", mock.Anything, s.threshold, 100).Return(s.toExpire, nil) + s.repo.On("Expire", mock.Anything, s.toExpire[0].ID).Return(biz.NewErrFailedPreconditionStr("not in progress")) + s.repo.On("Expire", mock.Anything, s.toExpire[1].ID).Return(nil) + s.prometheusRepo.On("ObserveAttestationIfNeeded", mock.Anything, s.toExpire[1], biz.WorkflowRunExpired).Return(true) + + s.NoError(s.useCase.ExpirationSweep(s.ctx, s.threshold)) + s.prometheusRepo.AssertNotCalled(s.T(), "ObserveAttestationIfNeeded", mock.Anything, s.toExpire[0], biz.WorkflowRunExpired) +} + +// Only the events older than the retention period go, in batches until a short batch +func (s *workflowrunExpirerTestSuite) TestEventsRetentionSweep() { + olderThan := time.Now().Add(-90 * 24 * time.Hour) + + s.eventRepo.On("DeleteOlderThan", mock.Anything, olderThan, 1000).Return(1000, nil).Once() + s.eventRepo.On("DeleteOlderThan", mock.Anything, olderThan, 1000).Return(3, nil).Once() + + s.NoError(s.useCase.EventsRetentionSweep(s.ctx, olderThan)) +} + +func (s *workflowrunExpirerTestSuite) TestEventsRetentionSweepError() { + olderThan := time.Now().Add(-90 * 24 * time.Hour) + s.eventRepo.On("DeleteOlderThan", mock.Anything, olderThan, 1000).Return(0, s.err) + + s.ErrorIs(s.useCase.EventsRetentionSweep(s.ctx, olderThan), s.err) +} + func (s *workflowrunTestSuite) TestMarkAsFinished() { testCases := []struct { name string diff --git a/app/controlplane/pkg/biz/workflowrunevent.go b/app/controlplane/pkg/biz/workflowrunevent.go new file mode 100644 index 000000000..00c1ef665 --- /dev/null +++ b/app/controlplane/pkg/biz/workflowrunevent.go @@ -0,0 +1,306 @@ +// +// Copyright 2026 The Chainloop Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package biz + +import ( + "context" + "fmt" + "slices" + "strings" + "time" + "unicode/utf8" + + "github.com/chainloop-dev/chainloop/pkg/otelx" + "github.com/go-kratos/kratos/v2/log" + "github.com/google/uuid" +) + +var workflowRunEventTracer = otelx.Tracer("chainloop-controlplane", "biz/workflowrunevent") + +const ( + // MaxWorkflowRunEvents is the maximum number of events that a run can hold + MaxWorkflowRunEvents = 1000 + // MaxWorkflowRunEventMessageBytes is the maximum size of an event message + MaxWorkflowRunEventMessageBytes = 1024 + // WorkflowRunEventKeyAttestation is the key of the events that open and close the timeline of a run + WorkflowRunEventKeyAttestation = "chainloop.attestation" + // workflowRunEventKeyPrefix is the prefix of the keys of the automatic events + workflowRunEventKeyPrefix = "chainloop." + // workflowRunEventExpiredMessage is the message of the closing event of an expired run + workflowRunEventExpiredMessage = "expired" +) + +type WorkflowRunEventSource string + +const ( + WorkflowRunEventSourceCLI WorkflowRunEventSource = "cli" + WorkflowRunEventSourceControlPlane WorkflowRunEventSource = "control_plane" +) + +// Values implements the ent enum interface +func (WorkflowRunEventSource) Values() []string { + return []string{string(WorkflowRunEventSourceCLI), string(WorkflowRunEventSourceControlPlane)} +} + +type WorkflowRunEventType string + +const ( + WorkflowRunEventTypeAttestation WorkflowRunEventType = "attestation" + WorkflowRunEventTypeMaterial WorkflowRunEventType = "material" +) + +// Values implements the ent enum interface +func (WorkflowRunEventType) Values() []string { + return []string{string(WorkflowRunEventTypeAttestation), string(WorkflowRunEventTypeMaterial)} +} + +type WorkflowRunEventStatus string + +const ( + WorkflowRunEventStatusStarted WorkflowRunEventStatus = "started" + WorkflowRunEventStatusSucceeded WorkflowRunEventStatus = "succeeded" + WorkflowRunEventStatusFailed WorkflowRunEventStatus = "failed" + WorkflowRunEventStatusCanceled WorkflowRunEventStatus = "canceled" +) + +// Values implements the ent enum interface +func (WorkflowRunEventStatus) Values() []string { + return []string{ + string(WorkflowRunEventStatusStarted), string(WorkflowRunEventStatusSucceeded), + string(WorkflowRunEventStatusFailed), string(WorkflowRunEventStatusCanceled), + } +} + +// WorkflowRunEvent is a progress event of a workflow run. +// It is unsigned, informational data and never part of the attestation. +type WorkflowRunEvent struct { + ID uuid.UUID + WorkflowRunID uuid.UUID + // Set by the control plane when it receives the event + CreatedAt *time.Time + Source WorkflowRunEventSource + Type WorkflowRunEventType + // Events with the same key are one step of the timeline + Key string + Status WorkflowRunEventStatus + Message string + Attributes *WorkflowRunEventAttributes +} + +// WorkflowRunEventAttributes holds the typed attributes of an event. Only the field +// that matches the type of the event is set. +type WorkflowRunEventAttributes struct { + Attestation *WorkflowRunEventAttestationAttributes `json:"attestation,omitempty"` + Material *WorkflowRunEventMaterialAttributes `json:"material,omitempty"` +} + +type WorkflowRunEventAttestationAttributes struct { + ContractName string `json:"contract_name,omitempty"` + ContractRevision int32 `json:"contract_revision,omitempty"` + RunnerType string `json:"runner_type,omitempty"` + RemoteState bool `json:"remote_state,omitempty"` + CLIVersion string `json:"cli_version,omitempty"` + AttestationDigest string `json:"attestation_digest,omitempty"` + // Results of the attestation policies evaluated at init + Policies *WorkflowRunEventPolicyCounts `json:"policies,omitempty"` + // Materials that the attestation expects, from the contract and its policy groups, as + // init resolves them. Set on the start event. + ExpectedMaterials []*WorkflowRunEventExpectedMaterial `json:"expected_materials,omitempty"` +} + +type WorkflowRunEventExpectedMaterial struct { + Name string `json:"name"` + MaterialType string `json:"material_type,omitempty"` + Optional bool `json:"optional,omitempty"` + // Set when the material is one of a group, of which one is required + Group string `json:"group,omitempty"` +} + +type WorkflowRunEventMaterialAttributes struct { + Name string `json:"name,omitempty"` + MaterialType string `json:"material_type,omitempty"` + Value string `json:"value,omitempty"` + Digest string `json:"digest,omitempty"` + InContract bool `json:"in_contract,omitempty"` + AddedByCollector bool `json:"added_by_collector,omitempty"` + Policies *WorkflowRunEventPolicyCounts `json:"policies,omitempty"` +} + +type WorkflowRunEventPolicyCounts struct { + Evaluated int32 `json:"evaluated,omitempty"` + Passed int32 `json:"passed,omitempty"` + Violated int32 `json:"violated,omitempty"` + Skipped int32 `json:"skipped,omitempty"` + ViolatedPolicies []string `json:"violated_policies,omitempty"` +} + +type WorkflowRunEventRepo interface { + // Create stores the event. It locks the run and rejects the event when the run is not + // in progress or it already holds maxEvents events. + Create(ctx context.Context, event *WorkflowRunEvent, maxEvents int) (*WorkflowRunEvent, error) + // List returns the events of a run, oldest first + List(ctx context.Context, runID uuid.UUID) ([]*WorkflowRunEvent, error) + // DeleteOlderThan deletes up to limit events created before t, and returns how many it deleted. + DeleteOlderThan(ctx context.Context, t time.Time, limit int) (int, error) +} + +type WorkflowRunEventUseCase struct { + repo WorkflowRunEventRepo + logger *log.Helper +} + +func NewWorkflowRunEventUseCase(repo WorkflowRunEventRepo, logger log.Logger) *WorkflowRunEventUseCase { + return &WorkflowRunEventUseCase{repo: repo, logger: log.NewHelper(log.With(logger, "component", "biz.WorkflowRunEvent"))} +} + +// Record stores an event that the CLI sent. The run must be in progress. +func (uc *WorkflowRunEventUseCase) Record(ctx context.Context, runID string, event *WorkflowRunEvent) (*WorkflowRunEvent, error) { + ctx, span := otelx.Start(ctx, workflowRunEventTracer, "WorkflowRunEventUseCase.Record") + defer span.End() + + runUUID, err := uuid.Parse(runID) + if err != nil { + return nil, NewErrInvalidUUID(err) + } + + if event == nil { + return nil, NewErrValidationStr("event is required") + } + + if err := validateWorkflowRunEvent(event); err != nil { + return nil, err + } + + ev := *event + ev.WorkflowRunID = runUUID + ev.Source = WorkflowRunEventSourceCLI + + return uc.repo.Create(ctx, &ev, MaxWorkflowRunEvents) +} + +func validateWorkflowRunEvent(ev *WorkflowRunEvent) error { + if !strings.HasPrefix(ev.Key, workflowRunEventKeyPrefix) { + return NewErrValidationStr(fmt.Sprintf("event key must start with %q", workflowRunEventKeyPrefix)) + } + + if len(ev.Message) > MaxWorkflowRunEventMessageBytes { + return NewErrValidationStr(fmt.Sprintf("event message is longer than %d bytes", MaxWorkflowRunEventMessageBytes)) + } + + // the type of each attribute field that is set + var set []WorkflowRunEventType + if attrs := ev.Attributes; attrs != nil { + if attrs.Attestation != nil { + set = append(set, WorkflowRunEventTypeAttestation) + } + if attrs.Material != nil { + set = append(set, WorkflowRunEventTypeMaterial) + } + } + + if !slices.Contains(ev.Type.Values(), string(ev.Type)) { + return NewErrValidationStr(fmt.Sprintf("unsupported event type %q", ev.Type)) + } + + if len(set) > 1 || (len(set) == 1 && set[0] != ev.Type) { + return NewErrValidationStr(fmt.Sprintf("event attributes do not match the event type %q", ev.Type)) + } + + return nil +} + +// List returns the events of a run, oldest first. +func (uc *WorkflowRunEventUseCase) List(ctx context.Context, runID string) ([]*WorkflowRunEvent, error) { + ctx, span := otelx.Start(ctx, workflowRunEventTracer, "WorkflowRunEventUseCase.List") + defer span.End() + + runUUID, err := uuid.Parse(runID) + if err != nil { + return nil, NewErrInvalidUUID(err) + } + + return uc.repo.List(ctx, runUUID) +} + +// DeleteOlderThan deletes the events created before t, in batches of batchSize. +// It returns the number of deleted events. +func (uc *WorkflowRunEventUseCase) DeleteOlderThan(ctx context.Context, t time.Time, batchSize int) (int, error) { + ctx, span := otelx.Start(ctx, workflowRunEventTracer, "WorkflowRunEventUseCase.DeleteOlderThan") + defer span.End() + + var total int + for { + n, err := uc.repo.DeleteOlderThan(ctx, t, batchSize) + if err != nil { + return total, fmt.Errorf("deleting workflow run events: %w", err) + } + total += n + + if n < batchSize { + return total, nil + } + } +} + +// ClosingWorkflowRunEvent returns the event that closes the timeline of a run when it +// gets the given status. It returns nil for a status that does not finish the run. +func ClosingWorkflowRunEvent(runID uuid.UUID, runStatus WorkflowRunStatus, reason, attestationDigest string) *WorkflowRunEvent { + ev := &WorkflowRunEvent{ + WorkflowRunID: runID, + Source: WorkflowRunEventSourceControlPlane, + Type: WorkflowRunEventTypeAttestation, + Key: WorkflowRunEventKeyAttestation, + } + + switch runStatus { + case WorkflowRunSuccess: + // Automatic events that succeed have no message + ev.Status = WorkflowRunEventStatusSucceeded + if attestationDigest != "" { + ev.Attributes = &WorkflowRunEventAttributes{ + Attestation: &WorkflowRunEventAttestationAttributes{AttestationDigest: attestationDigest}, + } + } + case WorkflowRunCancelled: + ev.Status = WorkflowRunEventStatusCanceled + ev.Message = truncateBytes(reason, MaxWorkflowRunEventMessageBytes) + case WorkflowRunError: + ev.Status = WorkflowRunEventStatusFailed + ev.Message = truncateBytes(reason, MaxWorkflowRunEventMessageBytes) + case WorkflowRunExpired: + ev.Status = WorkflowRunEventStatusFailed + ev.Message = workflowRunEventExpiredMessage + default: + return nil + } + + return ev +} + +// truncateBytes cuts s to at most n bytes without splitting a UTF-8 character +func truncateBytes(s string, n int) string { + if len(s) <= n { + return s + } + + cut := s[:n] + // drop a trailing partial rune + for len(cut) > 0 && !utf8.ValidString(cut) { + cut = cut[:len(cut)-1] + } + + return cut +} diff --git a/app/controlplane/pkg/biz/workflowrunevent_test.go b/app/controlplane/pkg/biz/workflowrunevent_test.go new file mode 100644 index 000000000..329916027 --- /dev/null +++ b/app/controlplane/pkg/biz/workflowrunevent_test.go @@ -0,0 +1,150 @@ +// +// Copyright 2026 The Chainloop Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package biz + +import ( + "strings" + "testing" + "unicode/utf8" + + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const ( + sbomKey = "chainloop.material.sbom" + shortText = "abc" +) + +func TestValidateWorkflowRunEvent(t *testing.T) { + material := &WorkflowRunEventAttributes{Material: &WorkflowRunEventMaterialAttributes{Name: "sbom"}} + attestation := &WorkflowRunEventAttributes{Attestation: &WorkflowRunEventAttestationAttributes{ContractName: "build"}} + + testCases := []struct { + name string + event *WorkflowRunEvent + wantErr string + }{ + { + name: "material event", + event: &WorkflowRunEvent{Type: WorkflowRunEventTypeMaterial, Key: sbomKey, Attributes: material}, + }, + { + name: "event with no attributes", + event: &WorkflowRunEvent{Type: WorkflowRunEventTypeAttestation, Key: WorkflowRunEventKeyAttestation}, + }, + { + name: "key that is not automatic", + event: &WorkflowRunEvent{Type: WorkflowRunEventTypeMaterial, Key: "sbom", Attributes: material}, + wantErr: "must start with", + }, + { + name: "attributes of another type", + event: &WorkflowRunEvent{Type: WorkflowRunEventTypeMaterial, Key: sbomKey, Attributes: attestation}, + wantErr: "do not match", + }, + { + name: "unknown type", + event: &WorkflowRunEvent{Type: "custom", Key: "chainloop.x"}, + wantErr: "unsupported event type", + }, + { + name: "message over the limit", + event: &WorkflowRunEvent{Type: WorkflowRunEventTypeMaterial, Key: sbomKey, Message: strings.Repeat("a", MaxWorkflowRunEventMessageBytes+1)}, + wantErr: "longer than", + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + err := validateWorkflowRunEvent(tc.event) + if tc.wantErr == "" { + assert.NoError(t, err) + return + } + + require.Error(t, err) + assert.True(t, IsErrValidation(err)) + assert.Contains(t, err.Error(), tc.wantErr) + }) + } +} + +func TestClosingWorkflowRunEvent(t *testing.T) { + runID := uuid.New() + + testCases := []struct { + name string + status WorkflowRunStatus + reason string + digest string + wantNil bool + wantStatus WorkflowRunEventStatus + wantMessage string + wantDigest string + }{ + {name: "store", status: WorkflowRunSuccess, reason: "ignored", digest: "sha256:abc", wantStatus: WorkflowRunEventStatusSucceeded, wantDigest: "sha256:abc"}, + {name: "cancellation", status: WorkflowRunCancelled, reason: "stopped", wantStatus: WorkflowRunEventStatusCanceled, wantMessage: "stopped"}, + {name: "failure", status: WorkflowRunError, reason: "build failed", wantStatus: WorkflowRunEventStatusFailed, wantMessage: "build failed"}, + {name: "expiry", status: WorkflowRunExpired, wantStatus: WorkflowRunEventStatusFailed, wantMessage: "expired"}, + {name: "not a final status", status: WorkflowRunInitialized, wantNil: true}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + got := ClosingWorkflowRunEvent(runID, tc.status, tc.reason, tc.digest) + if tc.wantNil { + assert.Nil(t, got) + return + } + + require.NotNil(t, got) + assert.Equal(t, runID, got.WorkflowRunID) + assert.Equal(t, WorkflowRunEventSourceControlPlane, got.Source) + assert.Equal(t, WorkflowRunEventKeyAttestation, got.Key) + assert.Equal(t, tc.wantStatus, got.Status) + assert.Equal(t, tc.wantMessage, got.Message) + if tc.wantDigest != "" { + assert.Equal(t, tc.wantDigest, got.Attributes.Attestation.AttestationDigest) + } else { + assert.Nil(t, got.Attributes) + } + }) + } +} + +func TestTruncateBytes(t *testing.T) { + testCases := []struct { + name string + in string + n int + want string + }{ + {name: "short", in: shortText, n: 5, want: shortText}, + {name: "cut", in: "abcdef", n: 3, want: "abc"}, + // "é" is two bytes, so a cut in the middle drops it + {name: "no partial rune", in: "aé", n: 2, want: "a"}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + got := truncateBytes(tc.in, tc.n) + assert.Equal(t, tc.want, got) + assert.True(t, utf8.ValidString(got)) + }) + } +} diff --git a/app/controlplane/pkg/biz/workflowrunprogress.go b/app/controlplane/pkg/biz/workflowrunprogress.go new file mode 100644 index 000000000..5bd5437db --- /dev/null +++ b/app/controlplane/pkg/biz/workflowrunprogress.go @@ -0,0 +1,206 @@ +// +// Copyright 2026 The Chainloop Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package biz + +import ( + schemav1 "github.com/chainloop-dev/chainloop/app/controlplane/api/workflowcontract/v1" +) + +type WorkflowRunMaterialRequirement string + +const ( + WorkflowRunMaterialRequired WorkflowRunMaterialRequirement = "required" + WorkflowRunMaterialOptional WorkflowRunMaterialRequirement = "optional" + WorkflowRunMaterialOneOfGroup WorkflowRunMaterialRequirement = "one_of_group" + WorkflowRunMaterialNotInContract WorkflowRunMaterialRequirement = "not_in_contract" +) + +type WorkflowRunMaterialStatus string + +const ( + WorkflowRunMaterialMissing WorkflowRunMaterialStatus = "missing" + WorkflowRunMaterialProvided WorkflowRunMaterialStatus = "provided" + WorkflowRunMaterialFailed WorkflowRunMaterialStatus = "failed" +) + +// WorkflowRunProgress is the progress of a run in progress, ready to show. +type WorkflowRunProgress struct { + // One row for each expected material, in contract order, then the materials not in the contract + Materials []*WorkflowRunProgressMaterial + // Required materials, where a group of materials counts once + RequiredTotal int32 + RequiredProvided int32 + // Results of the attestation policies evaluated at init + AttestationPolicies *WorkflowRunEventPolicyCounts +} + +type WorkflowRunProgressMaterial struct { + Name string + MaterialType string + Requirement WorkflowRunMaterialRequirement + // Set when the requirement is one of a group + Group string + Status WorkflowRunMaterialStatus + // Value and policy results of the last successful add + Value string + Policies *WorkflowRunEventPolicyCounts + // Error of the last add, when it failed + LastError string + FailedAttempts int32 +} + +// contractExpectedMaterials returns the materials of a contract version. It is the fallback +// for a run whose start event does not list the materials that init resolved, for example +// a run of an older CLI. It does not have the materials of the policy groups. +// +//nolint:staticcheck // the V1 schema is the fallback for contracts with no V2 body +func contractExpectedMaterials(c *Contract) []*WorkflowRunEventExpectedMaterial { + var materials []*schemav1.CraftingSchema_Material + switch { + case c == nil: + case c.isV2Schema(): + materials = c.Schemav2.GetSpec().GetMaterials() + case c.isV1Schema(): + materials = c.Schema.GetMaterials() + } + + out := make([]*WorkflowRunEventExpectedMaterial, 0, len(materials)) + for _, m := range materials { + out = append(out, &WorkflowRunEventExpectedMaterial{ + Name: m.GetName(), MaterialType: m.GetType().String(), Optional: m.GetOptional(), Group: m.GetGroup(), + }) + } + + return out +} + +// BuildWorkflowRunProgress joins the expected materials with the material events of a run. +// The expected materials come from the start event, which lists them as init resolved them, +// contract and policy groups. A run with no such list uses the materials of its contract. +func BuildWorkflowRunProgress(contract *Contract, events []*WorkflowRunEvent) *WorkflowRunProgress { + progress := &WorkflowRunProgress{} + var expected []*WorkflowRunEventExpectedMaterial + + // the attempts of each material, in the order they were first reported + type attempts struct { + lastSuccess *WorkflowRunEvent + // whether the last add failed, and its error + lastFailed bool + lastError string + failed int32 + } + byName := make(map[string]*attempts) + var order []string + for _, e := range events { + attrs := e.Attributes + switch { + case attrs == nil: + case attrs.Material != nil && attrs.Material.Name != "": + name := attrs.Material.Name + a, ok := byName[name] + if !ok { + a = &attempts{} + byName[name] = a + order = append(order, name) + } + switch e.Status { + case WorkflowRunEventStatusSucceeded: + a.lastSuccess, a.lastFailed, a.lastError = e, false, "" + case WorkflowRunEventStatusFailed: + a.lastFailed, a.lastError = true, e.Message + a.failed++ + } + case attrs.Attestation != nil && e.Status == WorkflowRunEventStatusStarted: + progress.AttestationPolicies = attrs.Attestation.Policies + if len(attrs.Attestation.ExpectedMaterials) > 0 { + expected = attrs.Attestation.ExpectedMaterials + } + } + } + + if expected == nil { + expected = contractExpectedMaterials(contract) + } + progress.Materials = make([]*WorkflowRunProgressMaterial, 0, len(expected)+len(order)) + + fill := func(m *WorkflowRunProgressMaterial) { + m.Status = WorkflowRunMaterialMissing + a, ok := byName[m.Name] + if !ok { + return + } + + m.FailedAttempts, m.LastError = a.failed, a.lastError + if a.lastFailed { + m.Status = WorkflowRunMaterialFailed + } + + // A failed add after a successful one leaves the material in the attestation + if s := a.lastSuccess; s != nil { + m.Status = WorkflowRunMaterialProvided + m.Value = s.Attributes.Material.Value + m.Policies = s.Attributes.Material.Policies + if m.MaterialType == "" { + m.MaterialType = s.Attributes.Material.MaterialType + } + } + } + + inContract := make(map[string]bool, len(expected)) + // A group requires at least one of its materials, so each group counts once + groupProvided := make(map[string]bool) + for _, em := range expected { + inContract[em.Name] = true + m := &WorkflowRunProgressMaterial{Name: em.Name, MaterialType: em.MaterialType, Requirement: WorkflowRunMaterialRequired} + switch { + case em.Group != "": + m.Requirement, m.Group = WorkflowRunMaterialOneOfGroup, em.Group + case em.Optional: + m.Requirement = WorkflowRunMaterialOptional + } + fill(m) + + provided := m.Status == WorkflowRunMaterialProvided + switch m.Requirement { + case WorkflowRunMaterialOneOfGroup: + groupProvided[m.Group] = groupProvided[m.Group] || provided + case WorkflowRunMaterialRequired: + progress.RequiredTotal++ + if provided { + progress.RequiredProvided++ + } + } + progress.Materials = append(progress.Materials, m) + } + + for _, provided := range groupProvided { + progress.RequiredTotal++ + if provided { + progress.RequiredProvided++ + } + } + + for _, name := range order { + if inContract[name] { + continue + } + m := &WorkflowRunProgressMaterial{Name: name, Requirement: WorkflowRunMaterialNotInContract} + fill(m) + progress.Materials = append(progress.Materials, m) + } + + return progress +} diff --git a/app/controlplane/pkg/biz/workflowrunprogress_test.go b/app/controlplane/pkg/biz/workflowrunprogress_test.go new file mode 100644 index 000000000..4f798fd78 --- /dev/null +++ b/app/controlplane/pkg/biz/workflowrunprogress_test.go @@ -0,0 +1,200 @@ +// +// Copyright 2026 The Chainloop Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package biz + +import ( + "testing" + + schemav1 "github.com/chainloop-dev/chainloop/app/controlplane/api/workflowcontract/v1" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const ( + progressSBOM = "sbom" + progressImage = "image" + progressCycloneDX = "SBOM_CYCLONEDX_JSON" + progressDupErr = "material already exists in the attestation" + progressSBOMFile = "sbom.json" + progressNotes = "notes" +) + +var progressImageType = schemav1.CraftingSchema_Material_CONTAINER_IMAGE.String() + +func TestBuildWorkflowRunProgress(t *testing.T) { + added := func(name, value string) *WorkflowRunEvent { + return &WorkflowRunEvent{Status: WorkflowRunEventStatusSucceeded, Attributes: &WorkflowRunEventAttributes{ + Material: &WorkflowRunEventMaterialAttributes{Name: name, MaterialType: progressCycloneDX, Value: value}, + }} + } + failed := func(name, msg string) *WorkflowRunEvent { + return &WorkflowRunEvent{Status: WorkflowRunEventStatusFailed, Message: msg, Attributes: &WorkflowRunEventAttributes{ + Material: &WorkflowRunEventMaterialAttributes{Name: name}, + }} + } + started := func(expected ...*WorkflowRunEventExpectedMaterial) *WorkflowRunEvent { + return &WorkflowRunEvent{Status: WorkflowRunEventStatusStarted, Attributes: &WorkflowRunEventAttributes{ + Attestation: &WorkflowRunEventAttestationAttributes{ExpectedMaterials: expected}, + }} + } + contractOf := func(materials ...*schemav1.CraftingSchema_Material) *Contract { + return &Contract{Schemav2: &schemav1.CraftingSchemaV2{Spec: &schemav1.CraftingSchemaV2Spec{Materials: materials}}} + } + contract := contractOf(&schemav1.CraftingSchema_Material{Name: progressSBOM, Type: schemav1.CraftingSchema_Material_SBOM_CYCLONEDX_JSON}) + + testCases := []struct { + name string + contract *Contract + events []*WorkflowRunEvent + // the material to check, and what it must be + material string + want *WorkflowRunProgressMaterial + // required counts of the whole run + wantTotal, wantProvided int32 + }{ + { + name: "no add yet", contract: contract, events: []*WorkflowRunEvent{started()}, + material: progressSBOM, wantTotal: 1, + want: &WorkflowRunProgressMaterial{Name: progressSBOM, MaterialType: progressCycloneDX, Requirement: WorkflowRunMaterialRequired, Status: WorkflowRunMaterialMissing}, + }, + { + name: "failed add, never provided", contract: contract, events: []*WorkflowRunEvent{failed(progressSBOM, "bad bomFormat")}, + material: progressSBOM, wantTotal: 1, + want: &WorkflowRunProgressMaterial{Name: progressSBOM, MaterialType: progressCycloneDX, Requirement: WorkflowRunMaterialRequired, + Status: WorkflowRunMaterialFailed, LastError: "bad bomFormat", FailedAttempts: 1}, + }, + { + name: "failed add with no error text", contract: contract, events: []*WorkflowRunEvent{failed(progressSBOM, "")}, + material: progressSBOM, wantTotal: 1, + want: &WorkflowRunProgressMaterial{Name: progressSBOM, MaterialType: progressCycloneDX, Requirement: WorkflowRunMaterialRequired, + Status: WorkflowRunMaterialFailed, FailedAttempts: 1}, + }, + { + name: "failed add, then a successful one", contract: contract, + events: []*WorkflowRunEvent{failed(progressSBOM, "bad bomFormat"), added(progressSBOM, progressSBOMFile)}, + material: progressSBOM, wantTotal: 1, wantProvided: 1, + want: &WorkflowRunProgressMaterial{Name: progressSBOM, MaterialType: progressCycloneDX, Requirement: WorkflowRunMaterialRequired, + Status: WorkflowRunMaterialProvided, Value: progressSBOMFile, FailedAttempts: 1}, + }, + { + name: "successful add, then a rejected duplicate add", contract: contract, + events: []*WorkflowRunEvent{added(progressSBOM, progressSBOMFile), failed(progressSBOM, progressDupErr)}, + material: progressSBOM, wantTotal: 1, wantProvided: 1, + want: &WorkflowRunProgressMaterial{Name: progressSBOM, MaterialType: progressCycloneDX, Requirement: WorkflowRunMaterialRequired, + Status: WorkflowRunMaterialProvided, Value: progressSBOMFile, LastError: progressDupErr, FailedAttempts: 1}, + }, + { + name: "successful add, then a failed replacement", contract: contract, + events: []*WorkflowRunEvent{added(progressSBOM, progressSBOMFile), failed(progressSBOM, "invalid CycloneDX document")}, + material: progressSBOM, wantTotal: 1, wantProvided: 1, + want: &WorkflowRunProgressMaterial{Name: progressSBOM, MaterialType: progressCycloneDX, Requirement: WorkflowRunMaterialRequired, + Status: WorkflowRunMaterialProvided, Value: progressSBOMFile, LastError: "invalid CycloneDX document", FailedAttempts: 1}, + }, + { + name: "material that only a policy group requires, from the start event", + // the contract has no materials, init resolved the one of the policy group + events: []*WorkflowRunEvent{started(&WorkflowRunEventExpectedMaterial{Name: progressSBOM, MaterialType: progressCycloneDX})}, + material: progressSBOM, wantTotal: 1, + want: &WorkflowRunProgressMaterial{Name: progressSBOM, MaterialType: progressCycloneDX, Requirement: WorkflowRunMaterialRequired, Status: WorkflowRunMaterialMissing}, + }, + { + name: "provided policy group material is in the contract", + events: []*WorkflowRunEvent{started(&WorkflowRunEventExpectedMaterial{Name: progressSBOM, MaterialType: progressCycloneDX}), added(progressSBOM, progressSBOMFile)}, + material: progressSBOM, wantTotal: 1, wantProvided: 1, + want: &WorkflowRunProgressMaterial{Name: progressSBOM, MaterialType: progressCycloneDX, Requirement: WorkflowRunMaterialRequired, + Status: WorkflowRunMaterialProvided, Value: progressSBOMFile}, + }, + { + name: "the start event list wins over the contract", + // declared in the contract and resolved again by init, it shows once + contract: contract, + events: []*WorkflowRunEvent{started( + &WorkflowRunEventExpectedMaterial{Name: progressSBOM, MaterialType: progressCycloneDX}, + &WorkflowRunEventExpectedMaterial{Name: progressImage, MaterialType: progressImageType}, + )}, + material: progressImage, wantTotal: 2, + want: &WorkflowRunProgressMaterial{Name: progressImage, MaterialType: progressImageType, Requirement: WorkflowRunMaterialRequired, Status: WorkflowRunMaterialMissing}, + }, + { + name: "material not in the contract", + contract: contract, events: []*WorkflowRunEvent{added("build-log", "build.log")}, + material: "build-log", wantTotal: 1, + want: &WorkflowRunProgressMaterial{Name: "build-log", MaterialType: progressCycloneDX, Requirement: WorkflowRunMaterialNotInContract, + Status: WorkflowRunMaterialProvided, Value: "build.log"}, + }, + { + name: "a group counts once, provided when one of its materials is", + contract: contractOf( + &schemav1.CraftingSchema_Material{Name: "spdx", Type: schemav1.CraftingSchema_Material_SBOM_SPDX_JSON, Group: progressSBOM}, + &schemav1.CraftingSchema_Material{Name: "cyclonedx", Type: schemav1.CraftingSchema_Material_SBOM_CYCLONEDX_JSON, Group: progressSBOM}, + &schemav1.CraftingSchema_Material{Name: progressNotes, Type: schemav1.CraftingSchema_Material_STRING, Optional: true}, + ), + events: []*WorkflowRunEvent{added("cyclonedx", "bom.json")}, + material: progressNotes, wantTotal: 1, wantProvided: 1, + want: &WorkflowRunProgressMaterial{Name: progressNotes, MaterialType: "STRING", Requirement: WorkflowRunMaterialOptional, Status: WorkflowRunMaterialMissing}, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + got := BuildWorkflowRunProgress(tc.contract, tc.events) + assert.Equal(t, tc.wantTotal, got.RequiredTotal) + assert.Equal(t, tc.wantProvided, got.RequiredProvided) + + var m *WorkflowRunProgressMaterial + for _, gm := range got.Materials { + if gm.Name == tc.material { + require.Nil(t, m, "each material shows once") + m = gm + } + } + require.NotNil(t, m) + assert.Equal(t, tc.want, m) + }) + } +} + +func TestBuildWorkflowRunProgressAttestationPolicies(t *testing.T) { + counts := &WorkflowRunEventPolicyCounts{Evaluated: 2, Passed: 2} + got := BuildWorkflowRunProgress(nil, []*WorkflowRunEvent{{ + Status: WorkflowRunEventStatusStarted, + Attributes: &WorkflowRunEventAttributes{Attestation: &WorkflowRunEventAttestationAttributes{Policies: counts}}, + }}) + assert.Equal(t, counts, got.AttestationPolicies) + assert.Empty(t, got.Materials) +} + +//nolint:staticcheck // the V1 schema is the fallback for contracts with no V2 body +func TestContractExpectedMaterials(t *testing.T) { + material := &schemav1.CraftingSchema_Material{Name: progressSBOM, Type: schemav1.CraftingSchema_Material_SBOM_CYCLONEDX_JSON, Optional: true} + want := []*WorkflowRunEventExpectedMaterial{{Name: progressSBOM, MaterialType: progressCycloneDX, Optional: true}} + + testCases := []struct { + name string + contract *Contract + want []*WorkflowRunEventExpectedMaterial + }{ + {name: "V1 contract", contract: &Contract{Schema: &schemav1.CraftingSchema{Materials: []*schemav1.CraftingSchema_Material{material}}}, want: want}, + {name: "V2 contract", contract: &Contract{Schemav2: &schemav1.CraftingSchemaV2{Spec: &schemav1.CraftingSchemaV2Spec{Materials: []*schemav1.CraftingSchema_Material{material}}}}, want: want}, + {name: "no contract", want: []*WorkflowRunEventExpectedMaterial{}}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, contractExpectedMaterials(tc.contract)) + }) + } +} diff --git a/app/controlplane/pkg/data/data.go b/app/controlplane/pkg/data/data.go index 36f7a263c..01f1b9c49 100644 --- a/app/controlplane/pkg/data/data.go +++ b/app/controlplane/pkg/data/data.go @@ -46,6 +46,7 @@ var ProviderSet = wire.NewSet( NewUserRepo, NewRobotAccountRepo, NewWorkflowRunRepo, + NewWorkflowRunEventRepo, NewOrganizationRepo, NewWorkflowContractRepo, NewCASBackendRepo, diff --git a/app/controlplane/pkg/data/ent/client.go b/app/controlplane/pkg/data/ent/client.go index 002b8359a..72d88cf68 100644 --- a/app/controlplane/pkg/data/ent/client.go +++ b/app/controlplane/pkg/data/ent/client.go @@ -38,6 +38,7 @@ import ( "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowcontract" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowcontractversion" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowrun" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowrunevent" ) // Client is the client that holds all ent builders. @@ -89,6 +90,8 @@ type Client struct { WorkflowContractVersion *WorkflowContractVersionClient // WorkflowRun is the client for interacting with the WorkflowRun builders. WorkflowRun *WorkflowRunClient + // WorkflowRunEvent is the client for interacting with the WorkflowRunEvent builders. + WorkflowRunEvent *WorkflowRunEventClient } // NewClient creates a new client configured with the given options. @@ -122,6 +125,7 @@ func (c *Client) init() { c.WorkflowContract = NewWorkflowContractClient(c.config) c.WorkflowContractVersion = NewWorkflowContractVersionClient(c.config) c.WorkflowRun = NewWorkflowRunClient(c.config) + c.WorkflowRunEvent = NewWorkflowRunEventClient(c.config) } type ( @@ -236,6 +240,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { WorkflowContract: NewWorkflowContractClient(cfg), WorkflowContractVersion: NewWorkflowContractVersionClient(cfg), WorkflowRun: NewWorkflowRunClient(cfg), + WorkflowRunEvent: NewWorkflowRunEventClient(cfg), }, nil } @@ -277,6 +282,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) WorkflowContract: NewWorkflowContractClient(cfg), WorkflowContractVersion: NewWorkflowContractVersionClient(cfg), WorkflowRun: NewWorkflowRunClient(cfg), + WorkflowRunEvent: NewWorkflowRunEventClient(cfg), }, nil } @@ -311,6 +317,7 @@ func (c *Client) Use(hooks ...Hook) { c.Membership, c.OrgInvitation, c.Organization, c.Project, c.ProjectVersion, c.Referrer, c.ReferrerReference, c.RobotAccount, c.User, c.Workflow, c.WorkflowContract, c.WorkflowContractVersion, c.WorkflowRun, + c.WorkflowRunEvent, } { n.Use(hooks...) } @@ -325,6 +332,7 @@ func (c *Client) Intercept(interceptors ...Interceptor) { c.Membership, c.OrgInvitation, c.Organization, c.Project, c.ProjectVersion, c.Referrer, c.ReferrerReference, c.RobotAccount, c.User, c.Workflow, c.WorkflowContract, c.WorkflowContractVersion, c.WorkflowRun, + c.WorkflowRunEvent, } { n.Intercept(interceptors...) } @@ -377,6 +385,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { return c.WorkflowContractVersion.mutate(ctx, m) case *WorkflowRunMutation: return c.WorkflowRun.mutate(ctx, m) + case *WorkflowRunEventMutation: + return c.WorkflowRunEvent.mutate(ctx, m) default: return nil, fmt.Errorf("ent: unknown mutation type %T", m) } @@ -4290,6 +4300,22 @@ func (c *WorkflowRunClient) QueryAttestationBundle(_m *WorkflowRun) *Attestation return query } +// QueryEvents queries the events edge of a WorkflowRun. +func (c *WorkflowRunClient) QueryEvents(_m *WorkflowRun) *WorkflowRunEventQuery { + query := (&WorkflowRunEventClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(workflowrun.Table, workflowrun.FieldID, id), + sqlgraph.To(workflowrunevent.Table, workflowrunevent.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, workflowrun.EventsTable, workflowrun.EventsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + // Hooks returns the client hooks. func (c *WorkflowRunClient) Hooks() []Hook { return c.hooks.WorkflowRun @@ -4315,6 +4341,155 @@ func (c *WorkflowRunClient) mutate(ctx context.Context, m *WorkflowRunMutation) } } +// WorkflowRunEventClient is a client for the WorkflowRunEvent schema. +type WorkflowRunEventClient struct { + config +} + +// NewWorkflowRunEventClient returns a client for the WorkflowRunEvent from the given config. +func NewWorkflowRunEventClient(c config) *WorkflowRunEventClient { + return &WorkflowRunEventClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `workflowrunevent.Hooks(f(g(h())))`. +func (c *WorkflowRunEventClient) Use(hooks ...Hook) { + c.hooks.WorkflowRunEvent = append(c.hooks.WorkflowRunEvent, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `workflowrunevent.Intercept(f(g(h())))`. +func (c *WorkflowRunEventClient) Intercept(interceptors ...Interceptor) { + c.inters.WorkflowRunEvent = append(c.inters.WorkflowRunEvent, interceptors...) +} + +// Create returns a builder for creating a WorkflowRunEvent entity. +func (c *WorkflowRunEventClient) Create() *WorkflowRunEventCreate { + mutation := newWorkflowRunEventMutation(c.config, OpCreate) + return &WorkflowRunEventCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of WorkflowRunEvent entities. +func (c *WorkflowRunEventClient) CreateBulk(builders ...*WorkflowRunEventCreate) *WorkflowRunEventCreateBulk { + return &WorkflowRunEventCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *WorkflowRunEventClient) MapCreateBulk(slice any, setFunc func(*WorkflowRunEventCreate, int)) *WorkflowRunEventCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &WorkflowRunEventCreateBulk{err: fmt.Errorf("calling to WorkflowRunEventClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*WorkflowRunEventCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &WorkflowRunEventCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for WorkflowRunEvent. +func (c *WorkflowRunEventClient) Update() *WorkflowRunEventUpdate { + mutation := newWorkflowRunEventMutation(c.config, OpUpdate) + return &WorkflowRunEventUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *WorkflowRunEventClient) UpdateOne(_m *WorkflowRunEvent) *WorkflowRunEventUpdateOne { + mutation := newWorkflowRunEventMutation(c.config, OpUpdateOne, withWorkflowRunEvent(_m)) + return &WorkflowRunEventUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *WorkflowRunEventClient) UpdateOneID(id uuid.UUID) *WorkflowRunEventUpdateOne { + mutation := newWorkflowRunEventMutation(c.config, OpUpdateOne, withWorkflowRunEventID(id)) + return &WorkflowRunEventUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for WorkflowRunEvent. +func (c *WorkflowRunEventClient) Delete() *WorkflowRunEventDelete { + mutation := newWorkflowRunEventMutation(c.config, OpDelete) + return &WorkflowRunEventDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *WorkflowRunEventClient) DeleteOne(_m *WorkflowRunEvent) *WorkflowRunEventDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *WorkflowRunEventClient) DeleteOneID(id uuid.UUID) *WorkflowRunEventDeleteOne { + builder := c.Delete().Where(workflowrunevent.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &WorkflowRunEventDeleteOne{builder} +} + +// Query returns a query builder for WorkflowRunEvent. +func (c *WorkflowRunEventClient) Query() *WorkflowRunEventQuery { + return &WorkflowRunEventQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeWorkflowRunEvent}, + inters: c.Interceptors(), + } +} + +// Get returns a WorkflowRunEvent entity by its id. +func (c *WorkflowRunEventClient) Get(ctx context.Context, id uuid.UUID) (*WorkflowRunEvent, error) { + return c.Query().Where(workflowrunevent.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *WorkflowRunEventClient) GetX(ctx context.Context, id uuid.UUID) *WorkflowRunEvent { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryWorkflowRun queries the workflow_run edge of a WorkflowRunEvent. +func (c *WorkflowRunEventClient) QueryWorkflowRun(_m *WorkflowRunEvent) *WorkflowRunQuery { + query := (&WorkflowRunClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(workflowrunevent.Table, workflowrunevent.FieldID, id), + sqlgraph.To(workflowrun.Table, workflowrun.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, workflowrunevent.WorkflowRunTable, workflowrunevent.WorkflowRunColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *WorkflowRunEventClient) Hooks() []Hook { + return c.hooks.WorkflowRunEvent +} + +// Interceptors returns the client interceptors. +func (c *WorkflowRunEventClient) Interceptors() []Interceptor { + return c.inters.WorkflowRunEvent +} + +func (c *WorkflowRunEventClient) mutate(ctx context.Context, m *WorkflowRunEventMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&WorkflowRunEventCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&WorkflowRunEventUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&WorkflowRunEventUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&WorkflowRunEventDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown WorkflowRunEvent mutation op: %q", m.Op()) + } +} + // hooks and interceptors per client, for fast access. type ( hooks struct { @@ -4322,13 +4497,13 @@ type ( Integration, IntegrationAttachment, LoginHandoff, Membership, OrgInvitation, Organization, Project, ProjectVersion, Referrer, ReferrerReference, RobotAccount, User, Workflow, WorkflowContract, WorkflowContractVersion, - WorkflowRun []ent.Hook + WorkflowRun, WorkflowRunEvent []ent.Hook } inters struct { APIToken, Attestation, CASBackend, CASMapping, Group, GroupMembership, Integration, IntegrationAttachment, LoginHandoff, Membership, OrgInvitation, Organization, Project, ProjectVersion, Referrer, ReferrerReference, RobotAccount, User, Workflow, WorkflowContract, WorkflowContractVersion, - WorkflowRun []ent.Interceptor + WorkflowRun, WorkflowRunEvent []ent.Interceptor } ) diff --git a/app/controlplane/pkg/data/ent/ent.go b/app/controlplane/pkg/data/ent/ent.go index a77070a39..22008ce76 100644 --- a/app/controlplane/pkg/data/ent/ent.go +++ b/app/controlplane/pkg/data/ent/ent.go @@ -34,6 +34,7 @@ import ( "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowcontract" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowcontractversion" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowrun" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowrunevent" ) // ent aliases to avoid import conflicts in user's code. @@ -116,6 +117,7 @@ func checkColumn(t, c string) error { workflowcontract.Table: workflowcontract.ValidColumn, workflowcontractversion.Table: workflowcontractversion.ValidColumn, workflowrun.Table: workflowrun.ValidColumn, + workflowrunevent.Table: workflowrunevent.ValidColumn, }) }) return columnCheck(t, c) diff --git a/app/controlplane/pkg/data/ent/hook/hook.go b/app/controlplane/pkg/data/ent/hook/hook.go index 77a2a0580..c9be7452c 100644 --- a/app/controlplane/pkg/data/ent/hook/hook.go +++ b/app/controlplane/pkg/data/ent/hook/hook.go @@ -273,6 +273,18 @@ func (f WorkflowRunFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.WorkflowRunMutation", m) } +// The WorkflowRunEventFunc type is an adapter to allow the use of ordinary +// function as WorkflowRunEvent mutator. +type WorkflowRunEventFunc func(context.Context, *ent.WorkflowRunEventMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f WorkflowRunEventFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.WorkflowRunEventMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.WorkflowRunEventMutation", m) +} + // Condition is a hook condition function. type Condition func(context.Context, ent.Mutation) bool diff --git a/app/controlplane/pkg/data/ent/migrate/migrations/20261130191056.sql b/app/controlplane/pkg/data/ent/migrate/migrations/20261130191056.sql new file mode 100644 index 000000000..742ec2b29 --- /dev/null +++ b/app/controlplane/pkg/data/ent/migrate/migrations/20261130191056.sql @@ -0,0 +1,20 @@ +-- atlas:txmode none + +-- Create "workflow_run_events" table +CREATE TABLE "workflow_run_events" ( + "id" uuid NOT NULL, + "created_at" timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP, + "source" character varying NOT NULL, + "type" character varying NOT NULL, + "key" character varying NOT NULL, + "status" character varying NOT NULL, + "message" text NULL, + "attributes" jsonb NULL, + "workflow_run_id" uuid NOT NULL, + PRIMARY KEY ("id"), + CONSTRAINT "workflow_run_events_workflow_runs_events" FOREIGN KEY ("workflow_run_id") REFERENCES "workflow_runs" ("id") ON UPDATE NO ACTION ON DELETE CASCADE +); +-- Create index "workflowrunevent_created_at" to table: "workflow_run_events" +CREATE INDEX CONCURRENTLY "workflowrunevent_created_at" ON "workflow_run_events" ("created_at"); +-- Create index "workflowrunevent_workflow_run_id_created_at" to table: "workflow_run_events" +CREATE INDEX CONCURRENTLY "workflowrunevent_workflow_run_id_created_at" ON "workflow_run_events" ("workflow_run_id", "created_at"); diff --git a/app/controlplane/pkg/data/ent/migrate/migrations/atlas.sum b/app/controlplane/pkg/data/ent/migrate/migrations/atlas.sum index 8401847de..5430b58e7 100644 --- a/app/controlplane/pkg/data/ent/migrate/migrations/atlas.sum +++ b/app/controlplane/pkg/data/ent/migrate/migrations/atlas.sum @@ -1,4 +1,4 @@ -h1:TtllQWhorOS3DxgE0OjvSszcMo9xHKTFT1NE1CrtZ30= +h1:NaN66TTuSxozRg1B/ARWWhfUSdFYVFDwoR6dmNaJAwc= 20230706165452_init-schema.sql h1:VvqbNFEQnCvUVyj2iDYVQQxDM0+sSXqocpt/5H64k8M= 20230710111950-cas-backend.sql h1:A8iBuSzZIEbdsv9ipBtscZQuaBp3V5/VMw7eZH6GX+g= 20230712094107-cas-backends-workflow-runs.sql h1:a5rzxpVGyd56nLRSsKrmCFc9sebg65RWzLghKHh5xvI= @@ -148,3 +148,4 @@ h1:TtllQWhorOS3DxgE0OjvSszcMo9xHKTFT1NE1CrtZ30= 20261116124543.sql h1:r+8IOuLFQ3iMrQjYN8hPGxItVJu/bidc0/yeEUe6RFQ= 20261117162118.sql h1:kihy12JzE5ELo0Jy79LjMs8X4BBgmCjsh8Q1kpFp60c= 20261123100446.sql h1:m6G8YK7prIatRFKx10ZE1mL3qkL7W1pAcQm3vDwML24= +20261130191056.sql h1:pIT59TQwRU/ZBsSdBJjSEE4dOjbmclXbLWI4Upt7X+0= diff --git a/app/controlplane/pkg/data/ent/migrate/schema.go b/app/controlplane/pkg/data/ent/migrate/schema.go index 7b6ed3012..54c8eff7f 100644 --- a/app/controlplane/pkg/data/ent/migrate/schema.go +++ b/app/controlplane/pkg/data/ent/migrate/schema.go @@ -996,6 +996,44 @@ var ( }, }, } + // WorkflowRunEventsColumns holds the columns for the "workflow_run_events" table. + WorkflowRunEventsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeUUID, Unique: true}, + {Name: "created_at", Type: field.TypeTime, Default: "CURRENT_TIMESTAMP"}, + {Name: "source", Type: field.TypeEnum, Enums: []string{"cli", "control_plane"}}, + {Name: "type", Type: field.TypeEnum, Enums: []string{"attestation", "material"}}, + {Name: "key", Type: field.TypeString}, + {Name: "status", Type: field.TypeEnum, Enums: []string{"started", "succeeded", "failed", "canceled"}}, + {Name: "message", Type: field.TypeString, Nullable: true, Size: 2147483647}, + {Name: "attributes", Type: field.TypeJSON, Nullable: true}, + {Name: "workflow_run_id", Type: field.TypeUUID}, + } + // WorkflowRunEventsTable holds the schema information for the "workflow_run_events" table. + WorkflowRunEventsTable = &schema.Table{ + Name: "workflow_run_events", + Columns: WorkflowRunEventsColumns, + PrimaryKey: []*schema.Column{WorkflowRunEventsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "workflow_run_events_workflow_runs_events", + Columns: []*schema.Column{WorkflowRunEventsColumns[8]}, + RefColumns: []*schema.Column{WorkflowRunsColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "workflowrunevent_workflow_run_id_created_at", + Unique: false, + Columns: []*schema.Column{WorkflowRunEventsColumns[8], WorkflowRunEventsColumns[1]}, + }, + { + Name: "workflowrunevent_created_at", + Unique: false, + Columns: []*schema.Column{WorkflowRunEventsColumns[1]}, + }, + }, + } // ReferrerWorkflowsColumns holds the columns for the "referrer_workflows" table. ReferrerWorkflowsColumns = []*schema.Column{ {Name: "referrer_id", Type: field.TypeUUID}, @@ -1070,6 +1108,7 @@ var ( WorkflowContractsTable, WorkflowContractVersionsTable, WorkflowRunsTable, + WorkflowRunEventsTable, ReferrerWorkflowsTable, WorkflowRunCasBackendsTable, } @@ -1114,6 +1153,7 @@ func init() { WorkflowRunsTable.ForeignKeys[1].RefTable = ProjectVersionsTable WorkflowRunsTable.ForeignKeys[2].RefTable = WorkflowsTable WorkflowRunsTable.ForeignKeys[3].RefTable = WorkflowContractVersionsTable + WorkflowRunEventsTable.ForeignKeys[0].RefTable = WorkflowRunsTable ReferrerWorkflowsTable.ForeignKeys[0].RefTable = ReferrersTable ReferrerWorkflowsTable.ForeignKeys[1].RefTable = WorkflowsTable WorkflowRunCasBackendsTable.ForeignKeys[0].RefTable = WorkflowRunsTable diff --git a/app/controlplane/pkg/data/ent/mutation.go b/app/controlplane/pkg/data/ent/mutation.go index c60f6e01e..0e13e5d0d 100644 --- a/app/controlplane/pkg/data/ent/mutation.go +++ b/app/controlplane/pkg/data/ent/mutation.go @@ -36,6 +36,7 @@ import ( "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowcontract" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowcontractversion" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowrun" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowrunevent" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/unmarshal" "github.com/google/uuid" "github.com/secure-systems-lab/go-securesystemslib/dsse" @@ -72,6 +73,7 @@ const ( TypeWorkflowContract = "WorkflowContract" TypeWorkflowContractVersion = "WorkflowContractVersion" TypeWorkflowRun = "WorkflowRun" + TypeWorkflowRunEvent = "WorkflowRunEvent" ) // APITokenMutation represents an operation that mutates the APIToken nodes in the graph. @@ -20122,6 +20124,9 @@ type WorkflowRunMutation struct { clearedversion bool attestation_bundle *uuid.UUID clearedattestation_bundle bool + events map[uuid.UUID]struct{} + removedevents map[uuid.UUID]struct{} + clearedevents bool done bool oldValue func(context.Context) (*WorkflowRun, error) predicates []predicate.WorkflowRun @@ -21576,6 +21581,60 @@ func (m *WorkflowRunMutation) ResetAttestationBundle() { m.clearedattestation_bundle = false } +// AddEventIDs adds the "events" edge to the WorkflowRunEvent entity by ids. +func (m *WorkflowRunMutation) AddEventIDs(ids ...uuid.UUID) { + if m.events == nil { + m.events = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.events[ids[i]] = struct{}{} + } +} + +// ClearEvents clears the "events" edge to the WorkflowRunEvent entity. +func (m *WorkflowRunMutation) ClearEvents() { + m.clearedevents = true +} + +// EventsCleared reports if the "events" edge to the WorkflowRunEvent entity was cleared. +func (m *WorkflowRunMutation) EventsCleared() bool { + return m.clearedevents +} + +// RemoveEventIDs removes the "events" edge to the WorkflowRunEvent entity by IDs. +func (m *WorkflowRunMutation) RemoveEventIDs(ids ...uuid.UUID) { + if m.removedevents == nil { + m.removedevents = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.events, ids[i]) + m.removedevents[ids[i]] = struct{}{} + } +} + +// RemovedEvents returns the removed IDs of the "events" edge to the WorkflowRunEvent entity. +func (m *WorkflowRunMutation) RemovedEventsIDs() (ids []uuid.UUID) { + for id := range m.removedevents { + ids = append(ids, id) + } + return +} + +// EventsIDs returns the "events" edge IDs in the mutation. +func (m *WorkflowRunMutation) EventsIDs() (ids []uuid.UUID) { + for id := range m.events { + ids = append(ids, id) + } + return +} + +// ResetEvents resets all changes to the "events" edge. +func (m *WorkflowRunMutation) ResetEvents() { + m.events = nil + m.clearedevents = false + m.removedevents = nil +} + // Where appends a list predicates to the WorkflowRunMutation builder. func (m *WorkflowRunMutation) Where(ps ...predicate.WorkflowRun) { m.predicates = append(m.predicates, ps...) @@ -22246,7 +22305,7 @@ func (m *WorkflowRunMutation) ResetField(name string) error { // AddedEdges returns all edge names that were set/added in this mutation. func (m *WorkflowRunMutation) AddedEdges() []string { - edges := make([]string, 0, 6) + edges := make([]string, 0, 7) if m.workflow != nil { edges = append(edges, workflowrun.EdgeWorkflow) } @@ -22265,6 +22324,9 @@ func (m *WorkflowRunMutation) AddedEdges() []string { if m.attestation_bundle != nil { edges = append(edges, workflowrun.EdgeAttestationBundle) } + if m.events != nil { + edges = append(edges, workflowrun.EdgeEvents) + } return edges } @@ -22298,16 +22360,25 @@ func (m *WorkflowRunMutation) AddedIDs(name string) []ent.Value { if id := m.attestation_bundle; id != nil { return []ent.Value{*id} } + case workflowrun.EdgeEvents: + ids := make([]ent.Value, 0, len(m.events)) + for id := range m.events { + ids = append(ids, id) + } + return ids } return nil } // RemovedEdges returns all edge names that were removed in this mutation. func (m *WorkflowRunMutation) RemovedEdges() []string { - edges := make([]string, 0, 6) + edges := make([]string, 0, 7) if m.removedcas_backends != nil { edges = append(edges, workflowrun.EdgeCasBackends) } + if m.removedevents != nil { + edges = append(edges, workflowrun.EdgeEvents) + } return edges } @@ -22321,13 +22392,19 @@ func (m *WorkflowRunMutation) RemovedIDs(name string) []ent.Value { ids = append(ids, id) } return ids + case workflowrun.EdgeEvents: + ids := make([]ent.Value, 0, len(m.removedevents)) + for id := range m.removedevents { + ids = append(ids, id) + } + return ids } return nil } // ClearedEdges returns all edge names that were cleared in this mutation. func (m *WorkflowRunMutation) ClearedEdges() []string { - edges := make([]string, 0, 6) + edges := make([]string, 0, 7) if m.clearedworkflow { edges = append(edges, workflowrun.EdgeWorkflow) } @@ -22346,6 +22423,9 @@ func (m *WorkflowRunMutation) ClearedEdges() []string { if m.clearedattestation_bundle { edges = append(edges, workflowrun.EdgeAttestationBundle) } + if m.clearedevents { + edges = append(edges, workflowrun.EdgeEvents) + } return edges } @@ -22365,6 +22445,8 @@ func (m *WorkflowRunMutation) EdgeCleared(name string) bool { return m.clearedversion case workflowrun.EdgeAttestationBundle: return m.clearedattestation_bundle + case workflowrun.EdgeEvents: + return m.clearedevents } return false } @@ -22414,6 +22496,814 @@ func (m *WorkflowRunMutation) ResetEdge(name string) error { case workflowrun.EdgeAttestationBundle: m.ResetAttestationBundle() return nil + case workflowrun.EdgeEvents: + m.ResetEvents() + return nil } return fmt.Errorf("unknown WorkflowRun edge %s", name) } + +// WorkflowRunEventMutation represents an operation that mutates the WorkflowRunEvent nodes in the graph. +type WorkflowRunEventMutation struct { + config + op Op + typ string + id *uuid.UUID + created_at *time.Time + source *biz.WorkflowRunEventSource + _type *biz.WorkflowRunEventType + key *string + status *biz.WorkflowRunEventStatus + message *string + attributes **biz.WorkflowRunEventAttributes + clearedFields map[string]struct{} + workflow_run *uuid.UUID + clearedworkflow_run bool + done bool + oldValue func(context.Context) (*WorkflowRunEvent, error) + predicates []predicate.WorkflowRunEvent +} + +var _ ent.Mutation = (*WorkflowRunEventMutation)(nil) + +// workflowruneventOption allows management of the mutation configuration using functional options. +type workflowruneventOption func(*WorkflowRunEventMutation) + +// newWorkflowRunEventMutation creates new mutation for the WorkflowRunEvent entity. +func newWorkflowRunEventMutation(c config, op Op, opts ...workflowruneventOption) *WorkflowRunEventMutation { + m := &WorkflowRunEventMutation{ + config: c, + op: op, + typ: TypeWorkflowRunEvent, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withWorkflowRunEventID sets the ID field of the mutation. +func withWorkflowRunEventID(id uuid.UUID) workflowruneventOption { + return func(m *WorkflowRunEventMutation) { + var ( + err error + once sync.Once + value *WorkflowRunEvent + ) + m.oldValue = func(ctx context.Context) (*WorkflowRunEvent, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().WorkflowRunEvent.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withWorkflowRunEvent sets the old WorkflowRunEvent of the mutation. +func withWorkflowRunEvent(node *WorkflowRunEvent) workflowruneventOption { + return func(m *WorkflowRunEventMutation) { + m.oldValue = func(context.Context) (*WorkflowRunEvent, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m WorkflowRunEventMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m WorkflowRunEventMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of WorkflowRunEvent entities. +func (m *WorkflowRunEventMutation) SetID(id uuid.UUID) { + m.id = &id +} + +// ID returns the ID value in the mutation. Note that the ID is only available +// if it was provided to the builder or after it was returned from the database. +func (m *WorkflowRunEventMutation) ID() (id uuid.UUID, exists bool) { + if m.id == nil { + return + } + return *m.id, true +} + +// IDs queries the database and returns the entity ids that match the mutation's predicate. +// That means, if the mutation is applied within a transaction with an isolation level such +// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated +// or updated by the mutation. +func (m *WorkflowRunEventMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []uuid.UUID{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().WorkflowRunEvent.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetWorkflowRunID sets the "workflow_run_id" field. +func (m *WorkflowRunEventMutation) SetWorkflowRunID(u uuid.UUID) { + m.workflow_run = &u +} + +// WorkflowRunID returns the value of the "workflow_run_id" field in the mutation. +func (m *WorkflowRunEventMutation) WorkflowRunID() (r uuid.UUID, exists bool) { + v := m.workflow_run + if v == nil { + return + } + return *v, true +} + +// OldWorkflowRunID returns the old "workflow_run_id" field's value of the WorkflowRunEvent entity. +// If the WorkflowRunEvent object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *WorkflowRunEventMutation) OldWorkflowRunID(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldWorkflowRunID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldWorkflowRunID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldWorkflowRunID: %w", err) + } + return oldValue.WorkflowRunID, nil +} + +// ResetWorkflowRunID resets all changes to the "workflow_run_id" field. +func (m *WorkflowRunEventMutation) ResetWorkflowRunID() { + m.workflow_run = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *WorkflowRunEventMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *WorkflowRunEventMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return + } + return *v, true +} + +// OldCreatedAt returns the old "created_at" field's value of the WorkflowRunEvent entity. +// If the WorkflowRunEvent object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *WorkflowRunEventMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + } + return oldValue.CreatedAt, nil +} + +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *WorkflowRunEventMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetSource sets the "source" field. +func (m *WorkflowRunEventMutation) SetSource(bres biz.WorkflowRunEventSource) { + m.source = &bres +} + +// Source returns the value of the "source" field in the mutation. +func (m *WorkflowRunEventMutation) Source() (r biz.WorkflowRunEventSource, exists bool) { + v := m.source + if v == nil { + return + } + return *v, true +} + +// OldSource returns the old "source" field's value of the WorkflowRunEvent entity. +// If the WorkflowRunEvent object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *WorkflowRunEventMutation) OldSource(ctx context.Context) (v biz.WorkflowRunEventSource, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSource is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSource requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSource: %w", err) + } + return oldValue.Source, nil +} + +// ResetSource resets all changes to the "source" field. +func (m *WorkflowRunEventMutation) ResetSource() { + m.source = nil +} + +// SetType sets the "type" field. +func (m *WorkflowRunEventMutation) SetType(bret biz.WorkflowRunEventType) { + m._type = &bret +} + +// GetType returns the value of the "type" field in the mutation. +func (m *WorkflowRunEventMutation) GetType() (r biz.WorkflowRunEventType, exists bool) { + v := m._type + if v == nil { + return + } + return *v, true +} + +// OldType returns the old "type" field's value of the WorkflowRunEvent entity. +// If the WorkflowRunEvent object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *WorkflowRunEventMutation) OldType(ctx context.Context) (v biz.WorkflowRunEventType, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldType: %w", err) + } + return oldValue.Type, nil +} + +// ResetType resets all changes to the "type" field. +func (m *WorkflowRunEventMutation) ResetType() { + m._type = nil +} + +// SetKey sets the "key" field. +func (m *WorkflowRunEventMutation) SetKey(s string) { + m.key = &s +} + +// Key returns the value of the "key" field in the mutation. +func (m *WorkflowRunEventMutation) Key() (r string, exists bool) { + v := m.key + if v == nil { + return + } + return *v, true +} + +// OldKey returns the old "key" field's value of the WorkflowRunEvent entity. +// If the WorkflowRunEvent object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *WorkflowRunEventMutation) OldKey(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldKey is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldKey requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldKey: %w", err) + } + return oldValue.Key, nil +} + +// ResetKey resets all changes to the "key" field. +func (m *WorkflowRunEventMutation) ResetKey() { + m.key = nil +} + +// SetStatus sets the "status" field. +func (m *WorkflowRunEventMutation) SetStatus(bres biz.WorkflowRunEventStatus) { + m.status = &bres +} + +// Status returns the value of the "status" field in the mutation. +func (m *WorkflowRunEventMutation) Status() (r biz.WorkflowRunEventStatus, exists bool) { + v := m.status + if v == nil { + return + } + return *v, true +} + +// OldStatus returns the old "status" field's value of the WorkflowRunEvent entity. +// If the WorkflowRunEvent object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *WorkflowRunEventMutation) OldStatus(ctx context.Context) (v biz.WorkflowRunEventStatus, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStatus is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStatus requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStatus: %w", err) + } + return oldValue.Status, nil +} + +// ResetStatus resets all changes to the "status" field. +func (m *WorkflowRunEventMutation) ResetStatus() { + m.status = nil +} + +// SetMessage sets the "message" field. +func (m *WorkflowRunEventMutation) SetMessage(s string) { + m.message = &s +} + +// Message returns the value of the "message" field in the mutation. +func (m *WorkflowRunEventMutation) Message() (r string, exists bool) { + v := m.message + if v == nil { + return + } + return *v, true +} + +// OldMessage returns the old "message" field's value of the WorkflowRunEvent entity. +// If the WorkflowRunEvent object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *WorkflowRunEventMutation) OldMessage(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMessage is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMessage requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMessage: %w", err) + } + return oldValue.Message, nil +} + +// ClearMessage clears the value of the "message" field. +func (m *WorkflowRunEventMutation) ClearMessage() { + m.message = nil + m.clearedFields[workflowrunevent.FieldMessage] = struct{}{} +} + +// MessageCleared returns if the "message" field was cleared in this mutation. +func (m *WorkflowRunEventMutation) MessageCleared() bool { + _, ok := m.clearedFields[workflowrunevent.FieldMessage] + return ok +} + +// ResetMessage resets all changes to the "message" field. +func (m *WorkflowRunEventMutation) ResetMessage() { + m.message = nil + delete(m.clearedFields, workflowrunevent.FieldMessage) +} + +// SetAttributes sets the "attributes" field. +func (m *WorkflowRunEventMutation) SetAttributes(brea *biz.WorkflowRunEventAttributes) { + m.attributes = &brea +} + +// Attributes returns the value of the "attributes" field in the mutation. +func (m *WorkflowRunEventMutation) Attributes() (r *biz.WorkflowRunEventAttributes, exists bool) { + v := m.attributes + if v == nil { + return + } + return *v, true +} + +// OldAttributes returns the old "attributes" field's value of the WorkflowRunEvent entity. +// If the WorkflowRunEvent object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *WorkflowRunEventMutation) OldAttributes(ctx context.Context) (v *biz.WorkflowRunEventAttributes, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAttributes is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAttributes requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAttributes: %w", err) + } + return oldValue.Attributes, nil +} + +// ClearAttributes clears the value of the "attributes" field. +func (m *WorkflowRunEventMutation) ClearAttributes() { + m.attributes = nil + m.clearedFields[workflowrunevent.FieldAttributes] = struct{}{} +} + +// AttributesCleared returns if the "attributes" field was cleared in this mutation. +func (m *WorkflowRunEventMutation) AttributesCleared() bool { + _, ok := m.clearedFields[workflowrunevent.FieldAttributes] + return ok +} + +// ResetAttributes resets all changes to the "attributes" field. +func (m *WorkflowRunEventMutation) ResetAttributes() { + m.attributes = nil + delete(m.clearedFields, workflowrunevent.FieldAttributes) +} + +// ClearWorkflowRun clears the "workflow_run" edge to the WorkflowRun entity. +func (m *WorkflowRunEventMutation) ClearWorkflowRun() { + m.clearedworkflow_run = true + m.clearedFields[workflowrunevent.FieldWorkflowRunID] = struct{}{} +} + +// WorkflowRunCleared reports if the "workflow_run" edge to the WorkflowRun entity was cleared. +func (m *WorkflowRunEventMutation) WorkflowRunCleared() bool { + return m.clearedworkflow_run +} + +// WorkflowRunIDs returns the "workflow_run" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// WorkflowRunID instead. It exists only for internal usage by the builders. +func (m *WorkflowRunEventMutation) WorkflowRunIDs() (ids []uuid.UUID) { + if id := m.workflow_run; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetWorkflowRun resets all changes to the "workflow_run" edge. +func (m *WorkflowRunEventMutation) ResetWorkflowRun() { + m.workflow_run = nil + m.clearedworkflow_run = false +} + +// Where appends a list predicates to the WorkflowRunEventMutation builder. +func (m *WorkflowRunEventMutation) Where(ps ...predicate.WorkflowRunEvent) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the WorkflowRunEventMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *WorkflowRunEventMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.WorkflowRunEvent, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *WorkflowRunEventMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *WorkflowRunEventMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (WorkflowRunEvent). +func (m *WorkflowRunEventMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *WorkflowRunEventMutation) Fields() []string { + fields := make([]string, 0, 8) + if m.workflow_run != nil { + fields = append(fields, workflowrunevent.FieldWorkflowRunID) + } + if m.created_at != nil { + fields = append(fields, workflowrunevent.FieldCreatedAt) + } + if m.source != nil { + fields = append(fields, workflowrunevent.FieldSource) + } + if m._type != nil { + fields = append(fields, workflowrunevent.FieldType) + } + if m.key != nil { + fields = append(fields, workflowrunevent.FieldKey) + } + if m.status != nil { + fields = append(fields, workflowrunevent.FieldStatus) + } + if m.message != nil { + fields = append(fields, workflowrunevent.FieldMessage) + } + if m.attributes != nil { + fields = append(fields, workflowrunevent.FieldAttributes) + } + return fields +} + +// Field returns the value of a field with the given name. The second boolean +// return value indicates that this field was not set, or was not defined in the +// schema. +func (m *WorkflowRunEventMutation) Field(name string) (ent.Value, bool) { + switch name { + case workflowrunevent.FieldWorkflowRunID: + return m.WorkflowRunID() + case workflowrunevent.FieldCreatedAt: + return m.CreatedAt() + case workflowrunevent.FieldSource: + return m.Source() + case workflowrunevent.FieldType: + return m.GetType() + case workflowrunevent.FieldKey: + return m.Key() + case workflowrunevent.FieldStatus: + return m.Status() + case workflowrunevent.FieldMessage: + return m.Message() + case workflowrunevent.FieldAttributes: + return m.Attributes() + } + return nil, false +} + +// OldField returns the old value of the field from the database. An error is +// returned if the mutation operation is not UpdateOne, or the query to the +// database failed. +func (m *WorkflowRunEventMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case workflowrunevent.FieldWorkflowRunID: + return m.OldWorkflowRunID(ctx) + case workflowrunevent.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case workflowrunevent.FieldSource: + return m.OldSource(ctx) + case workflowrunevent.FieldType: + return m.OldType(ctx) + case workflowrunevent.FieldKey: + return m.OldKey(ctx) + case workflowrunevent.FieldStatus: + return m.OldStatus(ctx) + case workflowrunevent.FieldMessage: + return m.OldMessage(ctx) + case workflowrunevent.FieldAttributes: + return m.OldAttributes(ctx) + } + return nil, fmt.Errorf("unknown WorkflowRunEvent field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *WorkflowRunEventMutation) SetField(name string, value ent.Value) error { + switch name { + case workflowrunevent.FieldWorkflowRunID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetWorkflowRunID(v) + return nil + case workflowrunevent.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case workflowrunevent.FieldSource: + v, ok := value.(biz.WorkflowRunEventSource) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSource(v) + return nil + case workflowrunevent.FieldType: + v, ok := value.(biz.WorkflowRunEventType) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetType(v) + return nil + case workflowrunevent.FieldKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetKey(v) + return nil + case workflowrunevent.FieldStatus: + v, ok := value.(biz.WorkflowRunEventStatus) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStatus(v) + return nil + case workflowrunevent.FieldMessage: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMessage(v) + return nil + case workflowrunevent.FieldAttributes: + v, ok := value.(*biz.WorkflowRunEventAttributes) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAttributes(v) + return nil + } + return fmt.Errorf("unknown WorkflowRunEvent field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *WorkflowRunEventMutation) AddedFields() []string { + return nil +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *WorkflowRunEventMutation) AddedField(name string) (ent.Value, bool) { + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *WorkflowRunEventMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown WorkflowRunEvent numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *WorkflowRunEventMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(workflowrunevent.FieldMessage) { + fields = append(fields, workflowrunevent.FieldMessage) + } + if m.FieldCleared(workflowrunevent.FieldAttributes) { + fields = append(fields, workflowrunevent.FieldAttributes) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *WorkflowRunEventMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *WorkflowRunEventMutation) ClearField(name string) error { + switch name { + case workflowrunevent.FieldMessage: + m.ClearMessage() + return nil + case workflowrunevent.FieldAttributes: + m.ClearAttributes() + return nil + } + return fmt.Errorf("unknown WorkflowRunEvent nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *WorkflowRunEventMutation) ResetField(name string) error { + switch name { + case workflowrunevent.FieldWorkflowRunID: + m.ResetWorkflowRunID() + return nil + case workflowrunevent.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case workflowrunevent.FieldSource: + m.ResetSource() + return nil + case workflowrunevent.FieldType: + m.ResetType() + return nil + case workflowrunevent.FieldKey: + m.ResetKey() + return nil + case workflowrunevent.FieldStatus: + m.ResetStatus() + return nil + case workflowrunevent.FieldMessage: + m.ResetMessage() + return nil + case workflowrunevent.FieldAttributes: + m.ResetAttributes() + return nil + } + return fmt.Errorf("unknown WorkflowRunEvent field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *WorkflowRunEventMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.workflow_run != nil { + edges = append(edges, workflowrunevent.EdgeWorkflowRun) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *WorkflowRunEventMutation) AddedIDs(name string) []ent.Value { + switch name { + case workflowrunevent.EdgeWorkflowRun: + if id := m.workflow_run; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *WorkflowRunEventMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *WorkflowRunEventMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *WorkflowRunEventMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedworkflow_run { + edges = append(edges, workflowrunevent.EdgeWorkflowRun) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *WorkflowRunEventMutation) EdgeCleared(name string) bool { + switch name { + case workflowrunevent.EdgeWorkflowRun: + return m.clearedworkflow_run + } + return false +} + +// ClearEdge clears the value of the edge with the given name. It returns an error +// if that edge is not defined in the schema. +func (m *WorkflowRunEventMutation) ClearEdge(name string) error { + switch name { + case workflowrunevent.EdgeWorkflowRun: + m.ClearWorkflowRun() + return nil + } + return fmt.Errorf("unknown WorkflowRunEvent unique edge %s", name) +} + +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *WorkflowRunEventMutation) ResetEdge(name string) error { + switch name { + case workflowrunevent.EdgeWorkflowRun: + m.ResetWorkflowRun() + return nil + } + return fmt.Errorf("unknown WorkflowRunEvent edge %s", name) +} diff --git a/app/controlplane/pkg/data/ent/predicate/predicate.go b/app/controlplane/pkg/data/ent/predicate/predicate.go index c46a3dd0f..0702d4d75 100644 --- a/app/controlplane/pkg/data/ent/predicate/predicate.go +++ b/app/controlplane/pkg/data/ent/predicate/predicate.go @@ -71,3 +71,6 @@ type WorkflowContractVersion func(*sql.Selector) // WorkflowRun is the predicate function for workflowrun builders. type WorkflowRun func(*sql.Selector) + +// WorkflowRunEvent is the predicate function for workflowrunevent builders. +type WorkflowRunEvent func(*sql.Selector) diff --git a/app/controlplane/pkg/data/ent/runtime.go b/app/controlplane/pkg/data/ent/runtime.go index 12642e9dd..ace8400c9 100644 --- a/app/controlplane/pkg/data/ent/runtime.go +++ b/app/controlplane/pkg/data/ent/runtime.go @@ -27,6 +27,7 @@ import ( "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowcontract" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowcontractversion" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowrun" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowrunevent" "github.com/google/uuid" ) @@ -400,4 +401,14 @@ func init() { workflowrunDescID := workflowrunFields[0].Descriptor() // workflowrun.DefaultID holds the default value on creation for the id field. workflowrun.DefaultID = workflowrunDescID.Default.(func() uuid.UUID) + workflowruneventFields := schema.WorkflowRunEvent{}.Fields() + _ = workflowruneventFields + // workflowruneventDescCreatedAt is the schema descriptor for created_at field. + workflowruneventDescCreatedAt := workflowruneventFields[2].Descriptor() + // workflowrunevent.DefaultCreatedAt holds the default value on creation for the created_at field. + workflowrunevent.DefaultCreatedAt = workflowruneventDescCreatedAt.Default.(func() time.Time) + // workflowruneventDescID is the schema descriptor for id field. + workflowruneventDescID := workflowruneventFields[0].Descriptor() + // workflowrunevent.DefaultID holds the default value on creation for the id field. + workflowrunevent.DefaultID = workflowruneventDescID.Default.(func() uuid.UUID) } diff --git a/app/controlplane/pkg/data/ent/schema/workflowrun.go b/app/controlplane/pkg/data/ent/schema/workflowrun.go index 98bbac6ea..dcbd21565 100644 --- a/app/controlplane/pkg/data/ent/schema/workflowrun.go +++ b/app/controlplane/pkg/data/ent/schema/workflowrun.go @@ -98,6 +98,8 @@ func (WorkflowRun) Edges() []ent.Edge { // not required since we have old data edge.From("version", ProjectVersion.Type).Field("version_id").Ref("runs").Unique().Required(), edge.To("attestation_bundle", Attestation.Type).Unique().Annotations(entsql.Annotation{OnDelete: entsql.Cascade}), + // Progress events of the run, deleted with the run + edge.To("events", WorkflowRunEvent.Type).Annotations(entsql.Annotation{OnDelete: entsql.Cascade}), } } diff --git a/app/controlplane/pkg/data/ent/schema/workflowrunevent.go b/app/controlplane/pkg/data/ent/schema/workflowrunevent.go new file mode 100644 index 000000000..f9d9a121f --- /dev/null +++ b/app/controlplane/pkg/data/ent/schema/workflowrunevent.go @@ -0,0 +1,70 @@ +// +// Copyright 2026 The Chainloop Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/biz" + "github.com/google/uuid" +) + +// WorkflowRunEvent holds the progress events of a workflow run. +// They are informational only and never part of the attestation. +type WorkflowRunEvent struct { + ent.Schema +} + +func (WorkflowRunEvent) Fields() []ent.Field { + return []ent.Field{ + field.UUID("id", uuid.UUID{}).Default(uuid.New).Unique(), + field.UUID("workflow_run_id", uuid.UUID{}).Immutable(), + // Set by the control plane when it receives the event + field.Time("created_at"). + Default(time.Now). + Immutable(). + Annotations(&entsql.Annotation{Default: currentTimestamp}), + field.Enum("source").GoType(biz.WorkflowRunEventSource("")).Immutable(), + field.Enum("type").GoType(biz.WorkflowRunEventType("")).Immutable(), + field.String("key").Immutable(), + field.Enum("status").GoType(biz.WorkflowRunEventStatus("")).Immutable(), + field.Text("message").Optional().Immutable(), + field.JSON("attributes", &biz.WorkflowRunEventAttributes{}).Optional().Immutable(), + } +} + +func (WorkflowRunEvent) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("workflow_run", WorkflowRun.Type). + Field("workflow_run_id"). + Ref("events"). + Unique().Required().Immutable(), + } +} + +func (WorkflowRunEvent) Indexes() []ent.Index { + return []ent.Index{ + // Events of a run, oldest first + index.Fields("workflow_run_id", "created_at"), + // Deletion of old events + index.Fields("created_at"), + } +} diff --git a/app/controlplane/pkg/data/ent/tx.go b/app/controlplane/pkg/data/ent/tx.go index 2fca8d2a7..e41b55754 100644 --- a/app/controlplane/pkg/data/ent/tx.go +++ b/app/controlplane/pkg/data/ent/tx.go @@ -56,6 +56,8 @@ type Tx struct { WorkflowContractVersion *WorkflowContractVersionClient // WorkflowRun is the client for interacting with the WorkflowRun builders. WorkflowRun *WorkflowRunClient + // WorkflowRunEvent is the client for interacting with the WorkflowRunEvent builders. + WorkflowRunEvent *WorkflowRunEventClient // lazily loaded. client *Client @@ -209,6 +211,7 @@ func (tx *Tx) init() { tx.WorkflowContract = NewWorkflowContractClient(tx.config) tx.WorkflowContractVersion = NewWorkflowContractVersionClient(tx.config) tx.WorkflowRun = NewWorkflowRunClient(tx.config) + tx.WorkflowRunEvent = NewWorkflowRunEventClient(tx.config) } // txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation. diff --git a/app/controlplane/pkg/data/ent/workflowrun.go b/app/controlplane/pkg/data/ent/workflowrun.go index e67a2a273..b14fe87ba 100644 --- a/app/controlplane/pkg/data/ent/workflowrun.go +++ b/app/controlplane/pkg/data/ent/workflowrun.go @@ -91,9 +91,11 @@ type WorkflowRunEdges struct { Version *ProjectVersion `json:"version,omitempty"` // AttestationBundle holds the value of the attestation_bundle edge. AttestationBundle *Attestation `json:"attestation_bundle,omitempty"` + // Events holds the value of the events edge. + Events []*WorkflowRunEvent `json:"events,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. - loadedTypes [6]bool + loadedTypes [7]bool } // WorkflowOrErr returns the Workflow value or an error if the edge @@ -160,6 +162,15 @@ func (e WorkflowRunEdges) AttestationBundleOrErr() (*Attestation, error) { return nil, &NotLoadedError{edge: "attestation_bundle"} } +// EventsOrErr returns the Events value or an error if the edge +// was not loaded in eager-loading. +func (e WorkflowRunEdges) EventsOrErr() ([]*WorkflowRunEvent, error) { + if e.loadedTypes[6] { + return e.Events, nil + } + return nil, &NotLoadedError{edge: "events"} +} + // scanValues returns the types for scanning values from sql.Rows. func (*WorkflowRun) scanValues(columns []string) ([]any, error) { values := make([]any, len(columns)) @@ -392,6 +403,11 @@ func (_m *WorkflowRun) QueryAttestationBundle() *AttestationQuery { return NewWorkflowRunClient(_m.config).QueryAttestationBundle(_m) } +// QueryEvents queries the "events" edge of the WorkflowRun entity. +func (_m *WorkflowRun) QueryEvents() *WorkflowRunEventQuery { + return NewWorkflowRunClient(_m.config).QueryEvents(_m) +} + // Update returns a builder for updating this WorkflowRun. // Note that you need to call WorkflowRun.Unwrap() before calling this method if this WorkflowRun // was returned from a transaction, and the transaction was committed or rolled back. diff --git a/app/controlplane/pkg/data/ent/workflowrun/where.go b/app/controlplane/pkg/data/ent/workflowrun/where.go index 0fc4add6c..3bca5f641 100644 --- a/app/controlplane/pkg/data/ent/workflowrun/where.go +++ b/app/controlplane/pkg/data/ent/workflowrun/where.go @@ -1230,6 +1230,29 @@ func HasAttestationBundleWith(preds ...predicate.Attestation) predicate.Workflow }) } +// HasEvents applies the HasEdge predicate on the "events" edge. +func HasEvents() predicate.WorkflowRun { + return predicate.WorkflowRun(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, EventsTable, EventsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasEventsWith applies the HasEdge predicate on the "events" edge with a given conditions (other predicates). +func HasEventsWith(preds ...predicate.WorkflowRunEvent) predicate.WorkflowRun { + return predicate.WorkflowRun(func(s *sql.Selector) { + step := newEventsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + // And groups predicates with the AND operator between them. func And(predicates ...predicate.WorkflowRun) predicate.WorkflowRun { return predicate.WorkflowRun(sql.AndPredicates(predicates...)) diff --git a/app/controlplane/pkg/data/ent/workflowrun/workflowrun.go b/app/controlplane/pkg/data/ent/workflowrun/workflowrun.go index 7fa381dda..8e8898d90 100644 --- a/app/controlplane/pkg/data/ent/workflowrun/workflowrun.go +++ b/app/controlplane/pkg/data/ent/workflowrun/workflowrun.go @@ -73,6 +73,8 @@ const ( EdgeVersion = "version" // EdgeAttestationBundle holds the string denoting the attestation_bundle edge name in mutations. EdgeAttestationBundle = "attestation_bundle" + // EdgeEvents holds the string denoting the events edge name in mutations. + EdgeEvents = "events" // Table holds the table name of the workflowrun in the database. Table = "workflow_runs" // WorkflowTable is the table that holds the workflow relation/edge. @@ -115,6 +117,13 @@ const ( AttestationBundleInverseTable = "attestations" // AttestationBundleColumn is the table column denoting the attestation_bundle relation/edge. AttestationBundleColumn = "workflowrun_id" + // EventsTable is the table that holds the events relation/edge. + EventsTable = "workflow_run_events" + // EventsInverseTable is the table name for the WorkflowRunEvent entity. + // It exists in this package in order to avoid circular dependency with the "workflowrunevent" package. + EventsInverseTable = "workflow_run_events" + // EventsColumn is the table column denoting the events relation/edge. + EventsColumn = "workflow_run_id" ) // Columns holds all SQL columns for workflowrun fields. @@ -373,6 +382,20 @@ func ByAttestationBundleField(field string, opts ...sql.OrderTermOption) OrderOp sqlgraph.OrderByNeighborTerms(s, newAttestationBundleStep(), sql.OrderByField(field, opts...)) } } + +// ByEventsCount orders the results by events count. +func ByEventsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newEventsStep(), opts...) + } +} + +// ByEvents orders the results by events terms. +func ByEvents(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newEventsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} func newWorkflowStep() *sqlgraph.Step { return sqlgraph.NewStep( sqlgraph.From(Table, FieldID), @@ -415,3 +438,10 @@ func newAttestationBundleStep() *sqlgraph.Step { sqlgraph.Edge(sqlgraph.O2O, false, AttestationBundleTable, AttestationBundleColumn), ) } +func newEventsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(EventsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, EventsTable, EventsColumn), + ) +} diff --git a/app/controlplane/pkg/data/ent/workflowrun_create.go b/app/controlplane/pkg/data/ent/workflowrun_create.go index d2b1f353f..d2ccd0825 100644 --- a/app/controlplane/pkg/data/ent/workflowrun_create.go +++ b/app/controlplane/pkg/data/ent/workflowrun_create.go @@ -20,6 +20,7 @@ import ( "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflow" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowcontractversion" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowrun" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowrunevent" "github.com/google/uuid" "github.com/secure-systems-lab/go-securesystemslib/dsse" ) @@ -366,6 +367,21 @@ func (_c *WorkflowRunCreate) SetAttestationBundle(v *Attestation) *WorkflowRunCr return _c.SetAttestationBundleID(v.ID) } +// AddEventIDs adds the "events" edge to the WorkflowRunEvent entity by IDs. +func (_c *WorkflowRunCreate) AddEventIDs(ids ...uuid.UUID) *WorkflowRunCreate { + _c.mutation.AddEventIDs(ids...) + return _c +} + +// AddEvents adds the "events" edges to the WorkflowRunEvent entity. +func (_c *WorkflowRunCreate) AddEvents(v ...*WorkflowRunEvent) *WorkflowRunCreate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddEventIDs(ids...) +} + // Mutation returns the WorkflowRunMutation object of the builder. func (_c *WorkflowRunCreate) Mutation() *WorkflowRunMutation { return _c.mutation @@ -669,6 +685,22 @@ func (_c *WorkflowRunCreate) createSpec() (*WorkflowRun, *sqlgraph.CreateSpec) { } _spec.Edges = append(_spec.Edges, edge) } + if nodes := _c.mutation.EventsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: workflowrun.EventsTable, + Columns: []string{workflowrun.EventsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(workflowrunevent.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } return _node, _spec } diff --git a/app/controlplane/pkg/data/ent/workflowrun_query.go b/app/controlplane/pkg/data/ent/workflowrun_query.go index 702e6c368..8ed57e95f 100644 --- a/app/controlplane/pkg/data/ent/workflowrun_query.go +++ b/app/controlplane/pkg/data/ent/workflowrun_query.go @@ -21,6 +21,7 @@ import ( "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflow" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowcontractversion" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowrun" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowrunevent" "github.com/google/uuid" ) @@ -37,6 +38,7 @@ type WorkflowRunQuery struct { withCasBackends *CASBackendQuery withVersion *ProjectVersionQuery withAttestationBundle *AttestationQuery + withEvents *WorkflowRunEventQuery withFKs bool modifiers []func(*sql.Selector) // intermediate query (i.e. traversal path). @@ -207,6 +209,28 @@ func (_q *WorkflowRunQuery) QueryAttestationBundle() *AttestationQuery { return query } +// QueryEvents chains the current query on the "events" edge. +func (_q *WorkflowRunQuery) QueryEvents() *WorkflowRunEventQuery { + query := (&WorkflowRunEventClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(workflowrun.Table, workflowrun.FieldID, selector), + sqlgraph.To(workflowrunevent.Table, workflowrunevent.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, workflowrun.EventsTable, workflowrun.EventsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + // First returns the first WorkflowRun entity from the query. // Returns a *NotFoundError when no WorkflowRun was found. func (_q *WorkflowRunQuery) First(ctx context.Context) (*WorkflowRun, error) { @@ -405,6 +429,7 @@ func (_q *WorkflowRunQuery) Clone() *WorkflowRunQuery { withCasBackends: _q.withCasBackends.Clone(), withVersion: _q.withVersion.Clone(), withAttestationBundle: _q.withAttestationBundle.Clone(), + withEvents: _q.withEvents.Clone(), // clone intermediate query. sql: _q.sql.Clone(), path: _q.path, @@ -478,6 +503,17 @@ func (_q *WorkflowRunQuery) WithAttestationBundle(opts ...func(*AttestationQuery return _q } +// WithEvents tells the query-builder to eager-load the nodes that are connected to +// the "events" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *WorkflowRunQuery) WithEvents(opts ...func(*WorkflowRunEventQuery)) *WorkflowRunQuery { + query := (&WorkflowRunEventClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withEvents = query + return _q +} + // GroupBy is used to group vertices by one or more fields/columns. // It is often used with aggregate functions, like: count, max, mean, min, sum. // @@ -557,13 +593,14 @@ func (_q *WorkflowRunQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]* nodes = []*WorkflowRun{} withFKs = _q.withFKs _spec = _q.querySpec() - loadedTypes = [6]bool{ + loadedTypes = [7]bool{ _q.withWorkflow != nil, _q.withOrganization != nil, _q.withContractVersion != nil, _q.withCasBackends != nil, _q.withVersion != nil, _q.withAttestationBundle != nil, + _q.withEvents != nil, } ) if _q.withContractVersion != nil { @@ -630,6 +667,13 @@ func (_q *WorkflowRunQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]* return nil, err } } + if query := _q.withEvents; query != nil { + if err := _q.loadEvents(ctx, query, nodes, + func(n *WorkflowRun) { n.Edges.Events = []*WorkflowRunEvent{} }, + func(n *WorkflowRun, e *WorkflowRunEvent) { n.Edges.Events = append(n.Edges.Events, e) }); err != nil { + return nil, err + } + } return nodes, nil } @@ -840,6 +884,36 @@ func (_q *WorkflowRunQuery) loadAttestationBundle(ctx context.Context, query *At } return nil } +func (_q *WorkflowRunQuery) loadEvents(ctx context.Context, query *WorkflowRunEventQuery, nodes []*WorkflowRun, init func(*WorkflowRun), assign func(*WorkflowRun, *WorkflowRunEvent)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[uuid.UUID]*WorkflowRun) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(workflowrunevent.FieldWorkflowRunID) + } + query.Where(predicate.WorkflowRunEvent(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(workflowrun.EventsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.WorkflowRunID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "workflow_run_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} func (_q *WorkflowRunQuery) sqlCount(ctx context.Context) (int, error) { _spec := _q.querySpec() diff --git a/app/controlplane/pkg/data/ent/workflowrun_update.go b/app/controlplane/pkg/data/ent/workflowrun_update.go index cfa86cf40..ff932450f 100644 --- a/app/controlplane/pkg/data/ent/workflowrun_update.go +++ b/app/controlplane/pkg/data/ent/workflowrun_update.go @@ -18,6 +18,7 @@ import ( "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/projectversion" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowcontractversion" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowrun" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowrunevent" "github.com/google/uuid" "github.com/secure-systems-lab/go-securesystemslib/dsse" ) @@ -483,6 +484,21 @@ func (_u *WorkflowRunUpdate) SetAttestationBundle(v *Attestation) *WorkflowRunUp return _u.SetAttestationBundleID(v.ID) } +// AddEventIDs adds the "events" edge to the WorkflowRunEvent entity by IDs. +func (_u *WorkflowRunUpdate) AddEventIDs(ids ...uuid.UUID) *WorkflowRunUpdate { + _u.mutation.AddEventIDs(ids...) + return _u +} + +// AddEvents adds the "events" edges to the WorkflowRunEvent entity. +func (_u *WorkflowRunUpdate) AddEvents(v ...*WorkflowRunEvent) *WorkflowRunUpdate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddEventIDs(ids...) +} + // Mutation returns the WorkflowRunMutation object of the builder. func (_u *WorkflowRunUpdate) Mutation() *WorkflowRunMutation { return _u.mutation @@ -527,6 +543,27 @@ func (_u *WorkflowRunUpdate) ClearAttestationBundle() *WorkflowRunUpdate { return _u } +// ClearEvents clears all "events" edges to the WorkflowRunEvent entity. +func (_u *WorkflowRunUpdate) ClearEvents() *WorkflowRunUpdate { + _u.mutation.ClearEvents() + return _u +} + +// RemoveEventIDs removes the "events" edge to WorkflowRunEvent entities by IDs. +func (_u *WorkflowRunUpdate) RemoveEventIDs(ids ...uuid.UUID) *WorkflowRunUpdate { + _u.mutation.RemoveEventIDs(ids...) + return _u +} + +// RemoveEvents removes "events" edges to WorkflowRunEvent entities. +func (_u *WorkflowRunUpdate) RemoveEvents(v ...*WorkflowRunEvent) *WorkflowRunUpdate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveEventIDs(ids...) +} + // Save executes the query and returns the number of nodes affected by the update operation. func (_u *WorkflowRunUpdate) Save(ctx context.Context) (int, error) { return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) @@ -848,6 +885,51 @@ func (_u *WorkflowRunUpdate) sqlSave(ctx context.Context) (_node int, err error) } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if _u.mutation.EventsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: workflowrun.EventsTable, + Columns: []string{workflowrun.EventsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(workflowrunevent.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedEventsIDs(); len(nodes) > 0 && !_u.mutation.EventsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: workflowrun.EventsTable, + Columns: []string{workflowrun.EventsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(workflowrunevent.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.EventsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: workflowrun.EventsTable, + Columns: []string{workflowrun.EventsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(workflowrunevent.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } _spec.AddModifiers(_u.modifiers...) if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { @@ -1317,6 +1399,21 @@ func (_u *WorkflowRunUpdateOne) SetAttestationBundle(v *Attestation) *WorkflowRu return _u.SetAttestationBundleID(v.ID) } +// AddEventIDs adds the "events" edge to the WorkflowRunEvent entity by IDs. +func (_u *WorkflowRunUpdateOne) AddEventIDs(ids ...uuid.UUID) *WorkflowRunUpdateOne { + _u.mutation.AddEventIDs(ids...) + return _u +} + +// AddEvents adds the "events" edges to the WorkflowRunEvent entity. +func (_u *WorkflowRunUpdateOne) AddEvents(v ...*WorkflowRunEvent) *WorkflowRunUpdateOne { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddEventIDs(ids...) +} + // Mutation returns the WorkflowRunMutation object of the builder. func (_u *WorkflowRunUpdateOne) Mutation() *WorkflowRunMutation { return _u.mutation @@ -1361,6 +1458,27 @@ func (_u *WorkflowRunUpdateOne) ClearAttestationBundle() *WorkflowRunUpdateOne { return _u } +// ClearEvents clears all "events" edges to the WorkflowRunEvent entity. +func (_u *WorkflowRunUpdateOne) ClearEvents() *WorkflowRunUpdateOne { + _u.mutation.ClearEvents() + return _u +} + +// RemoveEventIDs removes the "events" edge to WorkflowRunEvent entities by IDs. +func (_u *WorkflowRunUpdateOne) RemoveEventIDs(ids ...uuid.UUID) *WorkflowRunUpdateOne { + _u.mutation.RemoveEventIDs(ids...) + return _u +} + +// RemoveEvents removes "events" edges to WorkflowRunEvent entities. +func (_u *WorkflowRunUpdateOne) RemoveEvents(v ...*WorkflowRunEvent) *WorkflowRunUpdateOne { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveEventIDs(ids...) +} + // Where appends a list predicates to the WorkflowRunUpdate builder. func (_u *WorkflowRunUpdateOne) Where(ps ...predicate.WorkflowRun) *WorkflowRunUpdateOne { _u.mutation.Where(ps...) @@ -1712,6 +1830,51 @@ func (_u *WorkflowRunUpdateOne) sqlSave(ctx context.Context) (_node *WorkflowRun } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if _u.mutation.EventsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: workflowrun.EventsTable, + Columns: []string{workflowrun.EventsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(workflowrunevent.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedEventsIDs(); len(nodes) > 0 && !_u.mutation.EventsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: workflowrun.EventsTable, + Columns: []string{workflowrun.EventsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(workflowrunevent.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.EventsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: workflowrun.EventsTable, + Columns: []string{workflowrun.EventsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(workflowrunevent.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } _spec.AddModifiers(_u.modifiers...) _node = &WorkflowRun{config: _u.config} _spec.Assign = _node.assignValues diff --git a/app/controlplane/pkg/data/ent/workflowrunevent.go b/app/controlplane/pkg/data/ent/workflowrunevent.go new file mode 100644 index 000000000..1de2eb8fa --- /dev/null +++ b/app/controlplane/pkg/data/ent/workflowrunevent.go @@ -0,0 +1,219 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "encoding/json" + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/biz" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowrun" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowrunevent" + "github.com/google/uuid" +) + +// WorkflowRunEvent is the model entity for the WorkflowRunEvent schema. +type WorkflowRunEvent struct { + config `json:"-"` + // ID of the ent. + ID uuid.UUID `json:"id,omitempty"` + // WorkflowRunID holds the value of the "workflow_run_id" field. + WorkflowRunID uuid.UUID `json:"workflow_run_id,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // Source holds the value of the "source" field. + Source biz.WorkflowRunEventSource `json:"source,omitempty"` + // Type holds the value of the "type" field. + Type biz.WorkflowRunEventType `json:"type,omitempty"` + // Key holds the value of the "key" field. + Key string `json:"key,omitempty"` + // Status holds the value of the "status" field. + Status biz.WorkflowRunEventStatus `json:"status,omitempty"` + // Message holds the value of the "message" field. + Message string `json:"message,omitempty"` + // Attributes holds the value of the "attributes" field. + Attributes *biz.WorkflowRunEventAttributes `json:"attributes,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the WorkflowRunEventQuery when eager-loading is set. + Edges WorkflowRunEventEdges `json:"edges"` + selectValues sql.SelectValues +} + +// WorkflowRunEventEdges holds the relations/edges for other nodes in the graph. +type WorkflowRunEventEdges struct { + // WorkflowRun holds the value of the workflow_run edge. + WorkflowRun *WorkflowRun `json:"workflow_run,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// WorkflowRunOrErr returns the WorkflowRun value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e WorkflowRunEventEdges) WorkflowRunOrErr() (*WorkflowRun, error) { + if e.WorkflowRun != nil { + return e.WorkflowRun, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: workflowrun.Label} + } + return nil, &NotLoadedError{edge: "workflow_run"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*WorkflowRunEvent) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case workflowrunevent.FieldAttributes: + values[i] = new([]byte) + case workflowrunevent.FieldSource, workflowrunevent.FieldType, workflowrunevent.FieldKey, workflowrunevent.FieldStatus, workflowrunevent.FieldMessage: + values[i] = new(sql.NullString) + case workflowrunevent.FieldCreatedAt: + values[i] = new(sql.NullTime) + case workflowrunevent.FieldID, workflowrunevent.FieldWorkflowRunID: + values[i] = new(uuid.UUID) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the WorkflowRunEvent fields. +func (_m *WorkflowRunEvent) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case workflowrunevent.FieldID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value != nil { + _m.ID = *value + } + case workflowrunevent.FieldWorkflowRunID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field workflow_run_id", values[i]) + } else if value != nil { + _m.WorkflowRunID = *value + } + case workflowrunevent.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + _m.CreatedAt = value.Time + } + case workflowrunevent.FieldSource: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field source", values[i]) + } else if value.Valid { + _m.Source = biz.WorkflowRunEventSource(value.String) + } + case workflowrunevent.FieldType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field type", values[i]) + } else if value.Valid { + _m.Type = biz.WorkflowRunEventType(value.String) + } + case workflowrunevent.FieldKey: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field key", values[i]) + } else if value.Valid { + _m.Key = value.String + } + case workflowrunevent.FieldStatus: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field status", values[i]) + } else if value.Valid { + _m.Status = biz.WorkflowRunEventStatus(value.String) + } + case workflowrunevent.FieldMessage: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field message", values[i]) + } else if value.Valid { + _m.Message = value.String + } + case workflowrunevent.FieldAttributes: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field attributes", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.Attributes); err != nil { + return fmt.Errorf("unmarshal field attributes: %w", err) + } + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the WorkflowRunEvent. +// This includes values selected through modifiers, order, etc. +func (_m *WorkflowRunEvent) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryWorkflowRun queries the "workflow_run" edge of the WorkflowRunEvent entity. +func (_m *WorkflowRunEvent) QueryWorkflowRun() *WorkflowRunQuery { + return NewWorkflowRunEventClient(_m.config).QueryWorkflowRun(_m) +} + +// Update returns a builder for updating this WorkflowRunEvent. +// Note that you need to call WorkflowRunEvent.Unwrap() before calling this method if this WorkflowRunEvent +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *WorkflowRunEvent) Update() *WorkflowRunEventUpdateOne { + return NewWorkflowRunEventClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the WorkflowRunEvent entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *WorkflowRunEvent) Unwrap() *WorkflowRunEvent { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("ent: WorkflowRunEvent is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *WorkflowRunEvent) String() string { + var builder strings.Builder + builder.WriteString("WorkflowRunEvent(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("workflow_run_id=") + builder.WriteString(fmt.Sprintf("%v", _m.WorkflowRunID)) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("source=") + builder.WriteString(fmt.Sprintf("%v", _m.Source)) + builder.WriteString(", ") + builder.WriteString("type=") + builder.WriteString(fmt.Sprintf("%v", _m.Type)) + builder.WriteString(", ") + builder.WriteString("key=") + builder.WriteString(_m.Key) + builder.WriteString(", ") + builder.WriteString("status=") + builder.WriteString(fmt.Sprintf("%v", _m.Status)) + builder.WriteString(", ") + builder.WriteString("message=") + builder.WriteString(_m.Message) + builder.WriteString(", ") + builder.WriteString("attributes=") + builder.WriteString(fmt.Sprintf("%v", _m.Attributes)) + builder.WriteByte(')') + return builder.String() +} + +// WorkflowRunEvents is a parsable slice of WorkflowRunEvent. +type WorkflowRunEvents []*WorkflowRunEvent diff --git a/app/controlplane/pkg/data/ent/workflowrunevent/where.go b/app/controlplane/pkg/data/ent/workflowrunevent/where.go new file mode 100644 index 000000000..46df94d45 --- /dev/null +++ b/app/controlplane/pkg/data/ent/workflowrunevent/where.go @@ -0,0 +1,416 @@ +// Code generated by ent, DO NOT EDIT. + +package workflowrunevent + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/biz" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/predicate" + "github.com/google/uuid" +) + +// ID filters vertices based on their ID field. +func ID(id uuid.UUID) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id uuid.UUID) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id uuid.UUID) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...uuid.UUID) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...uuid.UUID) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id uuid.UUID) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id uuid.UUID) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id uuid.UUID) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id uuid.UUID) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldLTE(FieldID, id)) +} + +// WorkflowRunID applies equality check predicate on the "workflow_run_id" field. It's identical to WorkflowRunIDEQ. +func WorkflowRunID(v uuid.UUID) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldEQ(FieldWorkflowRunID, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldEQ(FieldCreatedAt, v)) +} + +// Key applies equality check predicate on the "key" field. It's identical to KeyEQ. +func Key(v string) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldEQ(FieldKey, v)) +} + +// Message applies equality check predicate on the "message" field. It's identical to MessageEQ. +func Message(v string) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldEQ(FieldMessage, v)) +} + +// WorkflowRunIDEQ applies the EQ predicate on the "workflow_run_id" field. +func WorkflowRunIDEQ(v uuid.UUID) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldEQ(FieldWorkflowRunID, v)) +} + +// WorkflowRunIDNEQ applies the NEQ predicate on the "workflow_run_id" field. +func WorkflowRunIDNEQ(v uuid.UUID) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldNEQ(FieldWorkflowRunID, v)) +} + +// WorkflowRunIDIn applies the In predicate on the "workflow_run_id" field. +func WorkflowRunIDIn(vs ...uuid.UUID) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldIn(FieldWorkflowRunID, vs...)) +} + +// WorkflowRunIDNotIn applies the NotIn predicate on the "workflow_run_id" field. +func WorkflowRunIDNotIn(vs ...uuid.UUID) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldNotIn(FieldWorkflowRunID, vs...)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldLTE(FieldCreatedAt, v)) +} + +// SourceEQ applies the EQ predicate on the "source" field. +func SourceEQ(v biz.WorkflowRunEventSource) predicate.WorkflowRunEvent { + vc := v + return predicate.WorkflowRunEvent(sql.FieldEQ(FieldSource, vc)) +} + +// SourceNEQ applies the NEQ predicate on the "source" field. +func SourceNEQ(v biz.WorkflowRunEventSource) predicate.WorkflowRunEvent { + vc := v + return predicate.WorkflowRunEvent(sql.FieldNEQ(FieldSource, vc)) +} + +// SourceIn applies the In predicate on the "source" field. +func SourceIn(vs ...biz.WorkflowRunEventSource) predicate.WorkflowRunEvent { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.WorkflowRunEvent(sql.FieldIn(FieldSource, v...)) +} + +// SourceNotIn applies the NotIn predicate on the "source" field. +func SourceNotIn(vs ...biz.WorkflowRunEventSource) predicate.WorkflowRunEvent { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.WorkflowRunEvent(sql.FieldNotIn(FieldSource, v...)) +} + +// TypeEQ applies the EQ predicate on the "type" field. +func TypeEQ(v biz.WorkflowRunEventType) predicate.WorkflowRunEvent { + vc := v + return predicate.WorkflowRunEvent(sql.FieldEQ(FieldType, vc)) +} + +// TypeNEQ applies the NEQ predicate on the "type" field. +func TypeNEQ(v biz.WorkflowRunEventType) predicate.WorkflowRunEvent { + vc := v + return predicate.WorkflowRunEvent(sql.FieldNEQ(FieldType, vc)) +} + +// TypeIn applies the In predicate on the "type" field. +func TypeIn(vs ...biz.WorkflowRunEventType) predicate.WorkflowRunEvent { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.WorkflowRunEvent(sql.FieldIn(FieldType, v...)) +} + +// TypeNotIn applies the NotIn predicate on the "type" field. +func TypeNotIn(vs ...biz.WorkflowRunEventType) predicate.WorkflowRunEvent { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.WorkflowRunEvent(sql.FieldNotIn(FieldType, v...)) +} + +// KeyEQ applies the EQ predicate on the "key" field. +func KeyEQ(v string) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldEQ(FieldKey, v)) +} + +// KeyNEQ applies the NEQ predicate on the "key" field. +func KeyNEQ(v string) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldNEQ(FieldKey, v)) +} + +// KeyIn applies the In predicate on the "key" field. +func KeyIn(vs ...string) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldIn(FieldKey, vs...)) +} + +// KeyNotIn applies the NotIn predicate on the "key" field. +func KeyNotIn(vs ...string) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldNotIn(FieldKey, vs...)) +} + +// KeyGT applies the GT predicate on the "key" field. +func KeyGT(v string) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldGT(FieldKey, v)) +} + +// KeyGTE applies the GTE predicate on the "key" field. +func KeyGTE(v string) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldGTE(FieldKey, v)) +} + +// KeyLT applies the LT predicate on the "key" field. +func KeyLT(v string) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldLT(FieldKey, v)) +} + +// KeyLTE applies the LTE predicate on the "key" field. +func KeyLTE(v string) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldLTE(FieldKey, v)) +} + +// KeyContains applies the Contains predicate on the "key" field. +func KeyContains(v string) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldContains(FieldKey, v)) +} + +// KeyHasPrefix applies the HasPrefix predicate on the "key" field. +func KeyHasPrefix(v string) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldHasPrefix(FieldKey, v)) +} + +// KeyHasSuffix applies the HasSuffix predicate on the "key" field. +func KeyHasSuffix(v string) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldHasSuffix(FieldKey, v)) +} + +// KeyEqualFold applies the EqualFold predicate on the "key" field. +func KeyEqualFold(v string) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldEqualFold(FieldKey, v)) +} + +// KeyContainsFold applies the ContainsFold predicate on the "key" field. +func KeyContainsFold(v string) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldContainsFold(FieldKey, v)) +} + +// StatusEQ applies the EQ predicate on the "status" field. +func StatusEQ(v biz.WorkflowRunEventStatus) predicate.WorkflowRunEvent { + vc := v + return predicate.WorkflowRunEvent(sql.FieldEQ(FieldStatus, vc)) +} + +// StatusNEQ applies the NEQ predicate on the "status" field. +func StatusNEQ(v biz.WorkflowRunEventStatus) predicate.WorkflowRunEvent { + vc := v + return predicate.WorkflowRunEvent(sql.FieldNEQ(FieldStatus, vc)) +} + +// StatusIn applies the In predicate on the "status" field. +func StatusIn(vs ...biz.WorkflowRunEventStatus) predicate.WorkflowRunEvent { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.WorkflowRunEvent(sql.FieldIn(FieldStatus, v...)) +} + +// StatusNotIn applies the NotIn predicate on the "status" field. +func StatusNotIn(vs ...biz.WorkflowRunEventStatus) predicate.WorkflowRunEvent { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.WorkflowRunEvent(sql.FieldNotIn(FieldStatus, v...)) +} + +// MessageEQ applies the EQ predicate on the "message" field. +func MessageEQ(v string) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldEQ(FieldMessage, v)) +} + +// MessageNEQ applies the NEQ predicate on the "message" field. +func MessageNEQ(v string) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldNEQ(FieldMessage, v)) +} + +// MessageIn applies the In predicate on the "message" field. +func MessageIn(vs ...string) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldIn(FieldMessage, vs...)) +} + +// MessageNotIn applies the NotIn predicate on the "message" field. +func MessageNotIn(vs ...string) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldNotIn(FieldMessage, vs...)) +} + +// MessageGT applies the GT predicate on the "message" field. +func MessageGT(v string) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldGT(FieldMessage, v)) +} + +// MessageGTE applies the GTE predicate on the "message" field. +func MessageGTE(v string) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldGTE(FieldMessage, v)) +} + +// MessageLT applies the LT predicate on the "message" field. +func MessageLT(v string) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldLT(FieldMessage, v)) +} + +// MessageLTE applies the LTE predicate on the "message" field. +func MessageLTE(v string) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldLTE(FieldMessage, v)) +} + +// MessageContains applies the Contains predicate on the "message" field. +func MessageContains(v string) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldContains(FieldMessage, v)) +} + +// MessageHasPrefix applies the HasPrefix predicate on the "message" field. +func MessageHasPrefix(v string) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldHasPrefix(FieldMessage, v)) +} + +// MessageHasSuffix applies the HasSuffix predicate on the "message" field. +func MessageHasSuffix(v string) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldHasSuffix(FieldMessage, v)) +} + +// MessageIsNil applies the IsNil predicate on the "message" field. +func MessageIsNil() predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldIsNull(FieldMessage)) +} + +// MessageNotNil applies the NotNil predicate on the "message" field. +func MessageNotNil() predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldNotNull(FieldMessage)) +} + +// MessageEqualFold applies the EqualFold predicate on the "message" field. +func MessageEqualFold(v string) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldEqualFold(FieldMessage, v)) +} + +// MessageContainsFold applies the ContainsFold predicate on the "message" field. +func MessageContainsFold(v string) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldContainsFold(FieldMessage, v)) +} + +// AttributesIsNil applies the IsNil predicate on the "attributes" field. +func AttributesIsNil() predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldIsNull(FieldAttributes)) +} + +// AttributesNotNil applies the NotNil predicate on the "attributes" field. +func AttributesNotNil() predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.FieldNotNull(FieldAttributes)) +} + +// HasWorkflowRun applies the HasEdge predicate on the "workflow_run" edge. +func HasWorkflowRun() predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, WorkflowRunTable, WorkflowRunColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasWorkflowRunWith applies the HasEdge predicate on the "workflow_run" edge with a given conditions (other predicates). +func HasWorkflowRunWith(preds ...predicate.WorkflowRun) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(func(s *sql.Selector) { + step := newWorkflowRunStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.WorkflowRunEvent) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.WorkflowRunEvent) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.WorkflowRunEvent) predicate.WorkflowRunEvent { + return predicate.WorkflowRunEvent(sql.NotPredicates(p)) +} diff --git a/app/controlplane/pkg/data/ent/workflowrunevent/workflowrunevent.go b/app/controlplane/pkg/data/ent/workflowrunevent/workflowrunevent.go new file mode 100644 index 000000000..d6848ea54 --- /dev/null +++ b/app/controlplane/pkg/data/ent/workflowrunevent/workflowrunevent.go @@ -0,0 +1,164 @@ +// Code generated by ent, DO NOT EDIT. + +package workflowrunevent + +import ( + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/biz" + "github.com/google/uuid" +) + +const ( + // Label holds the string label denoting the workflowrunevent type in the database. + Label = "workflow_run_event" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldWorkflowRunID holds the string denoting the workflow_run_id field in the database. + FieldWorkflowRunID = "workflow_run_id" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // FieldSource holds the string denoting the source field in the database. + FieldSource = "source" + // FieldType holds the string denoting the type field in the database. + FieldType = "type" + // FieldKey holds the string denoting the key field in the database. + FieldKey = "key" + // FieldStatus holds the string denoting the status field in the database. + FieldStatus = "status" + // FieldMessage holds the string denoting the message field in the database. + FieldMessage = "message" + // FieldAttributes holds the string denoting the attributes field in the database. + FieldAttributes = "attributes" + // EdgeWorkflowRun holds the string denoting the workflow_run edge name in mutations. + EdgeWorkflowRun = "workflow_run" + // Table holds the table name of the workflowrunevent in the database. + Table = "workflow_run_events" + // WorkflowRunTable is the table that holds the workflow_run relation/edge. + WorkflowRunTable = "workflow_run_events" + // WorkflowRunInverseTable is the table name for the WorkflowRun entity. + // It exists in this package in order to avoid circular dependency with the "workflowrun" package. + WorkflowRunInverseTable = "workflow_runs" + // WorkflowRunColumn is the table column denoting the workflow_run relation/edge. + WorkflowRunColumn = "workflow_run_id" +) + +// Columns holds all SQL columns for workflowrunevent fields. +var Columns = []string{ + FieldID, + FieldWorkflowRunID, + FieldCreatedAt, + FieldSource, + FieldType, + FieldKey, + FieldStatus, + FieldMessage, + FieldAttributes, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() uuid.UUID +) + +// SourceValidator is a validator for the "source" field enum values. It is called by the builders before save. +func SourceValidator(s biz.WorkflowRunEventSource) error { + switch s { + case "cli", "control_plane": + return nil + default: + return fmt.Errorf("workflowrunevent: invalid enum value for source field: %q", s) + } +} + +// TypeValidator is a validator for the "type" field enum values. It is called by the builders before save. +func TypeValidator(_type biz.WorkflowRunEventType) error { + switch _type { + case "attestation", "material": + return nil + default: + return fmt.Errorf("workflowrunevent: invalid enum value for type field: %q", _type) + } +} + +// StatusValidator is a validator for the "status" field enum values. It is called by the builders before save. +func StatusValidator(s biz.WorkflowRunEventStatus) error { + switch s { + case "started", "succeeded", "failed", "canceled": + return nil + default: + return fmt.Errorf("workflowrunevent: invalid enum value for status field: %q", s) + } +} + +// OrderOption defines the ordering options for the WorkflowRunEvent queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByWorkflowRunID orders the results by the workflow_run_id field. +func ByWorkflowRunID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldWorkflowRunID, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// BySource orders the results by the source field. +func BySource(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSource, opts...).ToFunc() +} + +// ByType orders the results by the type field. +func ByType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldType, opts...).ToFunc() +} + +// ByKey orders the results by the key field. +func ByKey(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldKey, opts...).ToFunc() +} + +// ByStatus orders the results by the status field. +func ByStatus(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldStatus, opts...).ToFunc() +} + +// ByMessage orders the results by the message field. +func ByMessage(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldMessage, opts...).ToFunc() +} + +// ByWorkflowRunField orders the results by workflow_run field. +func ByWorkflowRunField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newWorkflowRunStep(), sql.OrderByField(field, opts...)) + } +} +func newWorkflowRunStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(WorkflowRunInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, WorkflowRunTable, WorkflowRunColumn), + ) +} diff --git a/app/controlplane/pkg/data/ent/workflowrunevent_create.go b/app/controlplane/pkg/data/ent/workflowrunevent_create.go new file mode 100644 index 000000000..40abf1e2f --- /dev/null +++ b/app/controlplane/pkg/data/ent/workflowrunevent_create.go @@ -0,0 +1,660 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/biz" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowrun" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowrunevent" + "github.com/google/uuid" +) + +// WorkflowRunEventCreate is the builder for creating a WorkflowRunEvent entity. +type WorkflowRunEventCreate struct { + config + mutation *WorkflowRunEventMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetWorkflowRunID sets the "workflow_run_id" field. +func (_c *WorkflowRunEventCreate) SetWorkflowRunID(v uuid.UUID) *WorkflowRunEventCreate { + _c.mutation.SetWorkflowRunID(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *WorkflowRunEventCreate) SetCreatedAt(v time.Time) *WorkflowRunEventCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *WorkflowRunEventCreate) SetNillableCreatedAt(v *time.Time) *WorkflowRunEventCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetSource sets the "source" field. +func (_c *WorkflowRunEventCreate) SetSource(v biz.WorkflowRunEventSource) *WorkflowRunEventCreate { + _c.mutation.SetSource(v) + return _c +} + +// SetType sets the "type" field. +func (_c *WorkflowRunEventCreate) SetType(v biz.WorkflowRunEventType) *WorkflowRunEventCreate { + _c.mutation.SetType(v) + return _c +} + +// SetKey sets the "key" field. +func (_c *WorkflowRunEventCreate) SetKey(v string) *WorkflowRunEventCreate { + _c.mutation.SetKey(v) + return _c +} + +// SetStatus sets the "status" field. +func (_c *WorkflowRunEventCreate) SetStatus(v biz.WorkflowRunEventStatus) *WorkflowRunEventCreate { + _c.mutation.SetStatus(v) + return _c +} + +// SetMessage sets the "message" field. +func (_c *WorkflowRunEventCreate) SetMessage(v string) *WorkflowRunEventCreate { + _c.mutation.SetMessage(v) + return _c +} + +// SetNillableMessage sets the "message" field if the given value is not nil. +func (_c *WorkflowRunEventCreate) SetNillableMessage(v *string) *WorkflowRunEventCreate { + if v != nil { + _c.SetMessage(*v) + } + return _c +} + +// SetAttributes sets the "attributes" field. +func (_c *WorkflowRunEventCreate) SetAttributes(v *biz.WorkflowRunEventAttributes) *WorkflowRunEventCreate { + _c.mutation.SetAttributes(v) + return _c +} + +// SetID sets the "id" field. +func (_c *WorkflowRunEventCreate) SetID(v uuid.UUID) *WorkflowRunEventCreate { + _c.mutation.SetID(v) + return _c +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (_c *WorkflowRunEventCreate) SetNillableID(v *uuid.UUID) *WorkflowRunEventCreate { + if v != nil { + _c.SetID(*v) + } + return _c +} + +// SetWorkflowRun sets the "workflow_run" edge to the WorkflowRun entity. +func (_c *WorkflowRunEventCreate) SetWorkflowRun(v *WorkflowRun) *WorkflowRunEventCreate { + return _c.SetWorkflowRunID(v.ID) +} + +// Mutation returns the WorkflowRunEventMutation object of the builder. +func (_c *WorkflowRunEventCreate) Mutation() *WorkflowRunEventMutation { + return _c.mutation +} + +// Save creates the WorkflowRunEvent in the database. +func (_c *WorkflowRunEventCreate) Save(ctx context.Context) (*WorkflowRunEvent, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *WorkflowRunEventCreate) SaveX(ctx context.Context) *WorkflowRunEvent { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *WorkflowRunEventCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *WorkflowRunEventCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *WorkflowRunEventCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := workflowrunevent.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.ID(); !ok { + v := workflowrunevent.DefaultID() + _c.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *WorkflowRunEventCreate) check() error { + if _, ok := _c.mutation.WorkflowRunID(); !ok { + return &ValidationError{Name: "workflow_run_id", err: errors.New(`ent: missing required field "WorkflowRunEvent.workflow_run_id"`)} + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "WorkflowRunEvent.created_at"`)} + } + if _, ok := _c.mutation.Source(); !ok { + return &ValidationError{Name: "source", err: errors.New(`ent: missing required field "WorkflowRunEvent.source"`)} + } + if v, ok := _c.mutation.Source(); ok { + if err := workflowrunevent.SourceValidator(v); err != nil { + return &ValidationError{Name: "source", err: fmt.Errorf(`ent: validator failed for field "WorkflowRunEvent.source": %w`, err)} + } + } + if _, ok := _c.mutation.GetType(); !ok { + return &ValidationError{Name: "type", err: errors.New(`ent: missing required field "WorkflowRunEvent.type"`)} + } + if v, ok := _c.mutation.GetType(); ok { + if err := workflowrunevent.TypeValidator(v); err != nil { + return &ValidationError{Name: "type", err: fmt.Errorf(`ent: validator failed for field "WorkflowRunEvent.type": %w`, err)} + } + } + if _, ok := _c.mutation.Key(); !ok { + return &ValidationError{Name: "key", err: errors.New(`ent: missing required field "WorkflowRunEvent.key"`)} + } + if _, ok := _c.mutation.Status(); !ok { + return &ValidationError{Name: "status", err: errors.New(`ent: missing required field "WorkflowRunEvent.status"`)} + } + if v, ok := _c.mutation.Status(); ok { + if err := workflowrunevent.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "WorkflowRunEvent.status": %w`, err)} + } + } + if len(_c.mutation.WorkflowRunIDs()) == 0 { + return &ValidationError{Name: "workflow_run", err: errors.New(`ent: missing required edge "WorkflowRunEvent.workflow_run"`)} + } + return nil +} + +func (_c *WorkflowRunEventCreate) sqlSave(ctx context.Context) (*WorkflowRunEvent, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != nil { + if id, ok := _spec.ID.Value.(*uuid.UUID); ok { + _node.ID = *id + } else if err := _node.ID.Scan(_spec.ID.Value); err != nil { + return nil, err + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *WorkflowRunEventCreate) createSpec() (*WorkflowRunEvent, *sqlgraph.CreateSpec) { + var ( + _node = &WorkflowRunEvent{config: _c.config} + _spec = sqlgraph.NewCreateSpec(workflowrunevent.Table, sqlgraph.NewFieldSpec(workflowrunevent.FieldID, field.TypeUUID)) + ) + _spec.OnConflict = _c.conflict + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(workflowrunevent.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.Source(); ok { + _spec.SetField(workflowrunevent.FieldSource, field.TypeEnum, value) + _node.Source = value + } + if value, ok := _c.mutation.GetType(); ok { + _spec.SetField(workflowrunevent.FieldType, field.TypeEnum, value) + _node.Type = value + } + if value, ok := _c.mutation.Key(); ok { + _spec.SetField(workflowrunevent.FieldKey, field.TypeString, value) + _node.Key = value + } + if value, ok := _c.mutation.Status(); ok { + _spec.SetField(workflowrunevent.FieldStatus, field.TypeEnum, value) + _node.Status = value + } + if value, ok := _c.mutation.Message(); ok { + _spec.SetField(workflowrunevent.FieldMessage, field.TypeString, value) + _node.Message = value + } + if value, ok := _c.mutation.Attributes(); ok { + _spec.SetField(workflowrunevent.FieldAttributes, field.TypeJSON, value) + _node.Attributes = value + } + if nodes := _c.mutation.WorkflowRunIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: workflowrunevent.WorkflowRunTable, + Columns: []string{workflowrunevent.WorkflowRunColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(workflowrun.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.WorkflowRunID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.WorkflowRunEvent.Create(). +// SetWorkflowRunID(v). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.WorkflowRunEventUpsert) { +// SetWorkflowRunID(v+v). +// }). +// Exec(ctx) +func (_c *WorkflowRunEventCreate) OnConflict(opts ...sql.ConflictOption) *WorkflowRunEventUpsertOne { + _c.conflict = opts + return &WorkflowRunEventUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.WorkflowRunEvent.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *WorkflowRunEventCreate) OnConflictColumns(columns ...string) *WorkflowRunEventUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &WorkflowRunEventUpsertOne{ + create: _c, + } +} + +type ( + // WorkflowRunEventUpsertOne is the builder for "upsert"-ing + // one WorkflowRunEvent node. + WorkflowRunEventUpsertOne struct { + create *WorkflowRunEventCreate + } + + // WorkflowRunEventUpsert is the "OnConflict" setter. + WorkflowRunEventUpsert struct { + *sql.UpdateSet + } +) + +// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. +// Using this option is equivalent to using: +// +// client.WorkflowRunEvent.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(workflowrunevent.FieldID) +// }), +// ). +// Exec(ctx) +func (u *WorkflowRunEventUpsertOne) UpdateNewValues() *WorkflowRunEventUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + if _, exists := u.create.mutation.ID(); exists { + s.SetIgnore(workflowrunevent.FieldID) + } + if _, exists := u.create.mutation.WorkflowRunID(); exists { + s.SetIgnore(workflowrunevent.FieldWorkflowRunID) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(workflowrunevent.FieldCreatedAt) + } + if _, exists := u.create.mutation.Source(); exists { + s.SetIgnore(workflowrunevent.FieldSource) + } + if _, exists := u.create.mutation.GetType(); exists { + s.SetIgnore(workflowrunevent.FieldType) + } + if _, exists := u.create.mutation.Key(); exists { + s.SetIgnore(workflowrunevent.FieldKey) + } + if _, exists := u.create.mutation.Status(); exists { + s.SetIgnore(workflowrunevent.FieldStatus) + } + if _, exists := u.create.mutation.Message(); exists { + s.SetIgnore(workflowrunevent.FieldMessage) + } + if _, exists := u.create.mutation.Attributes(); exists { + s.SetIgnore(workflowrunevent.FieldAttributes) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.WorkflowRunEvent.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *WorkflowRunEventUpsertOne) Ignore() *WorkflowRunEventUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *WorkflowRunEventUpsertOne) DoNothing() *WorkflowRunEventUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the WorkflowRunEventCreate.OnConflict +// documentation for more info. +func (u *WorkflowRunEventUpsertOne) Update(set func(*WorkflowRunEventUpsert)) *WorkflowRunEventUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&WorkflowRunEventUpsert{UpdateSet: update}) + })) + return u +} + +// Exec executes the query. +func (u *WorkflowRunEventUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for WorkflowRunEventCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *WorkflowRunEventUpsertOne) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} + +// Exec executes the UPSERT query and returns the inserted/updated ID. +func (u *WorkflowRunEventUpsertOne) ID(ctx context.Context) (id uuid.UUID, err error) { + if u.create.driver.Dialect() == dialect.MySQL { + // In case of "ON CONFLICT", there is no way to get back non-numeric ID + // fields from the database since MySQL does not support the RETURNING clause. + return id, errors.New("ent: WorkflowRunEventUpsertOne.ID is not supported by MySQL driver. Use WorkflowRunEventUpsertOne.Exec instead") + } + node, err := u.create.Save(ctx) + if err != nil { + return id, err + } + return node.ID, nil +} + +// IDX is like ID, but panics if an error occurs. +func (u *WorkflowRunEventUpsertOne) IDX(ctx context.Context) uuid.UUID { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// WorkflowRunEventCreateBulk is the builder for creating many WorkflowRunEvent entities in bulk. +type WorkflowRunEventCreateBulk struct { + config + err error + builders []*WorkflowRunEventCreate + conflict []sql.ConflictOption +} + +// Save creates the WorkflowRunEvent entities in the database. +func (_c *WorkflowRunEventCreateBulk) Save(ctx context.Context) ([]*WorkflowRunEvent, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*WorkflowRunEvent, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*WorkflowRunEventMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = _c.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + mutation.done = true + return nodes[i], nil + }) + for i := len(builder.hooks) - 1; i >= 0; i-- { + mut = builder.hooks[i](mut) + } + mutators[i] = mut + }(i, ctx) + } + if len(mutators) > 0 { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *WorkflowRunEventCreateBulk) SaveX(ctx context.Context) []*WorkflowRunEvent { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *WorkflowRunEventCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *WorkflowRunEventCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.WorkflowRunEvent.CreateBulk(builders...). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.WorkflowRunEventUpsert) { +// SetWorkflowRunID(v+v). +// }). +// Exec(ctx) +func (_c *WorkflowRunEventCreateBulk) OnConflict(opts ...sql.ConflictOption) *WorkflowRunEventUpsertBulk { + _c.conflict = opts + return &WorkflowRunEventUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.WorkflowRunEvent.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *WorkflowRunEventCreateBulk) OnConflictColumns(columns ...string) *WorkflowRunEventUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &WorkflowRunEventUpsertBulk{ + create: _c, + } +} + +// WorkflowRunEventUpsertBulk is the builder for "upsert"-ing +// a bulk of WorkflowRunEvent nodes. +type WorkflowRunEventUpsertBulk struct { + create *WorkflowRunEventCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.WorkflowRunEvent.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(workflowrunevent.FieldID) +// }), +// ). +// Exec(ctx) +func (u *WorkflowRunEventUpsertBulk) UpdateNewValues() *WorkflowRunEventUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + for _, b := range u.create.builders { + if _, exists := b.mutation.ID(); exists { + s.SetIgnore(workflowrunevent.FieldID) + } + if _, exists := b.mutation.WorkflowRunID(); exists { + s.SetIgnore(workflowrunevent.FieldWorkflowRunID) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(workflowrunevent.FieldCreatedAt) + } + if _, exists := b.mutation.Source(); exists { + s.SetIgnore(workflowrunevent.FieldSource) + } + if _, exists := b.mutation.GetType(); exists { + s.SetIgnore(workflowrunevent.FieldType) + } + if _, exists := b.mutation.Key(); exists { + s.SetIgnore(workflowrunevent.FieldKey) + } + if _, exists := b.mutation.Status(); exists { + s.SetIgnore(workflowrunevent.FieldStatus) + } + if _, exists := b.mutation.Message(); exists { + s.SetIgnore(workflowrunevent.FieldMessage) + } + if _, exists := b.mutation.Attributes(); exists { + s.SetIgnore(workflowrunevent.FieldAttributes) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.WorkflowRunEvent.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *WorkflowRunEventUpsertBulk) Ignore() *WorkflowRunEventUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *WorkflowRunEventUpsertBulk) DoNothing() *WorkflowRunEventUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the WorkflowRunEventCreateBulk.OnConflict +// documentation for more info. +func (u *WorkflowRunEventUpsertBulk) Update(set func(*WorkflowRunEventUpsert)) *WorkflowRunEventUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&WorkflowRunEventUpsert{UpdateSet: update}) + })) + return u +} + +// Exec executes the query. +func (u *WorkflowRunEventUpsertBulk) Exec(ctx context.Context) error { + if u.create.err != nil { + return u.create.err + } + for i, b := range u.create.builders { + if len(b.conflict) != 0 { + return fmt.Errorf("ent: OnConflict was set for builder %d. Set it on the WorkflowRunEventCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for WorkflowRunEventCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *WorkflowRunEventUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/app/controlplane/pkg/data/ent/workflowrunevent_delete.go b/app/controlplane/pkg/data/ent/workflowrunevent_delete.go new file mode 100644 index 000000000..d946f7ca2 --- /dev/null +++ b/app/controlplane/pkg/data/ent/workflowrunevent_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/predicate" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowrunevent" +) + +// WorkflowRunEventDelete is the builder for deleting a WorkflowRunEvent entity. +type WorkflowRunEventDelete struct { + config + hooks []Hook + mutation *WorkflowRunEventMutation +} + +// Where appends a list predicates to the WorkflowRunEventDelete builder. +func (_d *WorkflowRunEventDelete) Where(ps ...predicate.WorkflowRunEvent) *WorkflowRunEventDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *WorkflowRunEventDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *WorkflowRunEventDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *WorkflowRunEventDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(workflowrunevent.Table, sqlgraph.NewFieldSpec(workflowrunevent.FieldID, field.TypeUUID)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// WorkflowRunEventDeleteOne is the builder for deleting a single WorkflowRunEvent entity. +type WorkflowRunEventDeleteOne struct { + _d *WorkflowRunEventDelete +} + +// Where appends a list predicates to the WorkflowRunEventDelete builder. +func (_d *WorkflowRunEventDeleteOne) Where(ps ...predicate.WorkflowRunEvent) *WorkflowRunEventDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *WorkflowRunEventDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{workflowrunevent.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *WorkflowRunEventDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/app/controlplane/pkg/data/ent/workflowrunevent_query.go b/app/controlplane/pkg/data/ent/workflowrunevent_query.go new file mode 100644 index 000000000..924e02cb4 --- /dev/null +++ b/app/controlplane/pkg/data/ent/workflowrunevent_query.go @@ -0,0 +1,657 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/predicate" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowrun" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowrunevent" + "github.com/google/uuid" +) + +// WorkflowRunEventQuery is the builder for querying WorkflowRunEvent entities. +type WorkflowRunEventQuery struct { + config + ctx *QueryContext + order []workflowrunevent.OrderOption + inters []Interceptor + predicates []predicate.WorkflowRunEvent + withWorkflowRun *WorkflowRunQuery + modifiers []func(*sql.Selector) + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the WorkflowRunEventQuery builder. +func (_q *WorkflowRunEventQuery) Where(ps ...predicate.WorkflowRunEvent) *WorkflowRunEventQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *WorkflowRunEventQuery) Limit(limit int) *WorkflowRunEventQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *WorkflowRunEventQuery) Offset(offset int) *WorkflowRunEventQuery { + _q.ctx.Offset = &offset + return _q +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (_q *WorkflowRunEventQuery) Unique(unique bool) *WorkflowRunEventQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *WorkflowRunEventQuery) Order(o ...workflowrunevent.OrderOption) *WorkflowRunEventQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryWorkflowRun chains the current query on the "workflow_run" edge. +func (_q *WorkflowRunEventQuery) QueryWorkflowRun() *WorkflowRunQuery { + query := (&WorkflowRunClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(workflowrunevent.Table, workflowrunevent.FieldID, selector), + sqlgraph.To(workflowrun.Table, workflowrun.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, workflowrunevent.WorkflowRunTable, workflowrunevent.WorkflowRunColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first WorkflowRunEvent entity from the query. +// Returns a *NotFoundError when no WorkflowRunEvent was found. +func (_q *WorkflowRunEventQuery) First(ctx context.Context) (*WorkflowRunEvent, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{workflowrunevent.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *WorkflowRunEventQuery) FirstX(ctx context.Context) *WorkflowRunEvent { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first WorkflowRunEvent ID from the query. +// Returns a *NotFoundError when no WorkflowRunEvent ID was found. +func (_q *WorkflowRunEventQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{workflowrunevent.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *WorkflowRunEventQuery) FirstIDX(ctx context.Context) uuid.UUID { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single WorkflowRunEvent entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one WorkflowRunEvent entity is found. +// Returns a *NotFoundError when no WorkflowRunEvent entities are found. +func (_q *WorkflowRunEventQuery) Only(ctx context.Context) (*WorkflowRunEvent, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{workflowrunevent.Label} + default: + return nil, &NotSingularError{workflowrunevent.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *WorkflowRunEventQuery) OnlyX(ctx context.Context) *WorkflowRunEvent { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only WorkflowRunEvent ID in the query. +// Returns a *NotSingularError when more than one WorkflowRunEvent ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *WorkflowRunEventQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{workflowrunevent.Label} + default: + err = &NotSingularError{workflowrunevent.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *WorkflowRunEventQuery) OnlyIDX(ctx context.Context) uuid.UUID { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of WorkflowRunEvents. +func (_q *WorkflowRunEventQuery) All(ctx context.Context) ([]*WorkflowRunEvent, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*WorkflowRunEvent, *WorkflowRunEventQuery]() + return withInterceptors[[]*WorkflowRunEvent](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *WorkflowRunEventQuery) AllX(ctx context.Context) []*WorkflowRunEvent { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of WorkflowRunEvent IDs. +func (_q *WorkflowRunEventQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(workflowrunevent.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *WorkflowRunEventQuery) IDsX(ctx context.Context) []uuid.UUID { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *WorkflowRunEventQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*WorkflowRunEventQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *WorkflowRunEventQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *WorkflowRunEventQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *WorkflowRunEventQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the WorkflowRunEventQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *WorkflowRunEventQuery) Clone() *WorkflowRunEventQuery { + if _q == nil { + return nil + } + return &WorkflowRunEventQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]workflowrunevent.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.WorkflowRunEvent{}, _q.predicates...), + withWorkflowRun: _q.withWorkflowRun.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + modifiers: append([]func(*sql.Selector){}, _q.modifiers...), + } +} + +// WithWorkflowRun tells the query-builder to eager-load the nodes that are connected to +// the "workflow_run" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *WorkflowRunEventQuery) WithWorkflowRun(opts ...func(*WorkflowRunQuery)) *WorkflowRunEventQuery { + query := (&WorkflowRunClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withWorkflowRun = query + return _q +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// WorkflowRunID uuid.UUID `json:"workflow_run_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.WorkflowRunEvent.Query(). +// GroupBy(workflowrunevent.FieldWorkflowRunID). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (_q *WorkflowRunEventQuery) GroupBy(field string, fields ...string) *WorkflowRunEventGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &WorkflowRunEventGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = workflowrunevent.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// WorkflowRunID uuid.UUID `json:"workflow_run_id,omitempty"` +// } +// +// client.WorkflowRunEvent.Query(). +// Select(workflowrunevent.FieldWorkflowRunID). +// Scan(ctx, &v) +func (_q *WorkflowRunEventQuery) Select(fields ...string) *WorkflowRunEventSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &WorkflowRunEventSelect{WorkflowRunEventQuery: _q} + sbuild.label = workflowrunevent.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a WorkflowRunEventSelect configured with the given aggregations. +func (_q *WorkflowRunEventQuery) Aggregate(fns ...AggregateFunc) *WorkflowRunEventSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *WorkflowRunEventQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !workflowrunevent.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *WorkflowRunEventQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*WorkflowRunEvent, error) { + var ( + nodes = []*WorkflowRunEvent{} + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withWorkflowRun != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*WorkflowRunEvent).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &WorkflowRunEvent{config: _q.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := _q.withWorkflowRun; query != nil { + if err := _q.loadWorkflowRun(ctx, query, nodes, nil, + func(n *WorkflowRunEvent, e *WorkflowRun) { n.Edges.WorkflowRun = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *WorkflowRunEventQuery) loadWorkflowRun(ctx context.Context, query *WorkflowRunQuery, nodes []*WorkflowRunEvent, init func(*WorkflowRunEvent), assign func(*WorkflowRunEvent, *WorkflowRun)) error { + ids := make([]uuid.UUID, 0, len(nodes)) + nodeids := make(map[uuid.UUID][]*WorkflowRunEvent) + for i := range nodes { + fk := nodes[i].WorkflowRunID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(workflowrun.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "workflow_run_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *WorkflowRunEventQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *WorkflowRunEventQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(workflowrunevent.Table, workflowrunevent.Columns, sqlgraph.NewFieldSpec(workflowrunevent.FieldID, field.TypeUUID)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, workflowrunevent.FieldID) + for i := range fields { + if fields[i] != workflowrunevent.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withWorkflowRun != nil { + _spec.Node.AddColumnOnce(workflowrunevent.FieldWorkflowRunID) + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *WorkflowRunEventQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(workflowrunevent.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = workflowrunevent.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, m := range _q.modifiers { + m(selector) + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// ForUpdate locks the selected rows against concurrent updates, and prevent them from being +// updated, deleted or "selected ... for update" by other sessions, until the transaction is +// either committed or rolled-back. +func (_q *WorkflowRunEventQuery) ForUpdate(opts ...sql.LockOption) *WorkflowRunEventQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return _q +} + +// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock +// on any rows that are read. Other sessions can read the rows, but cannot modify them +// until your transaction commits. +func (_q *WorkflowRunEventQuery) ForShare(opts ...sql.LockOption) *WorkflowRunEventQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (_q *WorkflowRunEventQuery) Modify(modifiers ...func(s *sql.Selector)) *WorkflowRunEventSelect { + _q.modifiers = append(_q.modifiers, modifiers...) + return _q.Select() +} + +// WorkflowRunEventGroupBy is the group-by builder for WorkflowRunEvent entities. +type WorkflowRunEventGroupBy struct { + selector + build *WorkflowRunEventQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *WorkflowRunEventGroupBy) Aggregate(fns ...AggregateFunc) *WorkflowRunEventGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *WorkflowRunEventGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*WorkflowRunEventQuery, *WorkflowRunEventGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *WorkflowRunEventGroupBy) sqlScan(ctx context.Context, root *WorkflowRunEventQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// WorkflowRunEventSelect is the builder for selecting fields of WorkflowRunEvent entities. +type WorkflowRunEventSelect struct { + *WorkflowRunEventQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *WorkflowRunEventSelect) Aggregate(fns ...AggregateFunc) *WorkflowRunEventSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *WorkflowRunEventSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*WorkflowRunEventQuery, *WorkflowRunEventSelect](ctx, _s.WorkflowRunEventQuery, _s, _s.inters, v) +} + +func (_s *WorkflowRunEventSelect) sqlScan(ctx context.Context, root *WorkflowRunEventQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (_s *WorkflowRunEventSelect) Modify(modifiers ...func(s *sql.Selector)) *WorkflowRunEventSelect { + _s.modifiers = append(_s.modifiers, modifiers...) + return _s +} diff --git a/app/controlplane/pkg/data/ent/workflowrunevent_update.go b/app/controlplane/pkg/data/ent/workflowrunevent_update.go new file mode 100644 index 000000000..57abfaf1a --- /dev/null +++ b/app/controlplane/pkg/data/ent/workflowrunevent_update.go @@ -0,0 +1,225 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/predicate" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowrunevent" +) + +// WorkflowRunEventUpdate is the builder for updating WorkflowRunEvent entities. +type WorkflowRunEventUpdate struct { + config + hooks []Hook + mutation *WorkflowRunEventMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the WorkflowRunEventUpdate builder. +func (_u *WorkflowRunEventUpdate) Where(ps ...predicate.WorkflowRunEvent) *WorkflowRunEventUpdate { + _u.mutation.Where(ps...) + return _u +} + +// Mutation returns the WorkflowRunEventMutation object of the builder. +func (_u *WorkflowRunEventUpdate) Mutation() *WorkflowRunEventMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *WorkflowRunEventUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *WorkflowRunEventUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *WorkflowRunEventUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *WorkflowRunEventUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *WorkflowRunEventUpdate) check() error { + if _u.mutation.WorkflowRunCleared() && len(_u.mutation.WorkflowRunIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "WorkflowRunEvent.workflow_run"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *WorkflowRunEventUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *WorkflowRunEventUpdate { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *WorkflowRunEventUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(workflowrunevent.Table, workflowrunevent.Columns, sqlgraph.NewFieldSpec(workflowrunevent.FieldID, field.TypeUUID)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if _u.mutation.MessageCleared() { + _spec.ClearField(workflowrunevent.FieldMessage, field.TypeString) + } + if _u.mutation.AttributesCleared() { + _spec.ClearField(workflowrunevent.FieldAttributes, field.TypeJSON) + } + _spec.AddModifiers(_u.modifiers...) + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{workflowrunevent.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// WorkflowRunEventUpdateOne is the builder for updating a single WorkflowRunEvent entity. +type WorkflowRunEventUpdateOne struct { + config + fields []string + hooks []Hook + mutation *WorkflowRunEventMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Mutation returns the WorkflowRunEventMutation object of the builder. +func (_u *WorkflowRunEventUpdateOne) Mutation() *WorkflowRunEventMutation { + return _u.mutation +} + +// Where appends a list predicates to the WorkflowRunEventUpdate builder. +func (_u *WorkflowRunEventUpdateOne) Where(ps ...predicate.WorkflowRunEvent) *WorkflowRunEventUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *WorkflowRunEventUpdateOne) Select(field string, fields ...string) *WorkflowRunEventUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated WorkflowRunEvent entity. +func (_u *WorkflowRunEventUpdateOne) Save(ctx context.Context) (*WorkflowRunEvent, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *WorkflowRunEventUpdateOne) SaveX(ctx context.Context) *WorkflowRunEvent { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *WorkflowRunEventUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *WorkflowRunEventUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *WorkflowRunEventUpdateOne) check() error { + if _u.mutation.WorkflowRunCleared() && len(_u.mutation.WorkflowRunIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "WorkflowRunEvent.workflow_run"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *WorkflowRunEventUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *WorkflowRunEventUpdateOne { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *WorkflowRunEventUpdateOne) sqlSave(ctx context.Context) (_node *WorkflowRunEvent, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(workflowrunevent.Table, workflowrunevent.Columns, sqlgraph.NewFieldSpec(workflowrunevent.FieldID, field.TypeUUID)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "WorkflowRunEvent.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, workflowrunevent.FieldID) + for _, f := range fields { + if !workflowrunevent.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != workflowrunevent.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if _u.mutation.MessageCleared() { + _spec.ClearField(workflowrunevent.FieldMessage, field.TypeString) + } + if _u.mutation.AttributesCleared() { + _spec.ClearField(workflowrunevent.FieldAttributes, field.TypeJSON) + } + _spec.AddModifiers(_u.modifiers...) + _node = &WorkflowRunEvent{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{workflowrunevent.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/app/controlplane/pkg/data/workflowrun.go b/app/controlplane/pkg/data/workflowrun.go index b761d1d06..e00b5d7bc 100644 --- a/app/controlplane/pkg/data/workflowrun.go +++ b/app/controlplane/pkg/data/workflowrun.go @@ -420,16 +420,31 @@ func (r *WorkflowRunRepo) MarkAsFinished(ctx context.Context, id uuid.UUID, stat ctx, span := otelx.Start(ctx, workflowRunRepoTracer, "WorkflowRunRepo.MarkAsFinished") defer span.End() - run, err := r.data.DB.WorkflowRun.Query().Where(workflowrun.ID(id)).WithWorkflow().First(ctx) - if err != nil { - return fmt.Errorf("failed to find workflow run: %w", err) - } + // The status update and the closing event of the timeline are one change + return WithTx(ctx, r.data.DB, func(tx *ent.Tx) error { + run, err := tx.WorkflowRun.Query().Where(workflowrun.ID(id)).Select(workflowrun.FieldState, workflowrun.FieldAttestationDigest).ForUpdate().Only(ctx) + if err != nil { + return fmt.Errorf("failed to find workflow run: %w", err) + } - if err = run.Update().SetFinishedAt(time.Now()).SetState(status).SetReason(reason).ClearAttestationState().Exec(ctx); err != nil { - return fmt.Errorf("failed to mark workflow run as finished: %w", err) + if err = tx.WorkflowRun.UpdateOne(run).SetFinishedAt(time.Now()).SetState(status).SetReason(reason).ClearAttestationState().Exec(ctx); err != nil { + return fmt.Errorf("failed to mark workflow run as finished: %w", err) + } + + // The store path saves the attestation digest before it finishes the run + return closeWorkflowRunTimeline(ctx, tx.Client(), id, status, reason, run.AttestationDigest) + }) +} + +// closeWorkflowRunTimeline records the event that closes the timeline of a run +func closeWorkflowRunTimeline(ctx context.Context, client *ent.Client, runID uuid.UUID, status biz.WorkflowRunStatus, reason, digest string) error { + ev := biz.ClosingWorkflowRunEvent(runID, status, reason, digest) + if ev == nil { + return nil } - return nil + _, err := createWorkflowRunEvent(ctx, client, ev) + return err } // List the runs in an organization, optionally filtered out by workflow @@ -563,7 +578,23 @@ func (r *WorkflowRunRepo) Expire(ctx context.Context, id uuid.UUID) error { ctx, span := otelx.Start(ctx, workflowRunRepoTracer, "WorkflowRunRepo.Expire") defer span.End() - return r.data.DB.WorkflowRun.UpdateOneID(id).SetState(biz.WorkflowRunExpired).ClearAttestationState().Exec(ctx) + return WithTx(ctx, r.data.DB, func(tx *ent.Tx) error { + run, err := tx.WorkflowRun.Query().Where(workflowrun.ID(id)).Select(workflowrun.FieldState).ForUpdate().Only(ctx) + if err != nil { + return fmt.Errorf("failed to find workflow run: %w", err) + } + + // A run that finished during the sweep keeps its status and its closing event, and the sweep skips it + if run.State != biz.WorkflowRunInitialized { + return biz.NewErrFailedPreconditionStr("the workflow run is not in progress") + } + + if err := tx.WorkflowRun.UpdateOne(run).SetState(biz.WorkflowRunExpired).ClearAttestationState().Exec(ctx); err != nil { + return fmt.Errorf("failed to expire workflow run: %w", err) + } + + return closeWorkflowRunTimeline(ctx, tx.Client(), id, biz.WorkflowRunExpired, "", "") + }) } func entWrToBizWr(ctx context.Context, wr *ent.WorkflowRun) (*biz.WorkflowRun, error) { diff --git a/app/controlplane/pkg/data/workflowrunevent.go b/app/controlplane/pkg/data/workflowrunevent.go new file mode 100644 index 000000000..73b8432a1 --- /dev/null +++ b/app/controlplane/pkg/data/workflowrunevent.go @@ -0,0 +1,154 @@ +// +// Copyright 2026 The Chainloop Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package data + +import ( + "context" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/biz" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowrun" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowrunevent" + "github.com/chainloop-dev/chainloop/pkg/otelx" + "github.com/go-kratos/kratos/v2/log" + "github.com/google/uuid" +) + +var workflowRunEventRepoTracer = otelx.Tracer("chainloop-controlplane", "data/workflowrunevent") + +type WorkflowRunEventRepo struct { + data *Data + log *log.Helper +} + +func NewWorkflowRunEventRepo(data *Data, logger log.Logger) biz.WorkflowRunEventRepo { + return &WorkflowRunEventRepo{data: data, log: log.NewHelper(logger)} +} + +func (r *WorkflowRunEventRepo) Create(ctx context.Context, event *biz.WorkflowRunEvent, maxEvents int) (*biz.WorkflowRunEvent, error) { + ctx, span := otelx.Start(ctx, workflowRunEventRepoTracer, "WorkflowRunEventRepo.Create") + defer span.End() + + var created *ent.WorkflowRunEvent + err := WithTx(ctx, r.data.DB, func(tx *ent.Tx) error { + // Lock the run, so that no event lands after the closing event + run, err := tx.WorkflowRun.Query().Where(workflowrun.ID(event.WorkflowRunID)).Select(workflowrun.FieldState).ForUpdate().Only(ctx) + if err != nil { + if ent.IsNotFound(err) { + return biz.NewErrNotFound("workflow run") + } + return fmt.Errorf("failed to find workflow run: %w", err) + } + + if run.State != biz.WorkflowRunInitialized { + return biz.NewErrFailedPreconditionStr("the workflow run is not in progress") + } + + count, err := tx.WorkflowRunEvent.Query().Where(workflowrunevent.WorkflowRunID(event.WorkflowRunID)).Count(ctx) + if err != nil { + return fmt.Errorf("failed to count workflow run events: %w", err) + } + + if count >= maxEvents { + return biz.NewErrFailedPreconditionStr(fmt.Sprintf("the workflow run reached the limit of %d events", maxEvents)) + } + + created, err = createWorkflowRunEvent(ctx, tx.Client(), event) + return err + }) + if err != nil { + return nil, err + } + + return entWorkflowRunEventToBiz(created), nil +} + +// createWorkflowRunEvent inserts an event with the given client, which can be bound to a transaction +func createWorkflowRunEvent(ctx context.Context, client *ent.Client, event *biz.WorkflowRunEvent) (*ent.WorkflowRunEvent, error) { + q := client.WorkflowRunEvent.Create(). + SetWorkflowRunID(event.WorkflowRunID). + SetSource(event.Source). + SetType(event.Type). + SetKey(event.Key). + SetStatus(event.Status). + SetMessage(event.Message) + + if event.Attributes != nil { + q.SetAttributes(event.Attributes) + } + + ev, err := q.Save(ctx) + if err != nil { + return nil, fmt.Errorf("failed to store workflow run event: %w", err) + } + + return ev, nil +} + +func (r *WorkflowRunEventRepo) List(ctx context.Context, runID uuid.UUID) ([]*biz.WorkflowRunEvent, error) { + ctx, span := otelx.Start(ctx, workflowRunEventRepoTracer, "WorkflowRunEventRepo.List") + defer span.End() + + q := r.data.DB.WorkflowRunEvent.Query().Where(workflowrunevent.WorkflowRunID(runID)) + + events, err := q.Order(ent.Asc(workflowrunevent.FieldCreatedAt), ent.Asc(workflowrunevent.FieldID)).All(ctx) + if err != nil { + return nil, fmt.Errorf("failed to list workflow run events: %w", err) + } + + result := make([]*biz.WorkflowRunEvent, 0, len(events)) + for _, e := range events { + result = append(result, entWorkflowRunEventToBiz(e)) + } + + return result, nil +} + +func (r *WorkflowRunEventRepo) DeleteOlderThan(ctx context.Context, t time.Time, limit int) (int, error) { + ctx, span := otelx.Start(ctx, workflowRunEventRepoTracer, "WorkflowRunEventRepo.DeleteOlderThan") + defer span.End() + + // One statement: delete a batch of the oldest rows that the created_at index finds + n, err := r.data.DB.WorkflowRunEvent.Delete().Where(func(s *sql.Selector) { + batch := sql.Select(workflowrunevent.FieldID). + From(sql.Table(workflowrunevent.Table)). + Where(sql.LT(workflowrunevent.FieldCreatedAt, t)). + Limit(limit) + s.Where(sql.In(s.C(workflowrunevent.FieldID), batch)) + }).Exec(ctx) + if err != nil { + return 0, fmt.Errorf("failed to delete old workflow run events: %w", err) + } + + return n, nil +} + +func entWorkflowRunEventToBiz(e *ent.WorkflowRunEvent) *biz.WorkflowRunEvent { + return &biz.WorkflowRunEvent{ + ID: e.ID, + WorkflowRunID: e.WorkflowRunID, + CreatedAt: toTimePtr(e.CreatedAt), + Source: e.Source, + Type: e.Type, + Key: e.Key, + Status: e.Status, + Message: e.Message, + Attributes: e.Attributes, + } +} diff --git a/app/controlplane/pkg/data/workflowrunevent_integration_test.go b/app/controlplane/pkg/data/workflowrunevent_integration_test.go new file mode 100644 index 000000000..27db60b0e --- /dev/null +++ b/app/controlplane/pkg/data/workflowrunevent_integration_test.go @@ -0,0 +1,341 @@ +// +// Copyright 2026 The Chainloop Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package data_test + +import ( + "context" + "testing" + "time" + + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/biz" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/biz/testhelpers" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowrunevent" + "github.com/google/uuid" + "github.com/stretchr/testify/suite" +) + +func TestWorkflowRunEventIntegration(t *testing.T) { + suite.Run(t, new(workflowRunEventIntegrationTestSuite)) +} + +type workflowRunEventIntegrationTestSuite struct { + testhelpers.UseCasesEachTestSuite + orgID, workflowID, versionID uuid.UUID +} + +func (s *workflowRunEventIntegrationTestSuite) SetupTest() { + s.UseCasesEachTestSuite.SetupTest() + ctx := context.Background() + client := s.Data.DB + + s.orgID = client.Organization.Create().SetName("org").SaveX(ctx).ID + contract := client.WorkflowContract.Create().SetName("contract").SetOrganizationID(s.orgID).SaveX(ctx) + project := client.Project.Create().SetName("project").SetOrganizationID(s.orgID).SaveX(ctx) + s.versionID = client.ProjectVersion.Create().SetProjectID(project.ID).SetVersion("v1").SaveX(ctx).ID + s.workflowID = client.Workflow.Create().SetName("workflow").SetOrganizationID(s.orgID). + SetProjectID(project.ID).SetContractID(contract.ID).SaveX(ctx).ID +} + +// newRun creates a workflow run in progress +func (s *workflowRunEventIntegrationTestSuite) newRun() uuid.UUID { + return s.Data.DB.WorkflowRun.Create(). + SetWorkflowID(s.workflowID). + SetOrganizationID(s.orgID). + SetVersionID(s.versionID). + SetContractRevisionUsed(1). + SetContractRevisionLatest(1). + SaveX(context.Background()).ID +} + +func materialEvent(runID uuid.UUID, name string, status biz.WorkflowRunEventStatus) *biz.WorkflowRunEvent { + return &biz.WorkflowRunEvent{ + WorkflowRunID: runID, + Source: biz.WorkflowRunEventSourceCLI, + Type: biz.WorkflowRunEventTypeMaterial, + Key: "chainloop.material." + name, + Status: status, + Attributes: &biz.WorkflowRunEventAttributes{ + Material: &biz.WorkflowRunEventMaterialAttributes{Name: name, MaterialType: "STRING"}, + }, + } +} + +func (s *workflowRunEventIntegrationTestSuite) TestCreate() { + ctx := context.Background() + repo := s.Repos.WorkflowRunEvent + + testCases := []struct { + name string + // setup returns the run to write to + setup func() uuid.UUID + maxEvents int + wantErr func(error) bool + }{ + { + name: "run in progress", + setup: s.newRun, + maxEvents: 10, + }, + { + name: "finished run is rejected", + setup: func() uuid.UUID { + id := s.newRun() + s.Require().NoError(s.Repos.WorkflowRunRepo.MarkAsFinished(ctx, id, biz.WorkflowRunSuccess, "")) + return id + }, + maxEvents: 10, + wantErr: biz.IsErrFailedPrecondition, + }, + { + name: "expired run is rejected", + setup: func() uuid.UUID { + id := s.newRun() + s.Require().NoError(s.Repos.WorkflowRunRepo.Expire(ctx, id)) + return id + }, + maxEvents: 10, + wantErr: biz.IsErrFailedPrecondition, + }, + { + name: "limit reached", + setup: func() uuid.UUID { + id := s.newRun() + for range 2 { + _, err := repo.Create(ctx, materialEvent(id, "sbom", biz.WorkflowRunEventStatusSucceeded), 2) + s.Require().NoError(err) + } + return id + }, + maxEvents: 2, + wantErr: biz.IsErrFailedPrecondition, + }, + { + name: "unknown run", + setup: uuid.New, + maxEvents: 10, + wantErr: biz.IsNotFound, + }, + } + + for _, tc := range testCases { + s.Run(tc.name, func() { + runID := tc.setup() + got, err := repo.Create(ctx, materialEvent(runID, "image", biz.WorkflowRunEventStatusFailed), tc.maxEvents) + if tc.wantErr != nil { + s.Require().Error(err) + s.True(tc.wantErr(err), "unexpected error: %v", err) + return + } + + s.Require().NoError(err) + s.NotEqual(uuid.Nil, got.ID) + s.NotNil(got.CreatedAt) + s.Equal(runID, got.WorkflowRunID) + s.Equal("chainloop.material.image", got.Key) + s.Equal(biz.WorkflowRunEventStatusFailed, got.Status) + s.Equal("image", got.Attributes.Material.Name) + }) + } +} + +func (s *workflowRunEventIntegrationTestSuite) TestList() { + ctx := context.Background() + repo := s.Repos.WorkflowRunEvent + + runID := s.newRun() + ids := make([]uuid.UUID, 0, 3) + for _, name := range []string{"a", "b", "c"} { + ev, err := repo.Create(ctx, materialEvent(runID, name, biz.WorkflowRunEventStatusSucceeded), 10) + s.Require().NoError(err) + ids = append(ids, ev.ID) + } + + // the events of another run never show + _, err := repo.Create(ctx, materialEvent(s.newRun(), "x", biz.WorkflowRunEventStatusSucceeded), 10) + s.Require().NoError(err) + + testCases := []struct { + name string + runID uuid.UUID + want []uuid.UUID + }{ + {name: "all events of the run, oldest first", runID: runID, want: ids}, + {name: "run with no events", runID: s.newRun(), want: nil}, + } + + for _, tc := range testCases { + s.Run(tc.name, func() { + got, err := repo.List(ctx, tc.runID) + s.Require().NoError(err) + + gotIDs := make([]uuid.UUID, 0, len(got)) + for _, e := range got { + gotIDs = append(gotIDs, e.ID) + } + if tc.want == nil { + s.Empty(gotIDs) + return + } + s.Equal(tc.want, gotIDs) + }) + } +} + +func (s *workflowRunEventIntegrationTestSuite) TestRunDeleteCascades() { + ctx := context.Background() + runID := s.newRun() + _, err := s.Repos.WorkflowRunEvent.Create(ctx, materialEvent(runID, "a", biz.WorkflowRunEventStatusSucceeded), 10) + s.Require().NoError(err) + + s.Require().NoError(s.Data.DB.WorkflowRun.DeleteOneID(runID).Exec(ctx)) + + n, err := s.Data.DB.WorkflowRunEvent.Query().Where(workflowrunevent.WorkflowRunID(runID)).Count(ctx) + s.Require().NoError(err) + s.Zero(n) +} + +func (s *workflowRunEventIntegrationTestSuite) TestDeleteOlderThan() { + ctx := context.Background() + runID := s.newRun() + now := time.Now() + + create := func(createdAt time.Time) uuid.UUID { + return s.Data.DB.WorkflowRunEvent.Create(). + SetWorkflowRunID(runID). + SetSource(biz.WorkflowRunEventSourceCLI). + SetType(biz.WorkflowRunEventTypeMaterial). + SetKey("chainloop.material.a"). + SetStatus(biz.WorkflowRunEventStatusSucceeded). + SetCreatedAt(createdAt). + SaveX(ctx).ID + } + + for range 3 { + create(now.Add(-100 * 24 * time.Hour)) + } + recent := create(now.Add(-time.Hour)) + + // batches of 2 delete the three old events + n, err := s.Repos.WorkflowRunEvent.DeleteOlderThan(ctx, now.Add(-90*24*time.Hour), 2) + s.Require().NoError(err) + s.Equal(2, n) + n, err = s.Repos.WorkflowRunEvent.DeleteOlderThan(ctx, now.Add(-90*24*time.Hour), 2) + s.Require().NoError(err) + s.Equal(1, n) + + left, err := s.Data.DB.WorkflowRunEvent.Query().IDs(ctx) + s.Require().NoError(err) + s.Equal([]uuid.UUID{recent}, left) + + // the run stays + _, err = s.Data.DB.WorkflowRun.Get(ctx, runID) + s.NoError(err) +} + +// The run closes its timeline when it is stored, canceled, failed, or expired (R-006) +func (s *workflowRunEventIntegrationTestSuite) TestClosingEvent() { + ctx := context.Background() + runRepo := s.Repos.WorkflowRunRepo + const digest = "sha256:deadbeef" + + testCases := []struct { + name string + finish func(id uuid.UUID) error + wantStatus biz.WorkflowRunEventStatus + wantMessage string + wantDigest string + }{ + { + name: "store", + finish: func(id uuid.UUID) error { + if err := runRepo.SaveAttestationDigest(ctx, id, digest, false); err != nil { + return err + } + return runRepo.MarkAsFinished(ctx, id, biz.WorkflowRunSuccess, "") + }, + wantStatus: biz.WorkflowRunEventStatusSucceeded, + wantDigest: digest, + }, + { + name: "reset with cancellation", + finish: func(id uuid.UUID) error { + return runRepo.MarkAsFinished(ctx, id, biz.WorkflowRunCancelled, "user canceled") + }, + wantStatus: biz.WorkflowRunEventStatusCanceled, + wantMessage: "user canceled", + }, + { + name: "reset with failure", + finish: func(id uuid.UUID) error { + return runRepo.MarkAsFinished(ctx, id, biz.WorkflowRunError, "build failed") + }, + wantStatus: biz.WorkflowRunEventStatusFailed, + wantMessage: "build failed", + }, + { + name: "expiry", + finish: func(id uuid.UUID) error { return runRepo.Expire(ctx, id) }, + wantStatus: biz.WorkflowRunEventStatusFailed, + wantMessage: "expired", + }, + } + + for _, tc := range testCases { + s.Run(tc.name, func() { + runID := s.newRun() + _, err := s.Repos.WorkflowRunEvent.Create(ctx, materialEvent(runID, "a", biz.WorkflowRunEventStatusSucceeded), 10) + s.Require().NoError(err) + + s.Require().NoError(tc.finish(runID)) + + events, err := s.Repos.WorkflowRunEvent.List(ctx, runID) + s.Require().NoError(err) + s.Require().Len(events, 2) + + last := events[len(events)-1] + s.Equal(biz.WorkflowRunEventSourceControlPlane, last.Source) + s.Equal(biz.WorkflowRunEventTypeAttestation, last.Type) + s.Equal(biz.WorkflowRunEventKeyAttestation, last.Key) + s.Equal(tc.wantStatus, last.Status) + s.Equal(tc.wantMessage, last.Message) + if tc.wantDigest != "" { + s.Require().NotNil(last.Attributes) + s.Equal(tc.wantDigest, last.Attributes.Attestation.AttestationDigest) + } else { + s.Nil(last.Attributes) + } + }) + } +} + +// A run that a store finishes during the expiry sweep keeps its status and gets one closing event +func (s *workflowRunEventIntegrationTestSuite) TestExpireSkipsFinishedRun() { + ctx := context.Background() + runID := s.newRun() + s.Require().NoError(s.Repos.WorkflowRunRepo.MarkAsFinished(ctx, runID, biz.WorkflowRunSuccess, "")) + + err := s.Repos.WorkflowRunRepo.Expire(ctx, runID) + s.True(biz.IsErrFailedPrecondition(err), "the sweep skips a run that is no longer in progress, got %v", err) + + run, err := s.Data.DB.WorkflowRun.Get(ctx, runID) + s.Require().NoError(err) + s.Equal(biz.WorkflowRunSuccess, run.State) + + events, err := s.Repos.WorkflowRunEvent.List(ctx, runID) + s.Require().NoError(err) + s.Require().Len(events, 1) + s.Equal(biz.WorkflowRunEventStatusSucceeded, events[0].Status) +} diff --git a/deployment/chainloop/Chart.yaml b/deployment/chainloop/Chart.yaml index 57d099e32..5c32f0cf4 100644 --- a/deployment/chainloop/Chart.yaml +++ b/deployment/chainloop/Chart.yaml @@ -7,7 +7,7 @@ description: Chainloop is an open source software supply chain control plane, a type: application # Bump the patch (not minor, not major) version on each change in the Chart Source code -version: 1.493.0 +version: 1.493.1 # Do not update appVersion, this is handled automatically by the release process appVersion: v1.138.0 diff --git a/deployment/chainloop/README.md b/deployment/chainloop/README.md index c6441e003..d54f80c3a 100644 --- a/deployment/chainloop/README.md +++ b/deployment/chainloop/README.md @@ -706,6 +706,7 @@ Once done, you can access with [two predefined users](https://github.com/chainlo | `controlplane.attestations` | Attestation processing configuration | | | `controlplane.attestations.workflowRunExpirationWindow` | Maximum age of an unfinished workflow run before it is marked as expired. Use seconds with an "s" suffix, for example "3600s". Units such as "1h" are not supported | `3600s` | | `controlplane.attestations.workflowRunExpirationCheckInterval` | Interval between checks for unfinished workflow runs. Use seconds with an "s" suffix, for example "60s". Units such as "1m" are not supported | `60s` | +| `controlplane.attestations.workflowRunEventsRetention` | Age after which workflow run events are deleted. Use seconds with an "s" suffix, for example "7776000s" | `7776000s` | | `controlplane.containerPorts.http` | controlplane HTTP container port | `8000` | | `controlplane.containerPorts.grpc` | controlplane gRPC container port | `9000` | | `controlplane.containerPorts.metrics` | controlplane prometheus metrics container port | `5000` | diff --git a/deployment/chainloop/templates/controlplane/configmap.yaml b/deployment/chainloop/templates/controlplane/configmap.yaml index 60f70cb4e..a78f9eea8 100644 --- a/deployment/chainloop/templates/controlplane/configmap.yaml +++ b/deployment/chainloop/templates/controlplane/configmap.yaml @@ -67,6 +67,7 @@ data: attestations: workflow_run_expiration_window: {{ .Values.controlplane.attestations.workflowRunExpirationWindow | quote }} workflow_run_expiration_check_interval: {{ .Values.controlplane.attestations.workflowRunExpirationCheckInterval | quote }} + workflow_run_events_retention: {{ .Values.controlplane.attestations.workflowRunEventsRetention | quote }} force_verification: {{ ne .Values.controlplane.keylessSigning.forceVerification false }} restrict_org_creation: {{ .Values.controlplane.restrictOrgCreation }} {{- if .Values.controlplane.uiDashboardURL }} diff --git a/deployment/chainloop/values.yaml b/deployment/chainloop/values.yaml index d9dcfd9de..1ea08ee11 100644 --- a/deployment/chainloop/values.yaml +++ b/deployment/chainloop/values.yaml @@ -151,9 +151,11 @@ controlplane: ## @extra controlplane.attestations Attestation processing configuration ## @param controlplane.attestations.workflowRunExpirationWindow Maximum age of an unfinished workflow run before it is marked as expired. Use seconds with an "s" suffix, for example "3600s". Units such as "1h" are not supported ## @param controlplane.attestations.workflowRunExpirationCheckInterval Interval between checks for unfinished workflow runs. Use seconds with an "s" suffix, for example "60s". Units such as "1m" are not supported + ## @param controlplane.attestations.workflowRunEventsRetention Age after which workflow run events are deleted. Use seconds with an "s" suffix, for example "7776000s" attestations: workflowRunExpirationWindow: "3600s" workflowRunExpirationCheckInterval: "60s" + workflowRunEventsRetention: "7776000s" ## @param controlplane.containerPorts.http controlplane HTTP container port ## @param controlplane.containerPorts.grpc controlplane gRPC container port diff --git a/docs/plans/issue-3825-attestation-progress-events.md b/docs/plans/issue-3825-attestation-progress-events.md index 96f07d9be..9f5df0d47 100644 --- a/docs/plans/issue-3825-attestation-progress-events.md +++ b/docs/plans/issue-3825-attestation-progress-events.md @@ -25,11 +25,11 @@ While an attestation is in progress, `chainloop workflow run describe` shows onl ### After this plan -`chainloop workflow run describe` on a run in progress shows the elapsed time and each contract material as provided or missing. It also shows the policy counts so far and a timeline of steps. A pipeline can add its own steps with `chainloop attestation event`. After the push, the same command shows the signed attestation, with the timeline as history. +`chainloop workflow run describe` on a run in progress shows the elapsed time, and each material of the contract and its policy groups as provided, missing, or failed. It also shows the policy counts so far and a timeline of steps. A pipeline can add its own steps with `chainloop attestation event`. After the push, the same command shows the signed attestation, with the timeline as history. ### How -The CLI records a run event after each attestation action, through a new call in the attestation API. The call is best effort, as other optional CLI calls are. The control plane stores the events in a new table next to the workflow run. It closes the timeline when it stores, cancels, or expires the run, and the run expiry job also deletes old events. A new call in the workflow run API returns the events, with the same project access rules as the run view. +The CLI records a run event after each attestation action, through a new call in the attestation API. The call is best effort, as other optional CLI calls are. The control plane stores the events in a new table next to the workflow run. It closes the timeline when it stores, cancels, or expires the run, and the run expiry job also deletes old events. A new call in the workflow run API, `GetProgress`, returns the events. For a run in progress, it also returns the progress, which the control plane builds from the expected materials and the events. The call has the access rules of the run view, and the run view does not change. ### Rollout @@ -49,7 +49,7 @@ flowchart LR end subgraph CP["Control plane"] svcA["attestation API: RecordEvent"]:::new - svcR["workflow run API: ListEvents"]:::new + svcR["workflow run API: GetProgress"]:::new biz["run events use case"]:::new fin["store, cancel, expire"]:::changed exp["run expiry job"]:::changed @@ -63,15 +63,15 @@ flowchart LR fin -->|closing event row| db exp -->|old event rows, deleted| db db -->|event rows| biz - biz -->|events| svcR - svcR -->|events| desc + biz -->|events and progress| svcR + svcR -->|events and progress| desc classDef new fill:#d4f7d4,stroke:#2e7d32 classDef changed fill:#fff4c2,stroke:#b8860b ``` Green: new. Yellow: changed. No color: unchanged. -Where does an event go from the CI job to the user? The CLI sends it to the attestation API. The control plane stores it with the run, and `describe` gets it through the run API. +Where does an event go from the CI job to the user? The CLI sends it to the attestation API. The control plane stores it with the run. `describe` gets it, and the progress that the control plane builds from it, through `GetProgress`. **Data model** @@ -96,17 +96,17 @@ One new table. A deleted run deletes its events. An index on the run and the tim | Impact on | What changes | Where | |-----------|--------------|-------| | Users | CI users see progress in `describe` (see User-facing changes). Operators get one new retention value. | `app/cli/cmd/`, `deployment/chainloop/` | -| Other parts of the product | The platform UI can poll the new read call. No change to it in this plan. The run store, cancel, and expiry paths write one more row, and the expiry job also deletes old events. | `app/controlplane/pkg/data/`, `app/controlplane/pkg/biz/` | +| Other parts of the product | The platform UI can poll `GetProgress` for the events and the progress. No change to it in this plan. The run store, cancel, and expiry paths write one more row, and the expiry job also deletes old events. | `app/controlplane/pkg/data/`, `app/controlplane/pkg/biz/` | | Data and migrations | New table `workflow_run_events`, with a foreign key to `workflow_runs` (cascade delete). The same migration creates its two indexes. The table is new and empty, so the migration locks no existing rows. | `app/controlplane/pkg/data/ent/schema/`, `app/controlplane/pkg/data/ent/migrate/migrations/` | | Rollout | Deploy the control plane before the CLI release. A CLI that comes first gets "not supported" and stops sending for the rest of each command. | none outside this repository | -| Compatibility | An older CLI sends no events, and `describe` shows its runs as today. A new CLI against an older control plane stops sending for the rest of each command, with no warning. `describe` against an older control plane shows the run as today. | `app/cli/pkg/action/` | +| Compatibility | An older CLI sends no events, and `describe` shows its runs as today. Some older CLIs send events but no expected materials. Their runs get a progress from the materials of the contract, with no policy group materials. A new CLI against an older control plane stops sending for the rest of each command, with no warning. `describe` against an older control plane shows the run as today. | `app/cli/pkg/action/` | | Rollback | Roll back the control plane. The table stays, unused, and no job deletes from it. The CLI gets "not supported" and shows no warning. | `app/controlplane/` | ## User-facing changes ### API -R-003, R-005, R-008 (M1) and R-009 (M2). `app/controlplane/api/controlplane/v1/workflow_run.proto`: +R-005, R-008, R-011 (M1) and R-009 (M2). `app/controlplane/api/controlplane/v1/workflow_run.proto`: ```diff service AttestationService { @@ -117,8 +117,8 @@ R-003, R-005, R-008 (M1) and R-009 (M2). `app/controlplane/api/controlplane/v1/w service WorkflowRunService { rpc View(WorkflowRunServiceViewRequest) returns (WorkflowRunServiceViewResponse); -+ // Events of a run, oldest first. Optional after_event_id returns only newer events. -+ rpc ListEvents(WorkflowRunServiceListEventsRequest) returns (WorkflowRunServiceListEventsResponse); ++ // Progress and timeline of a run. Clients poll it while the run is in progress. ++ rpc GetProgress(WorkflowRunServiceGetProgressRequest) returns (WorkflowRunServiceGetProgressResponse); } + +message AttestationServiceRecordEventRequest { @@ -128,12 +128,25 @@ R-003, R-005, R-008 (M1) and R-009 (M2). `app/controlplane/api/controlplane/v1/w +} +message AttestationServiceRecordEventResponse {} + -+message WorkflowRunServiceListEventsRequest { ++message WorkflowRunServiceGetProgressRequest { + string workflow_run_id = 1 [(buf.validate.field).string.uuid = true]; -+ string after_event_id = 2 [(buf.validate.field) = {ignore: IGNORE_IF_ZERO_VALUE, string: {uuid: true}}]; +} -+message WorkflowRunServiceListEventsResponse { -+ repeated WorkflowRunEvent events = 1; ++message WorkflowRunServiceGetProgressResponse { ++ // Progress of a run in progress, built by the control plane. Not set for a finished run. ++ WorkflowRunProgress progress = 1; ++ // Timeline of the run, oldest first ++ repeated WorkflowRunEvent events = 2; ++} ++ ++// One row for each expected material, then the materials not in the contract (spec D-012) ++message WorkflowRunProgress { ++ repeated Material materials = 1; ++ int32 required_total = 2; // a group of materials counts once ++ int32 required_provided = 3; ++ WorkflowRunEvent.PolicyCounts attestation_policies = 4; ++ message Material { string name = 1; string material_type = 2; Requirement requirement = 3; string group = 4; Status status = 5; string value = 6; WorkflowRunEvent.PolicyCounts policies = 7; string last_error = 8; int32 failed_attempts = 9; } ++ enum Requirement { REQUIREMENT_UNSPECIFIED = 0; REQUIREMENT_REQUIRED = 1; REQUIREMENT_OPTIONAL = 2; REQUIREMENT_ONE_OF_GROUP = 3; REQUIREMENT_NOT_IN_CONTRACT = 4; } ++ enum Status { STATUS_UNSPECIFIED = 0; STATUS_MISSING = 1; STATUS_PROVIDED = 2; STATUS_FAILED = 3; } +} + +message WorkflowRunEvent { @@ -144,16 +157,18 @@ R-003, R-005, R-008 (M1) and R-009 (M2). `app/controlplane/api/controlplane/v1/w + string key = 5 [(buf.validate.field).string = {min_len: 1, max_len: 128}]; + Status status = 6 [(buf.validate.field).enum = {not_in: [0], defined_only: true}]; + string message = 7 [(buf.validate.field).string.max_bytes = 1024]; -+ oneof attributes { AttestationAttributes attestation = 10; MaterialAttributes material = 11; PushAttributes push = 12; } ++ oneof attributes { AttestationAttributes attestation = 10; MaterialAttributes material = 11; } ++ reserved 12; reserved "push"; // the push event was dropped (spec D-011) + + enum Source { SOURCE_UNSPECIFIED = 0; SOURCE_CLI = 1; SOURCE_CONTROL_PLANE = 2; } -+ enum Type { TYPE_UNSPECIFIED = 0; TYPE_ATTESTATION = 1; TYPE_MATERIAL = 2; TYPE_PUSH = 3; } // TYPE_CUSTOM = 4 in M2 ++ enum Type { TYPE_UNSPECIFIED = 0; TYPE_ATTESTATION = 1; TYPE_MATERIAL = 2; reserved 3; reserved "TYPE_PUSH"; } // TYPE_CUSTOM = 4 in M2 + enum Status { STATUS_UNSPECIFIED = 0; STATUS_STARTED = 1; STATUS_SUCCEEDED = 2; STATUS_FAILED = 3; STATUS_CANCELED = 4; } + // Every string attribute below has [(buf.validate.field).string.max_len = 256] (D-010). + // Every policy name list has [(buf.validate.field).repeated = {max_items: 100, items: {string: {max_len: 256}}}]. -+ message AttestationAttributes { string contract_name = 1; int32 contract_revision = 2; string runner_type = 3; bool remote_state = 4; string cli_version = 5; string attestation_digest = 6; PolicyCounts policies = 7; } ++ message AttestationAttributes { string contract_name = 1; int32 contract_revision = 2; string runner_type = 3; bool remote_state = 4; string cli_version = 5; string attestation_digest = 6; PolicyCounts policies = 7; repeated ExpectedMaterial expected_materials = 8; } ++ // materials that init resolves, from the contract and its policy groups. Up to 1,000. ++ message ExpectedMaterial { string name = 1; string material_type = 2; bool optional = 3; string group = 4; } + message MaterialAttributes { string name = 1; string material_type = 2; string value = 3; string digest = 4; bool in_contract = 5; bool added_by_collector = 6; PolicyCounts policies = 7; } -+ message PushAttributes { PolicyCounts policies = 1; repeated string blocking_policies = 2; } + message PolicyCounts { int32 evaluated = 1; int32 passed = 2; int32 violated = 3; int32 skipped = 4; repeated string violated_policies = 5; } +} ``` @@ -168,24 +183,26 @@ $ chainloop workflow run describe --id 7c1e... INF the attestation crafting process is in progress, it has not been received yet ``` -After. JSON output (`-o json`) gets an `events` list with the fields of the API message. It also gets a `progress` object with the materials, the required counts, the attestation policy counts, and the steps. +After. JSON output (`-o json`) gets an `events` list with the fields of the API message. It also gets the `progress` object of `GetProgress`. For each material, it has the requirement, status, value, policy counts, last error, and failed attempts. It also has the required counts and the attestation policy counts. ```console $ chainloop workflow run describe --id 7c1e... -│ State │ in progress │ -│ Running for │ 5m45s │ -Materials (reported progress) 1 of 2 required provided - sbom SBOM_CYCLONEDX_JSON required provided 2 passed (1 failed add) - image CONTAINER_IMAGE required missing - sast-report SARIF optional provided 1 passed, 1 violated - build-log ARTIFACT not in contract -Policies (reported progress) attestation: 2 passed -Timeline - 10:00:02 attestation started 5m43s - 10:02:21 sast-report succeeded - 10:03:10 sbom failed 55s invalid CycloneDX document: missing bomFormat - 10:04:05 sbom succeeded - 10:05:30 build-log succeeded +│ State │ initialized │ +Timeline (reported progress) · started 10:00:02 · running for 5m43s · 1 of 2 required provided · attestation policies: 2 passed +├─ 10:00:02 ✓ initialized contract build rev 3 · GITHUB_ACTION · local state · policies: 2 passed +├─ 10:02:21 ✓ added evidence `sast-report` optional · policies: 1 passed, 1 violated +├─ 10:03:10 ✓ added evidence `sbom` required · policies: 2 passed · 1 failed attempt +│ ├─ 10:03:10 ✗ invalid CycloneDX document: missing bomFormat +│ └─ 10:04:05 ✓ succeeded +├─ 10:05:30 ✓ added evidence `build-log` not in contract +├─ ○ missing evidence `image` required +└─ ● waiting for push +``` + +After the push, the timeline shows as history after the signed attestation. Its last line comes from the closing event: + +```console +└─ 10:08:23 ✓ pushed and stored policies: 3 passed · sha256:4de7a1b2c3d4… ``` R-009 (M2). New command: @@ -211,32 +228,32 @@ R-007. `deployment/chainloop/values.yaml`, rendered into the control plane confi | # | Milestone | You get | Requirements | Depends on | |---|-----------|---------|--------------|------------| -| M1 | Automatic progress | `describe` shows a run in progress: elapsed time, provided and missing materials, policy counts, and the timeline | R-001 to R-008 | none | +| M1 | Automatic progress | `describe` shows a run in progress: elapsed time, provided and missing materials, policy counts, and the timeline | R-002, R-004 to R-008, R-010, R-011 (R-010 and R-011 supersede R-001 and R-003) | none | | M2 | Custom events | A pipeline adds its own steps to the timeline with `chainloop attestation event` | R-009 | M1 | ### M1: Automatic progress -The control plane gets the event table, the write and read calls, the closing events, and the deletion of old events. The CLI records events from `init`, `add`, and `push`, and `describe` shows them. The write call copies `Store`, the read call copies the run view, and the run expiry job also deletes old events. +The control plane gets the event table, the write call, the closing events, and the deletion of old events. `GetProgress` returns the events and the progress. The CLI records events from `init` and `add`, the store closes the timeline, and `describe` shows them. The write call copies `Store`, `GetProgress` copies `View`, and the run expiry job also deletes old events. **Done when:** a CI attestation with a failed and a repeated `add` shows in `describe` as in User-facing changes. The closing event matches the run status after store, reset, and expiry. Tested by the CLI action tests and the control plane integration tests. **Steps**, in build order. Open a step to see what changes and the files it touches.
-01 / 07 · Add the event calls and messages to the API, with the access rules of the run (R-003, R-005, R-008) +01 / 07 · Add the event calls and messages to the API, with the access rules of the run (R-005, R-008, R-011) Add the calls and messages of the API snippet, without the custom type, and with the bounds of each field (spec D-010). Classify each call as shown, so each role and API token has the same access to events as to the run. No new policy is added, so no token policy migration is needed. | New call | Classified as | Copies | |----------|---------------|--------| | `RecordEvent` | exempt from the authz middleware. The existing `AttestationService` rules apply the attestation auth, with no change to the gRPC server. | the classification of `Store` and `Cancel` | -| `ListEvents` | operations map entry with `PolicyWorkflowRunRead` | `View` | +| `GetProgress` | operations map entry with `PolicyWorkflowRunRead` | `View` | | File | Change | |------|--------| | `app/controlplane/api/controlplane/v1/workflow_run.proto` | Add the calls and messages. Run `buf format -w` and `make api`. | | `app/controlplane/api/gen/` | Generated code. Keep `frontend/google/protobuf/descriptor.ts` as on main. | -| `app/controlplane/pkg/authz/authz.go` | Map `/controlplane.v1.WorkflowRunService/ListEvents` to `PolicyWorkflowRunRead`. | +| `app/controlplane/pkg/authz/authz.go` | Map `/controlplane.v1.WorkflowRunService/GetProgress` to `PolicyWorkflowRunRead`. | | `app/controlplane/pkg/authz/authz_consistency_test.go` | Add `RecordEvent` to the exempt list next to `Store` and `Cancel`. |
@@ -244,7 +261,7 @@ Add the calls and messages of the API snippet, without the custom type, and with
02 / 07 · Store events with the run, only while the run is in progress (R-006, R-008) -Add the `WorkflowRunEvent` Ent schema with an edge to the run and cascade delete. Follow the repository rule for indexes: `CREATE INDEX CONCURRENTLY` and `atlas:txmode none`. Add a use case with `Record(ctx, runID, event) (*WorkflowRunEvent, error)`, `List(ctx, runID, afterID)`, and `DeleteOlderThan(ctx, t, limit)`. `Record` locks the run row in a transaction. It rejects a run that is not initialized or that has 1,000 events, then inserts. Both rejections return a new biz `ErrFailedPrecondition`. Add it to the shared error handler of the service layer, so that it maps to the gRPC code `FailedPrecondition`. So no event lands after the closing event. `List` finds the `afterID` event only inside the same run, and returns the oldest first. Run `make generate`, `make migration_sync`, and `wire ./...`. +Add the `WorkflowRunEvent` Ent schema with an edge to the run and cascade delete. Follow the repository rule for indexes: `CREATE INDEX CONCURRENTLY` and `atlas:txmode none`. Add a use case with `Record(ctx, runID, event) (*WorkflowRunEvent, error)`, `List(ctx, runID)`, and `DeleteOlderThan(ctx, t, limit)`. `Record` locks the run row in a transaction. It rejects a run that is not initialized or that has 1,000 events, then inserts. Both rejections return a new biz `ErrFailedPrecondition`. Add it to the shared error handler of the service layer, so that it maps to the gRPC code `FailedPrecondition`. So no event lands after the closing event. `List` returns the events of the run, oldest first. Run `make generate`, `make migration_sync`, and `wire ./...`. | File | Change | |------|--------| @@ -255,7 +272,7 @@ Add the `WorkflowRunEvent` Ent schema with an edge to the run and cascade delete | `app/controlplane/pkg/biz/errors.go` | Add `ErrFailedPrecondition` and `IsErrFailedPrecondition`. | | `app/controlplane/internal/service/service.go` | Map `IsErrFailedPrecondition` to `codes.FailedPrecondition` in the shared error handler. | | `app/controlplane/pkg/biz/biz.go`, `app/controlplane/pkg/data/data.go`, `app/controlplane/cmd/wire_gen.go` | Add the providers, run `wire ./...`. | -| `app/controlplane/pkg/data/workflowrunevent_integration_test.go` | Add tests: finished run rejected, limit reached, order, `afterID` of another run returns nothing, cascade delete. | +| `app/controlplane/pkg/data/workflowrunevent_integration_test.go` | Add tests: finished run rejected, limit reached, order, the events of another run never show, cascade delete. |
@@ -280,14 +297,14 @@ Wrap the status update and the insert of the closing `chainloop.attestation` eve
-04 / 07 · Serve the write and read calls with the checks of Store and View (R-003) +04 / 07 · Serve the write call with the checks of Store, and GetProgress with the checks of View (R-011) -`RecordEvent` copies the checks of `Store` in the same order. Then it sets the source to CLI. It accepts the types ATTESTATION, MATERIAL, and PUSH, with a key that starts with `chainloop.`, and an attributes field that matches the type. `ListEvents` copies the checks of `View`. +`RecordEvent` copies the checks of `Store` in the same order. Then it sets the source to CLI. It accepts the types ATTESTATION and MATERIAL, with a key that starts with `chainloop.`, and an attributes field that matches the type. `GetProgress` copies the checks of `View`. It returns the events of the run, and, for a run in progress, the progress that `BuildWorkflowRunProgress` builds. The expected materials come from the start event, or else from the contract version. `View` does not change. -| Caller | `RecordEvent` | `ListEvents` | -|--------|---------------|--------------| +| Caller | `RecordEvent` | `GetProgress` | +|--------|---------------|--------| | Any caller that `Store` accepts for the run | allowed | allowed | -| Token pinned to another workflow | denied | as for `View` | +| Token pinned to another workflow | denied | allowed, as `View` allows the project of the token | | API token scoped to another project | denied | denied | | User who can only view the project | denied | allowed | | User with no access to the project | denied | denied | @@ -296,8 +313,9 @@ Wrap the status update and the insert of the closing `chainloop.attestation` eve | File | Change | |------|--------| | `app/controlplane/internal/service/attestation.go` | Add `RecordEvent`. | -| `app/controlplane/internal/service/workflowrun.go` | Add `ListEvents`. | -| `app/controlplane/internal/service/workflowrunevent_integration_test.go` | Add an integration table test for each row, and for a type that does not match its attributes. For each row, check that `RecordEvent` gives the same result as `Store`, and `ListEvents` the same result as `View`. | +| `app/controlplane/internal/service/workflowrun.go` | Add `GetProgress`. | +| `app/controlplane/pkg/biz/workflowrunprogress.go` | `BuildWorkflowRunProgress`: one row for each expected material, the last successful add for the provided state, failed attempts, groups counted once. | +| `app/controlplane/internal/service/workflowrunevent_integration_test.go` | Add an integration table test for each row, and for a type that does not match its attributes. For each row, check that `RecordEvent` gives the same result as `Store`, and `GetProgress` the same result as `View`. Check that `GetProgress` returns the events and the progress of a run in progress. |
@@ -320,9 +338,9 @@ Add a retention duration to the attestations section of the config, with a defau
-06 / 07 · Record events from init, add, and push, so the run shows its progress (R-001, R-002, R-005) +06 / 07 · Record events from init and add, so the run shows its progress (R-010, R-002, R-005) -Add a recorder to the CLI actions: `Record(ctx, event) error` sends with a 2-second timeout. It cuts the message to 1 KB, the value to 256 characters, and each list of policy names to 100 names. The callers in M1 do not stop on its error. At the end of `init`, after the collectors and the init policies, `init` records the start with the init policy counts. Then it records the materials that collectors added. `add` records success or the error. An `add` that expands an archive into more than 20 materials records one summary event, as the spec describes. A smaller archive records one event for each material. Both also record an event for the evidence material of the archive file (`-archive`). After the push policies and the dry-run return, and before `Store`, `push` records `chainloop.push`. It counts all attestation evaluations in the state, from `init` and from `push`. The status is failed when a gate that is not bypassed blocks the push, with the blocking policies. Else it is succeeded. Move the gate check from the push command into the push action, as a function that returns the blocking policies. The action and the command then use the same check. A dry run records no push event. The policy counts come from the evaluations in the crafting state. +Add a recorder to the CLI actions: `Record(ctx, event) error` sends with a 2-second timeout. It cuts the message to 1 KB, the value to 256 characters, and each list of policy names to 100 names. The callers in M1 do not stop on its error. At the end of `init`, after the collectors and the init policies, `init` records the start with the init policy counts and the expected materials. These are the materials of the contract and its policy groups, as `init` resolves them, up to 1,000. Then it records the materials that collectors added. `add` records success or the error. An `add` that expands an archive into more than 20 materials records one summary event, as the spec describes. A smaller archive records one event for each material. Both also record an event for the evidence material of the archive file (`-archive`). `push` records no event: the closing event of the store shows it (spec D-011). The policy counts come from the evaluations in the crafting state. | Answer of the control plane | Recorder | |-----------------------------|----------| @@ -333,23 +351,24 @@ Add a recorder to the CLI actions: `Record(ctx, event) error` sends with a 2-sec | File | Change | |------|--------| | `app/cli/pkg/action/runevents.go` | New recorder and the builders for each event type. | -| `app/cli/pkg/action/attestation_init.go`, `attestation_add.go`, `attestation_push.go` | Record after each action, and the push event before `Store`. Add the gate function to `attestation_push.go`. | -| `app/cli/cmd/attestation_push.go` | Call the gate function of the action in `validatePolicyEnforcement`. | -| `app/cli/pkg/action/runevents_test.go` | Add table tests: limits cut, each answer row, a failed send keeps the result, no env vars or annotations in the event. Also test a blocked push, a bypassed gate, and a dry run. Test an archive above and at 20 materials, each with the event of the archive file. | +| `app/cli/pkg/action/attestation_init.go`, `attestation_add.go` | Record after each action of `init` and `add`. | +| `app/cli/pkg/action/runevents_test.go` | Add table tests: limits cut, each answer row, a failed send keeps the result, no env vars or annotations in the event. Test an archive above and at 20 materials, each with the event of the archive file. Test that the start event lists the expected materials. |
-07 / 07 · Show the progress in workflow run describe (R-004) +07 / 07 · Show the progress in workflow run describe (R-004, R-011) -`describe` calls `ListEvents` for each run. When the run state is initialized, it joins the contract materials of the run view with the latest material event for each `MaterialAttributes.name`. It adds the other materials as not in the contract. It takes the attestation policy counts from the latest `chainloop.push` event, or else from the start event. It groups the timeline by key, with durations. For a finished run, it prints the timeline after the attestation. Any error from `ListEvents` keeps the current output, and `describe` does not fail. `Unimplemented` gives a debug log, and other errors give a warning. +`describe` calls `GetProgress` after `View`, and shows the events and the progress that it returns, with no logic of its own for the checklist (spec D-012). It shows the timeline as a tree: one line for each step, with the events of a repeated step below it. A step shows its last successful add, with the failed attempts below it, as the progress does. The materials that the progress lists as missing show as "missing evidence" lines. The last line is "pushed and stored" from the closing event (spec D-011). It shows the policy status of the signed attestation and the short digest. A run in progress ends with "waiting for push", and a reset or expired run ends with its status and message. For a finished run, it prints the timeline after the attestation. A run with no events from the CLI, as from an older CLI, shows no timeline. Any error from `GetProgress` keeps the current output, and `describe` does not fail. `Unimplemented` gives a debug log, and other errors give a warning. | File | Change | |------|--------| -| `app/cli/pkg/action/workflow_run_describe.go` | Call `ListEvents`, build the checklist and the steps. | -| `app/cli/cmd/workflow_workflow_run_describe.go` | Print the materials, policies, and timeline. | -| `app/cli/pkg/action/workflow_run_describe_test.go` | Add table tests: failed then repeated add, material not in the contract, required material missing, expired run, `Unimplemented`, other error. | -| `app/cli/pkg/action/runevents_compat_test.go` | Add a test with an in-process gRPC server that has the services but not the new calls, as an older control plane. `Record` returns `Unimplemented`, and the `add` and `describe` callers succeed. | +| `app/cli/pkg/action/workflow_run_describe.go` | Call `GetProgress`, and map its events and progress. | +| `app/cli/cmd/workflow_workflow_run_describe.go` | Print the timeline after the run table, and after the attestation for a finished run. | +| `app/cli/cmd/workflow_run_timeline.go` | Render the timeline tree from the events and the progress. | +| `app/cli/cmd/workflow_run_timeline_test.go` | Add tests of the exact output: run in progress, a failed add after a successful one, stored run, blocked run, expired run. | +| `app/cli/pkg/action/workflow_run_describe_test.go` | Add table tests: a run in progress with its progress, an expired run, a run with no events, `Unimplemented`, other error. | +| `app/cli/pkg/action/runevents_compat_test.go` | Add a test with an in-process gRPC server that has the services but not the new calls, as an older control plane. `Record` and `GetProgress` return `Unimplemented`, and the `add` and `describe` callers succeed. |
@@ -392,7 +411,7 @@ None. | The run page in the UI | The UI is in another repository (spec Non-Goal). | A ticket in the platform repository | | Expiry on inactivity, events on the audit bus | Spec Non-Goals. | none | -Not checked: the load of 1,000 events for each run on the largest installs. Also not checked: whether the new call can serve the poll rate of the platform UI. +Not checked: the load of 1,000 events for each run on the largest installs. Also not checked: whether `GetProgress`, with up to 1,000 events and the progress, can serve the poll rate of the platform UI. | Risk | Mitigation | |------|------------| diff --git a/docs/specs/issue-3825-attestation-progress-events.md b/docs/specs/issue-3825-attestation-progress-events.md index 8ca4c9278..49a09ab86 100644 --- a/docs/specs/issue-3825-attestation-progress-events.md +++ b/docs/specs/issue-3825-attestation-progress-events.md @@ -54,20 +54,24 @@ While an attestation is in progress, the control plane knows only that its workf ## Requirements -### R-001: Automatic events for every attestation -The CLI MUST record a run event at each action of the attestation, with no new flags, in local and remote state modes. The actions are: -- the start of the attestation, at the end of `init`, with the results of the attestation policies of `init` -- each material that a collector adds at `init` -- each `add` that succeeds or fails. An `add` that expands an archive into more than 20 materials records one summary event and the event of the archive file (see Proposal). -- the `push`, before the control plane stores the attestation. It has the results of all attestation policies of the run, from `init` and from `push`. The event fails when a policy gate blocks the push. The control plane stores a blocked push as today, and then closes the attestation (R-006). -- Done when: the run of a regular attestation (init, three adds, push) has the events of the Appendix example. +### ~~R-001: Automatic events for every attestation~~ +Superseded by R-010. + +~~The CLI MUST record a run event at each action of the attestation, with no new flags, in local and remote state modes. The actions are:~~ +- ~~the start of the attestation, at the end of `init`, with the results of the attestation policies of `init`~~ +- ~~each material that a collector adds at `init`~~ +- ~~each `add` that succeeds or fails. An `add` that expands an archive into more than 20 materials records one summary event and the event of the archive file (see Proposal).~~ +- ~~the `push`, before the control plane stores the attestation. It has the results of all attestation policies of the run, from `init` and from `push`. The event fails when a policy gate blocks the push. The control plane stores a blocked push as today, and then closes the attestation (R-006).~~ +- ~~Done when: the run of a regular attestation (init, three adds, push) has the events of the Appendix example.~~ ### R-002: Event recording never breaks the attestation A failure to record an event MUST NOT fail or stop the attestation. Each call has a timeout of 2 seconds. When the control plane does not know the call, the CLI stops sending events for the rest of the command, with no warning. - Done when: an attestation against a control plane that rejects or does not support events completes with the same result as today. -### R-003: Read the events of a run -The control plane MUST return the events of a run, oldest first. It uses the same permissions as the run view. A caller can ask only for events newer than one that it already has, so the UI follow-up needs no later control plane change. +### ~~R-003: Read the events of a run~~ +Superseded by R-011. + +~~The control plane MUST return the events of a run, oldest first. It uses the same permissions as the run view. A caller can ask only for events newer than one that it already has, so the UI follow-up needs no later control plane change.~~ ### R-004: Describe a run in progress For a run in progress, `chainloop workflow run describe` MUST show: @@ -96,6 +100,17 @@ The control plane MUST reject an event that goes past a limit. The limits are 1, ### R-009: Custom events `chainloop attestation event --status --message ` MUST record a custom event on the run of the attestation in progress. The status is started, succeeded, failed, or canceled. The command finds the run in the same way as the other attestation commands. A custom key MUST use the format of annotation names: letters, digits, `_`, and `-`. A custom key cannot hold a dot, so it never matches an automatic `chainloop.` key. When the command cannot record the event, for example against an older control plane, it shows a warning and exits with success. A progress signal never breaks a pipeline. +### R-010: Automatic events for every attestation +Supersedes R-001. The CLI MUST record a run event at each action of the attestation, with no new flags, in local and remote state modes. The CLI records no event for the `push`. The closing event of the store shows it, and the signed attestation holds its policy results (D-011). The actions are: +- the start of the attestation, at the end of `init`, with the results of the attestation policies of `init` +- each material that a collector adds at `init` +- each `add` that succeeds or fails. An `add` that expands an archive into more than 20 materials records one summary event and the event of the archive file (see Proposal). +- Done when: the run of a regular attestation (init, three adds, push) has the events of the Appendix example, with no `chainloop.push` event. + +### R-011: Read the progress and the events of a run +Supersedes R-003. A read call next to the run view MUST return the events of a run, oldest first. It has the permissions of the run view. For a run in progress, the call MUST also return the progress of the run. The progress has one row for each expected material, with its requirement and its status: missing, provided, or failed. It also has the required counts and the attestation policy results of `init`. The control plane builds the progress, so that the CLI, the UI, and other tools show it with no logic of their own (D-012). The expected materials are the ones that `init` resolves, from the contract and its policy groups. The start event lists them. A run whose start event has no list uses the materials of its contract. +- Done when: a material that a policy group requires shows as missing until it is added. A failed `add` after a successful one keeps the material as provided, with the error. + ## Constraints - Open source: the feature works in the control plane and the CLI alone. It does not need the event bus or any commercial component. @@ -109,17 +124,18 @@ The control plane MUST reject an event that goes past a limit. The limits are 1, **Run events.** A run event has these fields: - a time, set by the control plane when it receives the event - a source: the CLI or the control plane -- a type: attestation, material, push, or custom +- ~~a type: attestation, material, push, or custom~~ +- a type: attestation, material, or custom (D-011) - a key - a status: started, succeeded, failed, or canceled - an optional message - typed attributes for its type -The key groups events into a step. `chainloop.attestation` runs from `init` to the end of the run. `chainloop.material.` holds each `add` of one material. A failed `add` with no material name uses the key `chainloop.material`. `chainloop.push` holds the push. A blocked push has the names of the blocking policies, and the message `blocked by policy gates: `. The policy results go in the event of the action that evaluates them. Material policies go in the material event. The start event holds the attestation policies of `init`. The push event holds all attestation policies of the run. The status describes the step, not the policy result. When the CLI adds a material that has a policy violation, the status is succeeded, and the attributes hold the policy counts. Automatic events that succeed have no message, with one exception. An `add` can expand an archive (an SBOM or SARIF zip or tar) into more than 20 materials. It then records one succeeded event on `chainloop.material.`, with the message " materials from the archive". N counts the expanded materials, not the archive file. With no `--name`, the name is the archive file name without its archive extension (`.zip`, `.tar`, `.tar.gz`, or `.tgz`). The value is the archive file name, and the type is the kind of the `add`. The policy counts are the sum for all the materials, and each violated policy shows once. An archive with 20 materials or fewer records one event for each material. In both cases, the CLI also records one event for the archive file itself, which the CLI keeps as an evidence material. A large archive can have up to 10,000 entries, so one event for each would use up the limit of the run (R-008). The CLI and the UI build the text from the type and the attributes. The Appendix lists the events of a regular attestation. +The key groups events into a step. `chainloop.attestation` runs from `init` to the end of the run. `chainloop.material.` holds each `add` of one material. A failed `add` with no material name uses the key `chainloop.material`. ~~`chainloop.push` holds the push. A blocked push has the names of the blocking policies, and the message `blocked by policy gates: `.~~ The closing event of the store ends the push (D-011). The policy results go in the event of the action that evaluates them. Material policies go in the material event. The start event holds the attestation policies of `init`. ~~The push event holds all attestation policies of the run.~~ The signed attestation holds the final policy results (D-011). The status describes the step, not the policy result. When the CLI adds a material that has a policy violation, the status is succeeded, and the attributes hold the policy counts. Automatic events that succeed have no message, with one exception. An `add` can expand an archive (an SBOM or SARIF zip or tar) into more than 20 materials. It then records one succeeded event on `chainloop.material.`, with the message " materials from the archive". N counts the expanded materials, not the archive file. With no `--name`, the name is the archive file name without its archive extension (`.zip`, `.tar`, `.tar.gz`, or `.tgz`). The value is the archive file name, and the type is the kind of the `add`. The policy counts are the sum for all the materials, and each violated policy shows once. An archive with 20 materials or fewer records one event for each material. In both cases, the CLI also records one event for the archive file itself, which the CLI keeps as an evidence material. A large archive can have up to 10,000 entries, so one event for each would use up the limit of the run (R-008). The CLI and the UI build the text from the type and the attributes. The Appendix lists the events of a regular attestation. -**CLI.** The attestation commands record events through the new write call of the attestation API. That API already holds the run-scoped authentication of the CI token. Each call is best effort (R-002). The CLI sends each event when the action happens. It does not batch events, so the receive time stays close to the action time. `chainloop workflow run describe` reads the run, its contract, and its events. It builds the list of provided and missing materials from the contract (the run view already returns it) and the material events. So the events are the only new data. +**CLI.** The attestation commands record events through the new write call of the attestation API. That API already holds the run-scoped authentication of the CI token. Each call is best effort (R-002). The CLI sends each event when the action happens. It does not batch events, so the receive time stays close to the action time. ~~`chainloop workflow run describe` reads the run, its contract, and its events. It builds the list of provided and missing materials from the contract (the run view already returns it) and the material events. So the events are the only new data.~~ `chainloop workflow run describe` shows the progress and the events that the new read call returns (D-012). -**Control plane.** The control plane stores events with the run, in its own database (D-002). It closes the timeline (R-006), deletes old events (R-007), and returns events through a new read call (R-003, D-007). +**Control plane.** The control plane stores events with the run, in its own database (D-002). It closes the timeline (R-006), deletes old events (R-007), and ~~returns events through a new read call (R-003, D-007).~~ It builds the progress of a run in progress and returns it with the events through a new read call (R-011, D-012). **UI (described, built in a follow-up).** The run page shows the same data as `describe` in place of its spinner. It polls the read call while the run is in progress. @@ -141,7 +157,7 @@ sequenceDiagram CP-->>U: signed attestation + timeline as history ``` -Dashed arrows are best effort. A failed event does not stop the attestation. +Dashed arrows are best effort. A failed event does not stop the attestation. Since D-011, the CLI sends no push event. Since D-012, "list events" also returns the progress. ## Decision Record @@ -190,12 +206,14 @@ Each event type has a fixed set of attributes that the control plane checks. The - A free JSON map: no API change for new types, but no check of the content. - Source: drafting -### D-007: A separate read call for events -The run read API gets a new call for the events of a run (R-003). The run view call does not change. -- Why: the run view also returns the full attestation. A client that polls every few seconds while a run is in progress must not get the attestation again each time. -- Alternatives considered: - - Add the events to the run view: one call, but heavy polling. -- Source: drafting +### ~~D-007: A separate read call for events~~ +Superseded by D-012. + +~~The run read API gets a new call for the events of a run (R-003). The run view call does not change.~~ +- ~~Why: the run view also returns the full attestation. A client that polls every few seconds while a run is in progress must not get the attestation again each time.~~ +- ~~Alternatives considered:~~ + - ~~Add the events to the run view: one call, but heavy polling.~~ +- ~~Source: drafting~~ ### D-008: The limits of R-008 stay as proposed The limits are 1,000 events for each run, 64 characters for a custom key, and 1 KB for a message. @@ -218,13 +236,29 @@ The control plane rejects an event with a field that goes past its bound (R-008) - A bound on the size of the full event only: one check, but the client cannot see which field goes past it. - Source: implementation review of #3859 +### D-011: No push event, the store closes the step +The CLI records no `chainloop.push` event. The closing event of the store (R-006) is the end of the push for the user. The policy results and the gate result come from the signed attestation, which `describe` and the UI already read for a stored run. The event types are attestation, material, and custom. +- Why: the push event and the closing event described one step, "pushed and stored", in two events. The signed attestation holds the final policy results. A copy in an event can only disagree with it, for example after a retry of the push. +- Alternatives considered: + - Keep the push event, and show it and the closing event as one line: two events for one step. + - Copy the policy summary of the attestation to the closing event: a second copy of data that the attestation already has. +- Source: implementation of #3859 + +### D-012: A separate read call returns the progress and the events +Supersedes D-007. A new call of the run read API returns the events and, for a run in progress, the progress (R-011). The control plane builds the progress. The run view call does not change. +- Why: a client polls while a run is in progress. It gets the progress and the timeline, not the run and its attestation again each time. The run view stays as it is for its other callers. The control plane builds the progress once, so all clients show the same result. No client joins the contract and the events. +- Alternatives considered: + - A read call for events only, with the progress built by each client (D-007): each client repeats the same join. Also, the CLI cannot resolve the policy groups of the contract with a user token. + - Add the progress and the events to the run view: one call, but every caller of the run view gets the events. +- Source: implementation review of #3859 + ## Open Questions None. ## Milestones -1. **Automatic progress.** Automatic events (R-001, R-002, R-005, R-006), the read call (R-003), `describe` for runs in progress (R-004), retention (R-007), and limits (R-008). +1. **Automatic progress.** Automatic events (R-001, R-002, R-005, R-006), the read call (R-003), `describe` for runs in progress (R-004), retention (R-007), and limits (R-008). R-010 supersedes R-001, and R-011 supersedes R-003. 2. **Custom events.** `chainloop attestation event` (R-009). ## Risks @@ -235,9 +269,9 @@ None. | Material values stay in events of runs that never finish. Today the control plane clears their state. | Values are cut to 256 characters and deleted after the retention period. Run viewers can already read the same values in stored attestations. | | The error text of a failed `add` quotes part of a file. | The 1 KB message limit (D-009). | | Event volume grows the database. | The limit for each run and the retention period. | -| A run with about 1,000 separate `add` commands fills the limit of 1,000 events. The control plane then rejects the later events, also the push event, and the CLI shows a warning. | Accepted. The limit applies only to the events of the client. The store and the closing event of the control plane do not depend on events. | +| A run with about 1,000 separate `add` commands fills the limit of 1,000 events. The control plane then rejects the later events~~, also the push event~~, and the CLI shows a warning (D-011). | Accepted. The limit applies only to the events of the client. The store and the closing event of the control plane do not depend on events. | | The start event comes at the end of `init`, so its time is a few seconds after the start of the run. | The run keeps its exact creation time. | -| The push event shows the gate result, not the store result. A retry of the push records it again. A store that fails leaves a succeeded push event on a run in progress. | `describe` uses the latest push event. The closing event of the control plane shows the store (R-006). | +| Superseded by D-011. ~~The push event shows the gate result, not the store result. A retry of the push records it again. A store that fails leaves a succeeded push event on a run in progress.~~ | ~~`describe` uses the latest push event. The closing event of the control plane shows the store (R-006).~~ | ## Appendix: Events of a regular attestation @@ -250,7 +284,9 @@ Contract: `image` (container image, required), `sbom` (CycloneDX, required), and | 10:03:10 | cli | material | `chainloop.material.sbom` | failed | invalid CycloneDX document: missing bomFormat | CycloneDX, value `sbom.json` | | 10:04:05 | cli | material | `chainloop.material.sbom` | succeeded | | CycloneDX, value `sbom.json`, digest, in contract, 2 evaluated, 2 passed, 0 violated, 0 skipped | | 10:05:40 | cli | material | `chainloop.material.image` | succeeded | | container image, value `ghcr.io/example/app:1.4.2`, digest, in contract, 1 evaluated, 1 passed, 0 violated, 0 skipped | -| 10:06:00 | cli | push | `chainloop.push` | succeeded | | 3 evaluated, 3 passed, 0 violated, 0 skipped | +| ~~10:06:00~~ | ~~cli~~ | ~~push~~ | ~~`chainloop.push`~~ | ~~succeeded~~ | | ~~3 evaluated, 3 passed, 0 violated, 0 skipped~~ | | 10:06:03 | control plane | attestation | `chainloop.attestation` | succeeded | | attestation digest | -When a policy gate blocks the push, the push event is failed, with the blocking policies. The control plane still stores the attestation, so the closing event is succeeded (R-006). Reset and expiry follow R-006. +~~When a policy gate blocks the push, the push event is failed, with the blocking policies. The control plane still stores the attestation, so the closing event is succeeded (R-006). Reset and expiry follow R-006.~~ + +Since D-011, the CLI records no push event (struck-through row). When a policy gate blocks the push, the control plane still stores the attestation, so the closing event is succeeded (R-006). The signed attestation shows the block. Reset and expiry follow R-006.