From f330ca5b71511daacbc65ea8ba12666655c9fb35 Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Mon, 30 Nov 2026 20:20:25 +0100 Subject: [PATCH 01/20] feat(controlplane): store workflow run progress events Add the RecordEvent and ListEvents calls, the workflow_run_events table, and the closing event that the control plane records when it stores, cancels, or expires a run. RecordEvent applies the checks of Store, and ListEvents the checks of View, so no new policy is added. Refs #3825 (M1, R-003, R-005, R-006, R-008) Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1cdb3220-119c-4a14-ac50-52d5437ee4eb --- .../api/controlplane/v1/workflow_run.pb.go | 1430 ++++++++++++--- .../api/controlplane/v1/workflow_run.proto | 109 ++ .../controlplane/v1/workflow_run_grpc.pb.go | 82 +- .../frontend/controlplane/v1/workflow_run.ts | 1609 +++++++++++++++-- ...nServiceRecordEventRequest.jsonschema.json | 26 + ...ationServiceRecordEventRequest.schema.json | 26 + ...ServiceRecordEventResponse.jsonschema.json | 8 + ...tionServiceRecordEventResponse.schema.json | 8 + ...vent.AttestationAttributes.jsonschema.json | 65 + ...RunEvent.AttestationAttributes.schema.json | 65 + ...unEvent.MaterialAttributes.jsonschema.json | 43 + ...lowRunEvent.MaterialAttributes.schema.json | 43 + ...unEvent.PoliciesAttributes.jsonschema.json | 16 + ...lowRunEvent.PoliciesAttributes.schema.json | 16 + ...kflowRunEvent.PolicyCounts.jsonschema.json | 43 + ....WorkflowRunEvent.PolicyCounts.schema.json | 43 + ...lplane.v1.WorkflowRunEvent.jsonschema.json | 98 + ...ntrolplane.v1.WorkflowRunEvent.schema.json | 98 + ...unServiceListEventsRequest.jsonschema.json | 29 + ...lowRunServiceListEventsRequest.schema.json | 29 + ...nServiceListEventsResponse.jsonschema.json | 15 + ...owRunServiceListEventsResponse.schema.json | 15 + app/controlplane/cmd/wire_gen.go | 4 + .../internal/service/attestation.go | 40 + app/controlplane/internal/service/service.go | 2 +- .../internal/service/workflowrun.go | 198 ++ .../workflowrunevent_integration_test.go | 384 ++++ app/controlplane/pkg/authz/authz.go | 5 +- .../pkg/authz/authz_consistency_test.go | 1 + app/controlplane/pkg/biz/biz.go | 1 + app/controlplane/pkg/biz/errors.go | 18 + .../pkg/biz/testhelpers/database.go | 2 + .../pkg/biz/testhelpers/wire_gen.go | 4 + app/controlplane/pkg/biz/workflowrunevent.go | 308 ++++ .../pkg/biz/workflowrunevent_test.go | 145 ++ app/controlplane/pkg/data/data.go | 1 + app/controlplane/pkg/data/ent/client.go | 179 +- app/controlplane/pkg/data/ent/ent.go | 2 + app/controlplane/pkg/data/ent/hook/hook.go | 12 + .../ent/migrate/migrations/20261130191056.sql | 20 + .../pkg/data/ent/migrate/migrations/atlas.sum | 3 +- .../pkg/data/ent/migrate/schema.go | 40 + app/controlplane/pkg/data/ent/mutation.go | 896 ++++++++- .../pkg/data/ent/predicate/predicate.go | 3 + app/controlplane/pkg/data/ent/runtime.go | 11 + .../pkg/data/ent/schema/workflowrun.go | 2 + .../pkg/data/ent/schema/workflowrunevent.go | 70 + app/controlplane/pkg/data/ent/tx.go | 3 + app/controlplane/pkg/data/ent/workflowrun.go | 18 +- .../pkg/data/ent/workflowrun/where.go | 23 + .../pkg/data/ent/workflowrun/workflowrun.go | 30 + .../pkg/data/ent/workflowrun_create.go | 32 + .../pkg/data/ent/workflowrun_query.go | 76 +- .../pkg/data/ent/workflowrun_update.go | 163 ++ .../pkg/data/ent/workflowrunevent.go | 219 +++ .../pkg/data/ent/workflowrunevent/where.go | 416 +++++ .../ent/workflowrunevent/workflowrunevent.go | 164 ++ .../pkg/data/ent/workflowrunevent_create.go | 660 +++++++ .../pkg/data/ent/workflowrunevent_delete.go | 88 + .../pkg/data/ent/workflowrunevent_query.go | 657 +++++++ .../pkg/data/ent/workflowrunevent_update.go | 225 +++ app/controlplane/pkg/data/workflowrun.go | 47 +- app/controlplane/pkg/data/workflowrunevent.go | 183 ++ .../data/workflowrunevent_integration_test.go | 346 ++++ 64 files changed, 9175 insertions(+), 442 deletions(-) create mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.AttestationServiceRecordEventRequest.jsonschema.json create mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.AttestationServiceRecordEventRequest.schema.json create mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.AttestationServiceRecordEventResponse.jsonschema.json create mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.AttestationServiceRecordEventResponse.schema.json create mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.AttestationAttributes.jsonschema.json create mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.AttestationAttributes.schema.json create mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.MaterialAttributes.jsonschema.json create mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.MaterialAttributes.schema.json create mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PoliciesAttributes.jsonschema.json create mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PoliciesAttributes.schema.json create mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PolicyCounts.jsonschema.json create mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PolicyCounts.schema.json create mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.jsonschema.json create mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.schema.json create mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceListEventsRequest.jsonschema.json create mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceListEventsRequest.schema.json create mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceListEventsResponse.jsonschema.json create mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceListEventsResponse.schema.json create mode 100644 app/controlplane/internal/service/workflowrunevent_integration_test.go create mode 100644 app/controlplane/pkg/biz/workflowrunevent.go create mode 100644 app/controlplane/pkg/biz/workflowrunevent_test.go create mode 100644 app/controlplane/pkg/data/ent/migrate/migrations/20261130191056.sql create mode 100644 app/controlplane/pkg/data/ent/schema/workflowrunevent.go create mode 100644 app/controlplane/pkg/data/ent/workflowrunevent.go create mode 100644 app/controlplane/pkg/data/ent/workflowrunevent/where.go create mode 100644 app/controlplane/pkg/data/ent/workflowrunevent/workflowrunevent.go create mode 100644 app/controlplane/pkg/data/ent/workflowrunevent_create.go create mode 100644 app/controlplane/pkg/data/ent/workflowrunevent_delete.go create mode 100644 app/controlplane/pkg/data/ent/workflowrunevent_query.go create mode 100644 app/controlplane/pkg/data/ent/workflowrunevent_update.go create mode 100644 app/controlplane/pkg/data/workflowrunevent.go create mode 100644 app/controlplane/pkg/data/workflowrunevent_integration_test.go diff --git a/app/controlplane/api/controlplane/v1/workflow_run.pb.go b/app/controlplane/api/controlplane/v1/workflow_run.pb.go index 529777e3a..92ee26b56 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,162 @@ 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{19, 0} +} + +type WorkflowRunEvent_Type int32 + +const ( + WorkflowRunEvent_TYPE_UNSPECIFIED WorkflowRunEvent_Type = 0 + WorkflowRunEvent_TYPE_ATTESTATION WorkflowRunEvent_Type = 1 + WorkflowRunEvent_TYPE_MATERIAL WorkflowRunEvent_Type = 2 + WorkflowRunEvent_TYPE_POLICIES WorkflowRunEvent_Type = 3 +) + +// Enum value maps for WorkflowRunEvent_Type. +var ( + WorkflowRunEvent_Type_name = map[int32]string{ + 0: "TYPE_UNSPECIFIED", + 1: "TYPE_ATTESTATION", + 2: "TYPE_MATERIAL", + 3: "TYPE_POLICIES", + } + WorkflowRunEvent_Type_value = map[string]int32{ + "TYPE_UNSPECIFIED": 0, + "TYPE_ATTESTATION": 1, + "TYPE_MATERIAL": 2, + "TYPE_POLICIES": 3, + } +) + +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{19, 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{19, 2} +} + 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 +1109,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 +1143,136 @@ 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 { +func (x *AttestationServiceRecordEventRequest) GetWorkflowRunId() string { if x != nil { - return x.WorkflowName + return x.WorkflowRunId } return "" } -func (x *WorkflowRunServiceListRequest) GetProjectName() string { +func (x *AttestationServiceRecordEventRequest) GetEvent() *WorkflowRunEvent { if x != nil { - return x.ProjectName + return x.Event } - return "" + return nil } -func (x *WorkflowRunServiceListRequest) GetStatus() RunStatus { - if x != nil { - return x.Status - } - return RunStatus_RUN_STATUS_UNSPECIFIED +type AttestationServiceRecordEventResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } -// Deprecated: Marked as deprecated in controlplane/v1/workflow_run.proto. -func (x *WorkflowRunServiceListRequest) GetProjectVersion() string { - if x != nil { - return x.ProjectVersion - } - 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) } -func (x *WorkflowRunServiceListRequest) GetProjectVersionName() string { - if x != nil { - return x.ProjectVersionName - } - return "" +func (x *AttestationServiceRecordEventResponse) String() string { + return protoimpl.X.MessageStringOf(x) } -// Deprecated: Marked as deprecated in controlplane/v1/workflow_run.proto. -func (x *WorkflowRunServiceListRequest) GetPolicyViolations() PolicyViolationsFilter { +func (*AttestationServiceRecordEventResponse) ProtoMessage() {} + +func (x *AttestationServiceRecordEventResponse) ProtoReflect() protoreflect.Message { + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[16] if x != nil { - return x.PolicyViolations + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms } - return PolicyViolationsFilter_POLICY_VIOLATIONS_FILTER_UNSPECIFIED + return mi.MessageOf(x) } -func (x *WorkflowRunServiceListRequest) GetPolicyStatus() PolicyStatusFilter { +// Deprecated: Use AttestationServiceRecordEventResponse.ProtoReflect.Descriptor instead. +func (*AttestationServiceRecordEventResponse) Descriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{16} +} + +type WorkflowRunServiceListEventsRequest 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"` + // Optional. Return only the events recorded after this one. + AfterEventId string `protobuf:"bytes,2,opt,name=after_event_id,json=afterEventId,proto3" json:"after_event_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *WorkflowRunServiceListEventsRequest) Reset() { + *x = WorkflowRunServiceListEventsRequest{} + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[17] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *WorkflowRunServiceListEventsRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WorkflowRunServiceListEventsRequest) ProtoMessage() {} + +func (x *WorkflowRunServiceListEventsRequest) ProtoReflect() protoreflect.Message { + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[17] if x != nil { - return x.PolicyStatus + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms } - return PolicyStatusFilter_POLICY_STATUS_FILTER_UNSPECIFIED + return mi.MessageOf(x) } -func (x *WorkflowRunServiceListRequest) GetPolicyGates() PolicyGatesFilter { +// Deprecated: Use WorkflowRunServiceListEventsRequest.ProtoReflect.Descriptor instead. +func (*WorkflowRunServiceListEventsRequest) Descriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{17} +} + +func (x *WorkflowRunServiceListEventsRequest) GetWorkflowRunId() string { if x != nil { - return x.PolicyGates + return x.WorkflowRunId } - return PolicyGatesFilter_POLICY_GATES_FILTER_UNSPECIFIED + return "" } -func (x *WorkflowRunServiceListRequest) GetPagination() *CursorPaginationRequest { +func (x *WorkflowRunServiceListEventsRequest) GetAfterEventId() string { if x != nil { - return x.Pagination + return x.AfterEventId } - return nil + return "" } -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"` +type WorkflowRunServiceListEventsResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Events []*WorkflowRunEvent `protobuf:"bytes,1,rep,name=events,proto3" json:"events,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } -func (x *WorkflowRunServiceListResponse) Reset() { - *x = WorkflowRunServiceListResponse{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[16] +func (x *WorkflowRunServiceListEventsResponse) Reset() { + *x = WorkflowRunServiceListEventsResponse{} + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[18] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } -func (x *WorkflowRunServiceListResponse) String() string { +func (x *WorkflowRunServiceListEventsResponse) String() string { return protoimpl.X.MessageStringOf(x) } -func (*WorkflowRunServiceListResponse) ProtoMessage() {} +func (*WorkflowRunServiceListEventsResponse) ProtoMessage() {} -func (x *WorkflowRunServiceListResponse) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[16] +func (x *WorkflowRunServiceListEventsResponse) 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 { @@ -1116,55 +1283,56 @@ 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} -} - -func (x *WorkflowRunServiceListResponse) GetResult() []*WorkflowRunItem { - if x != nil { - return x.Result - } - return nil +// Deprecated: Use WorkflowRunServiceListEventsResponse.ProtoReflect.Descriptor instead. +func (*WorkflowRunServiceListEventsResponse) Descriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{18} } -func (x *WorkflowRunServiceListResponse) GetPagination() *CursorPaginationResponse { +func (x *WorkflowRunServiceListEventsResponse) GetEvents() []*WorkflowRunEvent { if x != nil { - return x.Pagination + return x.Events } return nil } -type WorkflowRunServiceViewRequest struct { +// 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"` - // It can search by either ID or digest - // - // Types that are valid to be assigned to Ref: + 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: // - // *WorkflowRunServiceViewRequest_Id - // *WorkflowRunServiceViewRequest_Digest - Ref isWorkflowRunServiceViewRequest_Ref `protobuf_oneof:"ref"` - // run verification - Verify bool `protobuf:"varint,3,opt,name=verify,proto3" json:"verify,omitempty"` + // *WorkflowRunEvent_Attestation + // *WorkflowRunEvent_Material + // *WorkflowRunEvent_Policies + Attributes isWorkflowRunEvent_Attributes `protobuf_oneof:"attributes"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } -func (x *WorkflowRunServiceViewRequest) Reset() { - *x = WorkflowRunServiceViewRequest{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[17] +func (x *WorkflowRunEvent) Reset() { + *x = WorkflowRunEvent{} + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[19] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } -func (x *WorkflowRunServiceViewRequest) String() string { +func (x *WorkflowRunEvent) String() string { return protoimpl.X.MessageStringOf(x) } -func (*WorkflowRunServiceViewRequest) ProtoMessage() {} +func (*WorkflowRunEvent) ProtoMessage() {} -func (x *WorkflowRunServiceViewRequest) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[17] +func (x *WorkflowRunEvent) 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 { @@ -1175,28 +1343,361 @@ 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 WorkflowRunEvent.ProtoReflect.Descriptor instead. +func (*WorkflowRunEvent) Descriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{19} } -func (x *WorkflowRunServiceViewRequest) GetRef() isWorkflowRunServiceViewRequest_Ref { +func (x *WorkflowRunEvent) GetId() string { if x != nil { - return x.Ref + return x.Id } - return nil + return "" } -func (x *WorkflowRunServiceViewRequest) GetId() string { +func (x *WorkflowRunEvent) GetCreatedAt() *timestamppb.Timestamp { if x != nil { - if x, ok := x.Ref.(*WorkflowRunServiceViewRequest_Id); ok { - return x.Id - } + return x.CreatedAt } - return "" + return nil } -func (x *WorkflowRunServiceViewRequest) GetDigest() string { +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 +} + +func (x *WorkflowRunEvent) GetPolicies() *WorkflowRunEvent_PoliciesAttributes { + if x != nil { + if x, ok := x.Attributes.(*WorkflowRunEvent_Policies); ok { + return x.Policies + } + } + 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"` +} + +type WorkflowRunEvent_Policies struct { + Policies *WorkflowRunEvent_PoliciesAttributes `protobuf:"bytes,12,opt,name=policies,proto3,oneof"` +} + +func (*WorkflowRunEvent_Attestation) isWorkflowRunEvent_Attributes() {} + +func (*WorkflowRunEvent_Material) isWorkflowRunEvent_Attributes() {} + +func (*WorkflowRunEvent_Policies) 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[20] + 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[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 WorkflowRunServiceListRequest.ProtoReflect.Descriptor instead. +func (*WorkflowRunServiceListRequest) Descriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{20} +} + +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[21] + 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[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 WorkflowRunServiceListResponse.ProtoReflect.Descriptor instead. +func (*WorkflowRunServiceListResponse) Descriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{21} +} + +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"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *WorkflowRunServiceViewRequest) Reset() { + *x = WorkflowRunServiceViewRequest{} + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[22] + 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[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 WorkflowRunServiceViewRequest.ProtoReflect.Descriptor instead. +func (*WorkflowRunServiceViewRequest) Descriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{22} +} + +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 @@ -1237,7 +1738,7 @@ type WorkflowRunServiceViewResponse struct { func (x *WorkflowRunServiceViewResponse) Reset() { *x = WorkflowRunServiceViewResponse{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[18] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[23] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1249,7 +1750,7 @@ func (x *WorkflowRunServiceViewResponse) String() string { func (*WorkflowRunServiceViewResponse) ProtoMessage() {} func (x *WorkflowRunServiceViewResponse) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[18] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[23] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1262,7 +1763,7 @@ func (x *WorkflowRunServiceViewResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkflowRunServiceViewResponse.ProtoReflect.Descriptor instead. func (*WorkflowRunServiceViewResponse) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{18} + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{23} } func (x *WorkflowRunServiceViewResponse) GetResult() *WorkflowRunServiceViewResponse_Result { @@ -1281,7 +1782,7 @@ type AttestationServiceGetUploadCredsRequest struct { func (x *AttestationServiceGetUploadCredsRequest) Reset() { *x = AttestationServiceGetUploadCredsRequest{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[19] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[24] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1293,7 +1794,7 @@ func (x *AttestationServiceGetUploadCredsRequest) String() string { func (*AttestationServiceGetUploadCredsRequest) ProtoMessage() {} func (x *AttestationServiceGetUploadCredsRequest) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[19] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[24] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1306,7 +1807,7 @@ func (x *AttestationServiceGetUploadCredsRequest) ProtoReflect() protoreflect.Me // Deprecated: Use AttestationServiceGetUploadCredsRequest.ProtoReflect.Descriptor instead. func (*AttestationServiceGetUploadCredsRequest) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{19} + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{24} } func (x *AttestationServiceGetUploadCredsRequest) GetWorkflowRunId() string { @@ -1325,7 +1826,7 @@ type AttestationServiceGetUploadCredsResponse struct { func (x *AttestationServiceGetUploadCredsResponse) Reset() { *x = AttestationServiceGetUploadCredsResponse{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[20] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[25] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1337,7 +1838,7 @@ func (x *AttestationServiceGetUploadCredsResponse) String() string { func (*AttestationServiceGetUploadCredsResponse) ProtoMessage() {} func (x *AttestationServiceGetUploadCredsResponse) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[20] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[25] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1350,7 +1851,7 @@ func (x *AttestationServiceGetUploadCredsResponse) ProtoReflect() protoreflect.M // Deprecated: Use AttestationServiceGetUploadCredsResponse.ProtoReflect.Descriptor instead. func (*AttestationServiceGetUploadCredsResponse) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{20} + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{25} } func (x *AttestationServiceGetUploadCredsResponse) GetResult() *AttestationServiceGetUploadCredsResponse_Result { @@ -1370,7 +1871,7 @@ type AttestationServiceGetContractResponse_Result struct { func (x *AttestationServiceGetContractResponse_Result) Reset() { *x = AttestationServiceGetContractResponse_Result{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[21] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[26] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1382,7 +1883,7 @@ func (x *AttestationServiceGetContractResponse_Result) String() string { func (*AttestationServiceGetContractResponse_Result) ProtoMessage() {} func (x *AttestationServiceGetContractResponse_Result) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[21] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[26] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1438,7 +1939,7 @@ type AttestationServiceInitResponse_Result struct { func (x *AttestationServiceInitResponse_Result) Reset() { *x = AttestationServiceInitResponse_Result{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[22] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[27] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1450,7 +1951,7 @@ func (x *AttestationServiceInitResponse_Result) String() string { func (*AttestationServiceInitResponse_Result) ProtoMessage() {} func (x *AttestationServiceInitResponse_Result) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[22] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[27] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1541,7 +2042,7 @@ type AttestationServiceInitResponse_SigningOptions struct { func (x *AttestationServiceInitResponse_SigningOptions) Reset() { *x = AttestationServiceInitResponse_SigningOptions{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[23] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[28] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1553,7 +2054,7 @@ func (x *AttestationServiceInitResponse_SigningOptions) String() string { func (*AttestationServiceInitResponse_SigningOptions) ProtoMessage() {} func (x *AttestationServiceInitResponse_SigningOptions) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[23] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[28] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1593,7 +2094,7 @@ type AttestationServiceStoreResponse_Result struct { func (x *AttestationServiceStoreResponse_Result) Reset() { *x = AttestationServiceStoreResponse_Result{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[24] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[29] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1605,7 +2106,7 @@ func (x *AttestationServiceStoreResponse_Result) String() string { func (*AttestationServiceStoreResponse_Result) ProtoMessage() {} func (x *AttestationServiceStoreResponse_Result) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[24] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[29] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1628,6 +2129,321 @@ func (x *AttestationServiceStoreResponse_Result) GetDigest() string { 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"` + // policies that blocked a push + BlockingPolicies []string `protobuf:"bytes,7,rep,name=blocking_policies,json=blockingPolicies,proto3" json:"blocking_policies,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *WorkflowRunEvent_AttestationAttributes) Reset() { + *x = WorkflowRunEvent_AttestationAttributes{} + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[30] + 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[30] + 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{19, 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 *WorkflowRunEvent_AttestationAttributes) GetRunnerType() string { + if x != nil { + return x.RunnerType + } + return "" +} + +func (x *WorkflowRunEvent_AttestationAttributes) GetRemoteState() bool { + if x != nil { + return x.RemoteState + } + return false +} + +func (x *WorkflowRunEvent_AttestationAttributes) GetCliVersion() string { + if x != nil { + return x.CliVersion + } + return "" +} + +func (x *WorkflowRunEvent_AttestationAttributes) GetAttestationDigest() string { + if x != nil { + return x.AttestationDigest + } + return "" +} + +func (x *WorkflowRunEvent_AttestationAttributes) GetBlockingPolicies() []string { + if x != nil { + return x.BlockingPolicies + } + return nil +} + +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[31] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *WorkflowRunEvent_MaterialAttributes) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WorkflowRunEvent_MaterialAttributes) ProtoMessage() {} + +func (x *WorkflowRunEvent_MaterialAttributes) 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_MaterialAttributes.ProtoReflect.Descriptor instead. +func (*WorkflowRunEvent_MaterialAttributes) Descriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{19, 1} +} + +func (x *WorkflowRunEvent_MaterialAttributes) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *WorkflowRunEvent_MaterialAttributes) GetMaterialType() string { + if x != nil { + return x.MaterialType + } + return "" +} + +func (x *WorkflowRunEvent_MaterialAttributes) GetValue() string { + if x != nil { + return x.Value + } + return "" +} + +func (x *WorkflowRunEvent_MaterialAttributes) GetDigest() string { + if x != nil { + return x.Digest + } + return "" +} + +func (x *WorkflowRunEvent_MaterialAttributes) GetInContract() bool { + if x != nil { + return x.InContract + } + return false +} + +func (x *WorkflowRunEvent_MaterialAttributes) GetAddedByCollector() bool { + if x != nil { + return x.AddedByCollector + } + return false +} + +func (x *WorkflowRunEvent_MaterialAttributes) GetPolicies() *WorkflowRunEvent_PolicyCounts { + if x != nil { + return x.Policies + } + return nil +} + +type WorkflowRunEvent_PoliciesAttributes struct { + state protoimpl.MessageState `protogen:"open.v1"` + // init or push + Phase string `protobuf:"bytes,1,opt,name=phase,proto3" json:"phase,omitempty"` + Policies *WorkflowRunEvent_PolicyCounts `protobuf:"bytes,2,opt,name=policies,proto3" json:"policies,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *WorkflowRunEvent_PoliciesAttributes) Reset() { + *x = WorkflowRunEvent_PoliciesAttributes{} + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[32] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *WorkflowRunEvent_PoliciesAttributes) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WorkflowRunEvent_PoliciesAttributes) ProtoMessage() {} + +func (x *WorkflowRunEvent_PoliciesAttributes) 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 { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use WorkflowRunEvent_PoliciesAttributes.ProtoReflect.Descriptor instead. +func (*WorkflowRunEvent_PoliciesAttributes) Descriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{19, 2} +} + +func (x *WorkflowRunEvent_PoliciesAttributes) GetPhase() string { + if x != nil { + return x.Phase + } + return "" +} + +func (x *WorkflowRunEvent_PoliciesAttributes) GetPolicies() *WorkflowRunEvent_PolicyCounts { + if x != nil { + return x.Policies + } + return nil +} + +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 *WorkflowRunEvent_PolicyCounts) Reset() { + *x = WorkflowRunEvent_PolicyCounts{} + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[33] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *WorkflowRunEvent_PolicyCounts) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WorkflowRunEvent_PolicyCounts) ProtoMessage() {} + +func (x *WorkflowRunEvent_PolicyCounts) 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 { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use WorkflowRunEvent_PolicyCounts.ProtoReflect.Descriptor instead. +func (*WorkflowRunEvent_PolicyCounts) Descriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{19, 3} +} + +func (x *WorkflowRunEvent_PolicyCounts) GetEvaluated() int32 { + if x != nil { + return x.Evaluated + } + return 0 +} + +func (x *WorkflowRunEvent_PolicyCounts) GetPassed() int32 { + if x != nil { + return x.Passed + } + return 0 +} + +func (x *WorkflowRunEvent_PolicyCounts) GetViolated() int32 { + if x != nil { + return x.Violated + } + return 0 +} + +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 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 +2457,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[34] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1653,7 +2469,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[34] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1666,7 +2482,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{23, 0} } func (x *WorkflowRunServiceViewResponse_Result) GetOrgName() string { @@ -1709,7 +2525,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[35] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1721,7 +2537,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[35] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1734,7 +2550,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{23, 1} } func (x *WorkflowRunServiceViewResponse_VerificationResult) GetVerified() bool { @@ -1761,7 +2577,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[36] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1773,7 +2589,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[36] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1786,7 +2602,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{25, 0} } func (x *AttestationServiceGetUploadCredsResponse_Result) GetToken() string { @@ -1807,7 +2623,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 +2704,77 @@ 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\"\x8a\x01\n" + + "#WorkflowRunServiceListEventsRequest\x120\n" + + "\x0fworkflow_run_id\x18\x01 \x01(\tB\b\xbaH\x05r\x03\xb0\x01\x01R\rworkflowRunId\x121\n" + + "\x0eafter_event_id\x18\x02 \x01(\tB\v\xbaH\b\xd8\x01\x01r\x03\xb0\x01\x01R\fafterEventId\"a\n" + + "$WorkflowRunServiceListEventsResponse\x129\n" + + "\x06events\x18\x01 \x03(\v2!.controlplane.v1.WorkflowRunEventR\x06events\"\x93\x0e\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\x19\n" + + "\x03key\x18\x05 \x01(\tB\a\xbaH\x04r\x02\x10\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\x12R\n" + + "\bpolicies\x18\f \x01(\v24.controlplane.v1.WorkflowRunEvent.PoliciesAttributesH\x00R\bpolicies\x1a\xaa\x02\n" + + "\x15AttestationAttributes\x12#\n" + + "\rcontract_name\x18\x01 \x01(\tR\fcontractName\x12+\n" + + "\x11contract_revision\x18\x02 \x01(\x05R\x10contractRevision\x12\x1f\n" + + "\vrunner_type\x18\x03 \x01(\tR\n" + + "runnerType\x12!\n" + + "\fremote_state\x18\x04 \x01(\bR\vremoteState\x12\x1f\n" + + "\vcli_version\x18\x05 \x01(\tR\n" + + "cliVersion\x12-\n" + + "\x12attestation_digest\x18\x06 \x01(\tR\x11attestationDigest\x12+\n" + + "\x11blocking_policies\x18\a \x03(\tR\x10blockingPolicies\x1a\xa0\x02\n" + + "\x12MaterialAttributes\x12\x12\n" + + "\x04name\x18\x01 \x01(\tR\x04name\x12#\n" + + "\rmaterial_type\x18\x02 \x01(\tR\fmaterialType\x12\x1e\n" + + "\x05value\x18\x03 \x01(\tB\b\xbaH\x05r\x03\x18\x80\x02R\x05value\x12\x16\n" + + "\x06digest\x18\x04 \x01(\tR\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\x1av\n" + + "\x12PoliciesAttributes\x12\x14\n" + + "\x05phase\x18\x01 \x01(\tR\x05phase\x12J\n" + + "\bpolicies\x18\x02 \x01(\v2..controlplane.v1.WorkflowRunEvent.PolicyCountsR\bpolicies\x1a\xa7\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(\tR\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\"X\n" + + "\x04Type\x12\x14\n" + + "\x10TYPE_UNSPECIFIED\x10\x00\x12\x14\n" + + "\x10TYPE_ATTESTATION\x10\x01\x12\x11\n" + + "\rTYPE_MATERIAL\x10\x02\x12\x11\n" + + "\rTYPE_POLICIES\x10\x03\"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" + + "attributes\"\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" + @@ -1930,19 +2816,22 @@ 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\xe1\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\x12y\n" + + "\n" + + "ListEvents\x124.controlplane.v1.WorkflowRunServiceListEventsRequest\x1a5.controlplane.v1.WorkflowRunServiceListEventsResponseBLZJgithub.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1;v1b\x06proto3" var ( file_controlplane_v1_workflow_run_proto_rawDescOnce sync.Once @@ -1956,106 +2845,134 @@ 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, 4) +var file_controlplane_v1_workflow_run_proto_msgTypes = make([]protoimpl.MessageInfo, 37) 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 + (*FindOrCreateWorkflowRequest)(nil), // 4: controlplane.v1.FindOrCreateWorkflowRequest + (*FindOrCreateWorkflowResponse)(nil), // 5: controlplane.v1.FindOrCreateWorkflowResponse + (*AttestationServiceGetPolicyRequest)(nil), // 6: controlplane.v1.AttestationServiceGetPolicyRequest + (*AttestationServiceGetPolicyResponse)(nil), // 7: controlplane.v1.AttestationServiceGetPolicyResponse + (*RemotePolicyReference)(nil), // 8: controlplane.v1.RemotePolicyReference + (*AttestationServiceGetPolicyGroupRequest)(nil), // 9: controlplane.v1.AttestationServiceGetPolicyGroupRequest + (*AttestationServiceGetPolicyGroupResponse)(nil), // 10: controlplane.v1.AttestationServiceGetPolicyGroupResponse + (*AttestationServiceGetContractRequest)(nil), // 11: controlplane.v1.AttestationServiceGetContractRequest + (*AttestationServiceGetContractResponse)(nil), // 12: controlplane.v1.AttestationServiceGetContractResponse + (*AttestationServiceInitRequest)(nil), // 13: controlplane.v1.AttestationServiceInitRequest + (*AttestationServiceInitResponse)(nil), // 14: controlplane.v1.AttestationServiceInitResponse + (*AttestationServiceStoreRequest)(nil), // 15: controlplane.v1.AttestationServiceStoreRequest + (*AttestationServiceStoreResponse)(nil), // 16: controlplane.v1.AttestationServiceStoreResponse + (*AttestationServiceCancelRequest)(nil), // 17: controlplane.v1.AttestationServiceCancelRequest + (*AttestationServiceCancelResponse)(nil), // 18: controlplane.v1.AttestationServiceCancelResponse + (*AttestationServiceRecordEventRequest)(nil), // 19: controlplane.v1.AttestationServiceRecordEventRequest + (*AttestationServiceRecordEventResponse)(nil), // 20: controlplane.v1.AttestationServiceRecordEventResponse + (*WorkflowRunServiceListEventsRequest)(nil), // 21: controlplane.v1.WorkflowRunServiceListEventsRequest + (*WorkflowRunServiceListEventsResponse)(nil), // 22: controlplane.v1.WorkflowRunServiceListEventsResponse + (*WorkflowRunEvent)(nil), // 23: controlplane.v1.WorkflowRunEvent + (*WorkflowRunServiceListRequest)(nil), // 24: controlplane.v1.WorkflowRunServiceListRequest + (*WorkflowRunServiceListResponse)(nil), // 25: controlplane.v1.WorkflowRunServiceListResponse + (*WorkflowRunServiceViewRequest)(nil), // 26: controlplane.v1.WorkflowRunServiceViewRequest + (*WorkflowRunServiceViewResponse)(nil), // 27: controlplane.v1.WorkflowRunServiceViewResponse + (*AttestationServiceGetUploadCredsRequest)(nil), // 28: controlplane.v1.AttestationServiceGetUploadCredsRequest + (*AttestationServiceGetUploadCredsResponse)(nil), // 29: controlplane.v1.AttestationServiceGetUploadCredsResponse + (*AttestationServiceGetContractResponse_Result)(nil), // 30: controlplane.v1.AttestationServiceGetContractResponse.Result + (*AttestationServiceInitResponse_Result)(nil), // 31: controlplane.v1.AttestationServiceInitResponse.Result + (*AttestationServiceInitResponse_SigningOptions)(nil), // 32: controlplane.v1.AttestationServiceInitResponse.SigningOptions + (*AttestationServiceStoreResponse_Result)(nil), // 33: controlplane.v1.AttestationServiceStoreResponse.Result + (*WorkflowRunEvent_AttestationAttributes)(nil), // 34: controlplane.v1.WorkflowRunEvent.AttestationAttributes + (*WorkflowRunEvent_MaterialAttributes)(nil), // 35: controlplane.v1.WorkflowRunEvent.MaterialAttributes + (*WorkflowRunEvent_PoliciesAttributes)(nil), // 36: controlplane.v1.WorkflowRunEvent.PoliciesAttributes + (*WorkflowRunEvent_PolicyCounts)(nil), // 37: controlplane.v1.WorkflowRunEvent.PolicyCounts + (*WorkflowRunServiceViewResponse_Result)(nil), // 38: controlplane.v1.WorkflowRunServiceViewResponse.Result + (*WorkflowRunServiceViewResponse_VerificationResult)(nil), // 39: controlplane.v1.WorkflowRunServiceViewResponse.VerificationResult + (*AttestationServiceGetUploadCredsResponse_Result)(nil), // 40: controlplane.v1.AttestationServiceGetUploadCredsResponse.Result + (*WorkflowItem)(nil), // 41: controlplane.v1.WorkflowItem + (*v1.Policy)(nil), // 42: workflowcontract.v1.Policy + (*v1.PolicyGroup)(nil), // 43: workflowcontract.v1.PolicyGroup + (v1.CraftingSchema_Runner_RunnerType)(0), // 44: workflowcontract.v1.CraftingSchema.Runner.RunnerType + (*timestamppb.Timestamp)(nil), // 45: google.protobuf.Timestamp + (RunStatus)(0), // 46: controlplane.v1.RunStatus + (PolicyViolationsFilter)(0), // 47: controlplane.v1.PolicyViolationsFilter + (PolicyStatusFilter)(0), // 48: controlplane.v1.PolicyStatusFilter + (PolicyGatesFilter)(0), // 49: controlplane.v1.PolicyGatesFilter + (*CursorPaginationRequest)(nil), // 50: controlplane.v1.CursorPaginationRequest + (*WorkflowRunItem)(nil), // 51: controlplane.v1.WorkflowRunItem + (*CursorPaginationResponse)(nil), // 52: controlplane.v1.CursorPaginationResponse + (*WorkflowContractVersionItem)(nil), // 53: controlplane.v1.WorkflowContractVersionItem + (*AttestationItem)(nil), // 54: controlplane.v1.AttestationItem + (*CASBackendItem)(nil), // 55: 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 + 41, // 0: controlplane.v1.FindOrCreateWorkflowResponse.result:type_name -> controlplane.v1.WorkflowItem + 42, // 1: controlplane.v1.AttestationServiceGetPolicyResponse.policy:type_name -> workflowcontract.v1.Policy + 8, // 2: controlplane.v1.AttestationServiceGetPolicyResponse.reference:type_name -> controlplane.v1.RemotePolicyReference + 43, // 3: controlplane.v1.AttestationServiceGetPolicyGroupResponse.group:type_name -> workflowcontract.v1.PolicyGroup + 8, // 4: controlplane.v1.AttestationServiceGetPolicyGroupResponse.reference:type_name -> controlplane.v1.RemotePolicyReference + 30, // 5: controlplane.v1.AttestationServiceGetContractResponse.result:type_name -> controlplane.v1.AttestationServiceGetContractResponse.Result + 44, // 6: controlplane.v1.AttestationServiceInitRequest.runner:type_name -> workflowcontract.v1.CraftingSchema.Runner.RunnerType + 31, // 7: controlplane.v1.AttestationServiceInitResponse.result:type_name -> controlplane.v1.AttestationServiceInitResponse.Result + 33, // 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 + 23, // 11: controlplane.v1.WorkflowRunServiceListEventsResponse.events:type_name -> controlplane.v1.WorkflowRunEvent + 45, // 12: controlplane.v1.WorkflowRunEvent.created_at:type_name -> google.protobuf.Timestamp + 1, // 13: controlplane.v1.WorkflowRunEvent.source:type_name -> controlplane.v1.WorkflowRunEvent.Source + 2, // 14: controlplane.v1.WorkflowRunEvent.type:type_name -> controlplane.v1.WorkflowRunEvent.Type + 3, // 15: controlplane.v1.WorkflowRunEvent.status:type_name -> controlplane.v1.WorkflowRunEvent.Status + 34, // 16: controlplane.v1.WorkflowRunEvent.attestation:type_name -> controlplane.v1.WorkflowRunEvent.AttestationAttributes + 35, // 17: controlplane.v1.WorkflowRunEvent.material:type_name -> controlplane.v1.WorkflowRunEvent.MaterialAttributes + 36, // 18: controlplane.v1.WorkflowRunEvent.policies:type_name -> controlplane.v1.WorkflowRunEvent.PoliciesAttributes + 46, // 19: controlplane.v1.WorkflowRunServiceListRequest.status:type_name -> controlplane.v1.RunStatus + 47, // 20: controlplane.v1.WorkflowRunServiceListRequest.policy_violations:type_name -> controlplane.v1.PolicyViolationsFilter + 48, // 21: controlplane.v1.WorkflowRunServiceListRequest.policy_status:type_name -> controlplane.v1.PolicyStatusFilter + 49, // 22: controlplane.v1.WorkflowRunServiceListRequest.policy_gates:type_name -> controlplane.v1.PolicyGatesFilter + 50, // 23: controlplane.v1.WorkflowRunServiceListRequest.pagination:type_name -> controlplane.v1.CursorPaginationRequest + 51, // 24: controlplane.v1.WorkflowRunServiceListResponse.result:type_name -> controlplane.v1.WorkflowRunItem + 52, // 25: controlplane.v1.WorkflowRunServiceListResponse.pagination:type_name -> controlplane.v1.CursorPaginationResponse + 38, // 26: controlplane.v1.WorkflowRunServiceViewResponse.result:type_name -> controlplane.v1.WorkflowRunServiceViewResponse.Result + 40, // 27: controlplane.v1.AttestationServiceGetUploadCredsResponse.result:type_name -> controlplane.v1.AttestationServiceGetUploadCredsResponse.Result + 41, // 28: controlplane.v1.AttestationServiceGetContractResponse.Result.workflow:type_name -> controlplane.v1.WorkflowItem + 53, // 29: controlplane.v1.AttestationServiceGetContractResponse.Result.contract:type_name -> controlplane.v1.WorkflowContractVersionItem + 51, // 30: controlplane.v1.AttestationServiceInitResponse.Result.workflow_run:type_name -> controlplane.v1.WorkflowRunItem + 32, // 31: controlplane.v1.AttestationServiceInitResponse.Result.signing_options:type_name -> controlplane.v1.AttestationServiceInitResponse.SigningOptions + 37, // 32: controlplane.v1.WorkflowRunEvent.MaterialAttributes.policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts + 37, // 33: controlplane.v1.WorkflowRunEvent.PoliciesAttributes.policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts + 51, // 34: controlplane.v1.WorkflowRunServiceViewResponse.Result.workflow_run:type_name -> controlplane.v1.WorkflowRunItem + 54, // 35: controlplane.v1.WorkflowRunServiceViewResponse.Result.attestation:type_name -> controlplane.v1.AttestationItem + 39, // 36: controlplane.v1.WorkflowRunServiceViewResponse.Result.verification:type_name -> controlplane.v1.WorkflowRunServiceViewResponse.VerificationResult + 55, // 37: controlplane.v1.AttestationServiceGetUploadCredsResponse.Result.backend:type_name -> controlplane.v1.CASBackendItem + 4, // 38: controlplane.v1.AttestationService.FindOrCreateWorkflow:input_type -> controlplane.v1.FindOrCreateWorkflowRequest + 11, // 39: controlplane.v1.AttestationService.GetContract:input_type -> controlplane.v1.AttestationServiceGetContractRequest + 13, // 40: controlplane.v1.AttestationService.Init:input_type -> controlplane.v1.AttestationServiceInitRequest + 15, // 41: controlplane.v1.AttestationService.Store:input_type -> controlplane.v1.AttestationServiceStoreRequest + 28, // 42: controlplane.v1.AttestationService.GetUploadCreds:input_type -> controlplane.v1.AttestationServiceGetUploadCredsRequest + 17, // 43: controlplane.v1.AttestationService.Cancel:input_type -> controlplane.v1.AttestationServiceCancelRequest + 19, // 44: controlplane.v1.AttestationService.RecordEvent:input_type -> controlplane.v1.AttestationServiceRecordEventRequest + 6, // 45: controlplane.v1.AttestationService.GetPolicy:input_type -> controlplane.v1.AttestationServiceGetPolicyRequest + 9, // 46: controlplane.v1.AttestationService.GetPolicyGroup:input_type -> controlplane.v1.AttestationServiceGetPolicyGroupRequest + 24, // 47: controlplane.v1.WorkflowRunService.List:input_type -> controlplane.v1.WorkflowRunServiceListRequest + 26, // 48: controlplane.v1.WorkflowRunService.View:input_type -> controlplane.v1.WorkflowRunServiceViewRequest + 21, // 49: controlplane.v1.WorkflowRunService.ListEvents:input_type -> controlplane.v1.WorkflowRunServiceListEventsRequest + 5, // 50: controlplane.v1.AttestationService.FindOrCreateWorkflow:output_type -> controlplane.v1.FindOrCreateWorkflowResponse + 12, // 51: controlplane.v1.AttestationService.GetContract:output_type -> controlplane.v1.AttestationServiceGetContractResponse + 14, // 52: controlplane.v1.AttestationService.Init:output_type -> controlplane.v1.AttestationServiceInitResponse + 16, // 53: controlplane.v1.AttestationService.Store:output_type -> controlplane.v1.AttestationServiceStoreResponse + 29, // 54: controlplane.v1.AttestationService.GetUploadCreds:output_type -> controlplane.v1.AttestationServiceGetUploadCredsResponse + 18, // 55: controlplane.v1.AttestationService.Cancel:output_type -> controlplane.v1.AttestationServiceCancelResponse + 20, // 56: controlplane.v1.AttestationService.RecordEvent:output_type -> controlplane.v1.AttestationServiceRecordEventResponse + 7, // 57: controlplane.v1.AttestationService.GetPolicy:output_type -> controlplane.v1.AttestationServiceGetPolicyResponse + 10, // 58: controlplane.v1.AttestationService.GetPolicyGroup:output_type -> controlplane.v1.AttestationServiceGetPolicyGroupResponse + 25, // 59: controlplane.v1.WorkflowRunService.List:output_type -> controlplane.v1.WorkflowRunServiceListResponse + 27, // 60: controlplane.v1.WorkflowRunService.View:output_type -> controlplane.v1.WorkflowRunServiceViewResponse + 22, // 61: controlplane.v1.WorkflowRunService.ListEvents:output_type -> controlplane.v1.WorkflowRunServiceListEventsResponse + 50, // [50:62] is the sub-list for method output_type + 38, // [38:50] is the sub-list for method input_type + 38, // [38:38] is the sub-list for extension type_name + 38, // [38:38] is the sub-list for extension extendee + 0, // [0:38] is the sub-list for field type_name } func init() { file_controlplane_v1_workflow_run_proto_init() } @@ -2067,7 +2984,12 @@ func file_controlplane_v1_workflow_run_proto_init() { file_controlplane_v1_response_messages_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{ + file_controlplane_v1_workflow_run_proto_msgTypes[19].OneofWrappers = []any{ + (*WorkflowRunEvent_Attestation)(nil), + (*WorkflowRunEvent_Material)(nil), + (*WorkflowRunEvent_Policies)(nil), + } + file_controlplane_v1_workflow_run_proto_msgTypes[22].OneofWrappers = []any{ (*WorkflowRunServiceViewRequest_Id)(nil), (*WorkflowRunServiceViewRequest_Digest)(nil), } @@ -2076,8 +2998,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: 4, + NumMessages: 37, 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..e3925cb3e 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); + // Events of a run, oldest first. Optional after_event_id returns only newer events. + rpc ListEvents(WorkflowRunServiceListEventsRequest) returns (WorkflowRunServiceListEventsResponse); } message FindOrCreateWorkflowRequest { @@ -204,6 +209,110 @@ 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 {} + +message WorkflowRunServiceListEventsRequest { + string workflow_run_id = 1 [(buf.validate.field).string.uuid = true]; + // Optional. Return only the events recorded after this one. + string after_event_id = 2 [(buf.validate.field) = { + ignore: IGNORE_IF_ZERO_VALUE + string: {uuid: true} + }]; +} + +message WorkflowRunServiceListEventsResponse { + repeated WorkflowRunEvent events = 1; +} + +// 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]; + 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; + PoliciesAttributes policies = 12; + } + + enum Source { + SOURCE_UNSPECIFIED = 0; + SOURCE_CLI = 1; + SOURCE_CONTROL_PLANE = 2; + } + + enum Type { + TYPE_UNSPECIFIED = 0; + TYPE_ATTESTATION = 1; + TYPE_MATERIAL = 2; + TYPE_POLICIES = 3; + } + + enum Status { + STATUS_UNSPECIFIED = 0; + STATUS_STARTED = 1; + STATUS_SUCCEEDED = 2; + STATUS_FAILED = 3; + STATUS_CANCELED = 4; + } + + 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; + // policies that blocked a push + repeated string blocking_policies = 7; + } + + message MaterialAttributes { + string name = 1; + string material_type = 2; + // value shown by attestation status, cut to 256 characters + string value = 3 [(buf.validate.field).string.max_len = 256]; + string digest = 4; + bool in_contract = 5; + bool added_by_collector = 6; + PolicyCounts policies = 7; + } + + message PoliciesAttributes { + // init or push + string phase = 1; + PolicyCounts policies = 2; + } + + message PolicyCounts { + int32 evaluated = 1; + int32 passed = 2; + int32 violated = 3; + int32 skipped = 4; + repeated string violated_policies = 5; + } +} + message WorkflowRunServiceListRequest { // Filters // by workflow 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..fec70a703 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_ListEvents_FullMethodName = "/controlplane.v1.WorkflowRunService/ListEvents" ) // 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) + // Events of a run, oldest first. Optional after_event_id returns only newer events. + ListEvents(ctx context.Context, in *WorkflowRunServiceListEventsRequest, opts ...grpc.CallOption) (*WorkflowRunServiceListEventsResponse, error) } type workflowRunServiceClient struct { @@ -427,12 +469,23 @@ func (c *workflowRunServiceClient) View(ctx context.Context, in *WorkflowRunServ return out, nil } +func (c *workflowRunServiceClient) ListEvents(ctx context.Context, in *WorkflowRunServiceListEventsRequest, opts ...grpc.CallOption) (*WorkflowRunServiceListEventsResponse, error) { + out := new(WorkflowRunServiceListEventsResponse) + err := c.cc.Invoke(ctx, WorkflowRunService_ListEvents_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) + // Events of a run, oldest first. Optional after_event_id returns only newer events. + ListEvents(context.Context, *WorkflowRunServiceListEventsRequest) (*WorkflowRunServiceListEventsResponse, 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) ListEvents(context.Context, *WorkflowRunServiceListEventsRequest) (*WorkflowRunServiceListEventsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method ListEvents 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_ListEvents_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(WorkflowRunServiceListEventsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(WorkflowRunServiceServer).ListEvents(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: WorkflowRunService_ListEvents_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(WorkflowRunServiceServer).ListEvents(ctx, req.(*WorkflowRunServiceListEventsRequest)) + } + 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: "ListEvents", + Handler: _WorkflowRunService_ListEvents_Handler, + }, }, Streams: []grpc.StreamDesc{}, Metadata: "controlplane/v1/workflow_run.proto", 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..cd5940e68 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,215 @@ 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 { +} + +export interface WorkflowRunServiceListEventsRequest { + workflowRunId: string; + /** Optional. Return only the events recorded after this one. */ + afterEventId: string; +} + +export interface WorkflowRunServiceListEventsResponse { + events: WorkflowRunEvent[]; +} + +/** + * 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; + policies?: WorkflowRunEvent_PoliciesAttributes | 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, + TYPE_POLICIES = 3, + 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 3: + case "TYPE_POLICIES": + return WorkflowRunEvent_Type.TYPE_POLICIES; + 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.TYPE_POLICIES: + return "TYPE_POLICIES"; + 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; + /** policies that blocked a push */ + blockingPolicies: 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_PoliciesAttributes { + /** init or push */ + phase: string; + policies?: WorkflowRunEvent_PolicyCounts; +} + +export interface WorkflowRunEvent_PolicyCounts { + evaluated: number; + passed: number; + violated: number; + skipped: number; + violatedPolicies: string[]; +} + export interface WorkflowRunServiceListRequest { /** * Filters @@ -1964,56 +2174,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 +2201,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,95 +2219,54 @@ 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 ?? ""; - message.policyViolations = object.policyViolations ?? 0; - message.policyStatus = object.policyStatus ?? 0; - message.policyGates = object.policyGates ?? 0; - message.pagination = (object.pagination !== undefined && object.pagination !== null) - ? CursorPaginationRequest.fromPartial(object.pagination) + ): AttestationServiceRecordEventRequest { + const message = createBaseAttestationServiceRecordEventRequest(); + message.workflowRunId = object.workflowRunId ?? ""; + message.event = (object.event !== undefined && object.event !== null) + ? WorkflowRunEvent.fromPartial(object.event) : undefined; return message; }, }; -function createBaseWorkflowRunServiceListResponse(): WorkflowRunServiceListResponse { - return { result: [], pagination: undefined }; +function createBaseAttestationServiceRecordEventResponse(): AttestationServiceRecordEventResponse { + return {}; } -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(); - } +export const AttestationServiceRecordEventResponse = { + encode(_: AttestationServiceRecordEventResponse, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { return writer; }, - decode(input: _m0.Reader | Uint8Array, length?: number): WorkflowRunServiceListResponse { + 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 = createBaseWorkflowRunServiceListResponse(); + const message = createBaseAttestationServiceRecordEventResponse(); 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; @@ -2187,21 +2276,1105 @@ export const WorkflowRunServiceListResponse = { 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, - }; + fromJSON(_: any): AttestationServiceRecordEventResponse { + return {}; }, - toJSON(message: WorkflowRunServiceListResponse): unknown { + toJSON(_: AttestationServiceRecordEventResponse): unknown { const obj: any = {}; - if (message.result) { - obj.result = message.result.map((e) => e ? WorkflowRunItem.toJSON(e) : undefined); - } else { - obj.result = []; - } - message.pagination !== undefined && + return obj; + }, + + create, I>>( + base?: I, + ): AttestationServiceRecordEventResponse { + return AttestationServiceRecordEventResponse.fromPartial(base ?? {}); + }, + + fromPartial, I>>( + _: I, + ): AttestationServiceRecordEventResponse { + const message = createBaseAttestationServiceRecordEventResponse(); + return message; + }, +}; + +function createBaseWorkflowRunServiceListEventsRequest(): WorkflowRunServiceListEventsRequest { + return { workflowRunId: "", afterEventId: "" }; +} + +export const WorkflowRunServiceListEventsRequest = { + encode(message: WorkflowRunServiceListEventsRequest, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { + if (message.workflowRunId !== "") { + writer.uint32(10).string(message.workflowRunId); + } + if (message.afterEventId !== "") { + writer.uint32(18).string(message.afterEventId); + } + return writer; + }, + + decode(input: _m0.Reader | Uint8Array, length?: number): WorkflowRunServiceListEventsRequest { + const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input); + let end = length === undefined ? reader.len : reader.pos + length; + const message = createBaseWorkflowRunServiceListEventsRequest(); + while (reader.pos < end) { + const tag = reader.uint32(); + switch (tag >>> 3) { + case 1: + if (tag !== 10) { + break; + } + + message.workflowRunId = reader.string(); + continue; + case 2: + if (tag !== 18) { + break; + } + + message.afterEventId = reader.string(); + continue; + } + if ((tag & 7) === 4 || tag === 0) { + break; + } + reader.skipType(tag & 7); + } + return message; + }, + + fromJSON(object: any): WorkflowRunServiceListEventsRequest { + return { + workflowRunId: isSet(object.workflowRunId) ? String(object.workflowRunId) : "", + afterEventId: isSet(object.afterEventId) ? String(object.afterEventId) : "", + }; + }, + + toJSON(message: WorkflowRunServiceListEventsRequest): unknown { + const obj: any = {}; + message.workflowRunId !== undefined && (obj.workflowRunId = message.workflowRunId); + message.afterEventId !== undefined && (obj.afterEventId = message.afterEventId); + return obj; + }, + + create, I>>( + base?: I, + ): WorkflowRunServiceListEventsRequest { + return WorkflowRunServiceListEventsRequest.fromPartial(base ?? {}); + }, + + fromPartial, I>>( + object: I, + ): WorkflowRunServiceListEventsRequest { + const message = createBaseWorkflowRunServiceListEventsRequest(); + message.workflowRunId = object.workflowRunId ?? ""; + message.afterEventId = object.afterEventId ?? ""; + return message; + }, +}; + +function createBaseWorkflowRunServiceListEventsResponse(): WorkflowRunServiceListEventsResponse { + return { events: [] }; +} + +export const WorkflowRunServiceListEventsResponse = { + encode(message: WorkflowRunServiceListEventsResponse, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { + for (const v of message.events) { + WorkflowRunEvent.encode(v!, writer.uint32(10).fork()).ldelim(); + } + return writer; + }, + + decode(input: _m0.Reader | Uint8Array, length?: number): WorkflowRunServiceListEventsResponse { + const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input); + let end = length === undefined ? reader.len : reader.pos + length; + const message = createBaseWorkflowRunServiceListEventsResponse(); + while (reader.pos < end) { + const tag = reader.uint32(); + switch (tag >>> 3) { + case 1: + if (tag !== 10) { + break; + } + + message.events.push(WorkflowRunEvent.decode(reader, reader.uint32())); + continue; + } + if ((tag & 7) === 4 || tag === 0) { + break; + } + reader.skipType(tag & 7); + } + return message; + }, + + fromJSON(object: any): WorkflowRunServiceListEventsResponse { + return { events: Array.isArray(object?.events) ? object.events.map((e: any) => WorkflowRunEvent.fromJSON(e)) : [] }; + }, + + toJSON(message: WorkflowRunServiceListEventsResponse): unknown { + const obj: any = {}; + if (message.events) { + obj.events = message.events.map((e) => e ? WorkflowRunEvent.toJSON(e) : undefined); + } else { + obj.events = []; + } + return obj; + }, + + create, I>>( + base?: I, + ): WorkflowRunServiceListEventsResponse { + return WorkflowRunServiceListEventsResponse.fromPartial(base ?? {}); + }, + + fromPartial, I>>( + object: I, + ): WorkflowRunServiceListEventsResponse { + const message = createBaseWorkflowRunServiceListEventsResponse(); + message.events = object.events?.map((e) => WorkflowRunEvent.fromPartial(e)) || []; + return message; + }, +}; + +function createBaseWorkflowRunEvent(): WorkflowRunEvent { + return { + id: "", + createdAt: undefined, + source: 0, + type: 0, + key: "", + status: 0, + message: "", + attestation: undefined, + material: undefined, + policies: 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(); + } + if (message.policies !== undefined) { + WorkflowRunEvent_PoliciesAttributes.encode(message.policies, writer.uint32(98).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; + case 12: + if (tag !== 98) { + break; + } + + message.policies = WorkflowRunEvent_PoliciesAttributes.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, + policies: isSet(object.policies) ? WorkflowRunEvent_PoliciesAttributes.fromJSON(object.policies) : 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); + message.policies !== undefined && + (obj.policies = message.policies ? WorkflowRunEvent_PoliciesAttributes.toJSON(message.policies) : 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; + message.policies = (object.policies !== undefined && object.policies !== null) + ? WorkflowRunEvent_PoliciesAttributes.fromPartial(object.policies) + : undefined; + return message; + }, +}; + +function createBaseWorkflowRunEvent_AttestationAttributes(): WorkflowRunEvent_AttestationAttributes { + return { + contractName: "", + contractRevision: 0, + runnerType: "", + remoteState: false, + cliVersion: "", + attestationDigest: "", + blockingPolicies: [], + }; +} + +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); + } + for (const v of message.blockingPolicies) { + writer.uint32(58).string(v!); + } + 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.blockingPolicies.push(reader.string()); + 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) : "", + blockingPolicies: Array.isArray(object?.blockingPolicies) + ? object.blockingPolicies.map((e: any) => String(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); + if (message.blockingPolicies) { + obj.blockingPolicies = message.blockingPolicies.map((e) => e); + } else { + obj.blockingPolicies = []; + } + 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.blockingPolicies = object.blockingPolicies?.map((e) => e) || []; + 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_PoliciesAttributes(): WorkflowRunEvent_PoliciesAttributes { + return { phase: "", policies: undefined }; +} + +export const WorkflowRunEvent_PoliciesAttributes = { + encode(message: WorkflowRunEvent_PoliciesAttributes, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { + if (message.phase !== "") { + writer.uint32(10).string(message.phase); + } + if (message.policies !== undefined) { + WorkflowRunEvent_PolicyCounts.encode(message.policies, writer.uint32(18).fork()).ldelim(); + } + return writer; + }, + + decode(input: _m0.Reader | Uint8Array, length?: number): WorkflowRunEvent_PoliciesAttributes { + const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input); + let end = length === undefined ? reader.len : reader.pos + length; + const message = createBaseWorkflowRunEvent_PoliciesAttributes(); + while (reader.pos < end) { + const tag = reader.uint32(); + switch (tag >>> 3) { + case 1: + if (tag !== 10) { + break; + } + + message.phase = reader.string(); + continue; + case 2: + if (tag !== 18) { + 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_PoliciesAttributes { + return { + phase: isSet(object.phase) ? String(object.phase) : "", + policies: isSet(object.policies) ? WorkflowRunEvent_PolicyCounts.fromJSON(object.policies) : undefined, + }; + }, + + toJSON(message: WorkflowRunEvent_PoliciesAttributes): unknown { + const obj: any = {}; + message.phase !== undefined && (obj.phase = message.phase); + message.policies !== undefined && + (obj.policies = message.policies ? WorkflowRunEvent_PolicyCounts.toJSON(message.policies) : undefined); + return obj; + }, + + create, I>>( + base?: I, + ): WorkflowRunEvent_PoliciesAttributes { + return WorkflowRunEvent_PoliciesAttributes.fromPartial(base ?? {}); + }, + + fromPartial, I>>( + object: I, + ): WorkflowRunEvent_PoliciesAttributes { + const message = createBaseWorkflowRunEvent_PoliciesAttributes(); + message.phase = object.phase ?? ""; + 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; + message.pagination = (object.pagination !== undefined && object.pagination !== null) + ? CursorPaginationRequest.fromPartial(object.pagination) + : undefined; + return message; + }, +}; + +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; }, @@ -2800,6 +3973,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 +4000,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 +4059,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 +4233,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 +4312,11 @@ export interface WorkflowRunService { request: DeepPartial, metadata?: grpc.Metadata, ): Promise; + /** Events of a run, oldest first. Optional after_event_id returns only newer events. */ + ListEvents( + request: DeepPartial, + metadata?: grpc.Metadata, + ): Promise; } export class WorkflowRunServiceClientImpl implements WorkflowRunService { @@ -3108,6 +4326,7 @@ export class WorkflowRunServiceClientImpl implements WorkflowRunService { this.rpc = rpc; this.List = this.List.bind(this); this.View = this.View.bind(this); + this.ListEvents = this.ListEvents.bind(this); } List( @@ -3123,6 +4342,17 @@ export class WorkflowRunServiceClientImpl implements WorkflowRunService { ): Promise { return this.rpc.unary(WorkflowRunServiceViewDesc, WorkflowRunServiceViewRequest.fromPartial(request), metadata); } + + ListEvents( + request: DeepPartial, + metadata?: grpc.Metadata, + ): Promise { + return this.rpc.unary( + WorkflowRunServiceListEventsDesc, + WorkflowRunServiceListEventsRequest.fromPartial(request), + metadata, + ); + } } export const WorkflowRunServiceDesc = { serviceName: "controlplane.v1.WorkflowRunService" }; @@ -3173,6 +4403,29 @@ export const WorkflowRunServiceViewDesc: UnaryMethodDefinitionish = { } as any, }; +export const WorkflowRunServiceListEventsDesc: UnaryMethodDefinitionish = { + methodName: "ListEvents", + service: WorkflowRunServiceDesc, + requestStream: false, + responseStream: false, + requestType: { + serializeBinary() { + return WorkflowRunServiceListEventsRequest.encode(this).finish(); + }, + } as any, + responseType: { + deserializeBinary(data: Uint8Array) { + const value = WorkflowRunServiceListEventsResponse.decode(data); + return { + ...value, + toObject() { + return value; + }, + }; + }, + } as any, +}; + interface UnaryMethodDefinitionishR extends grpc.UnaryMethodDefinition { requestStream: any; responseStream: any; @@ -3296,6 +4549,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..58c07241e --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.AttestationAttributes.jsonschema.json @@ -0,0 +1,65 @@ +{ + "$id": "controlplane.v1.WorkflowRunEvent.AttestationAttributes.jsonschema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "patternProperties": { + "^(attestation_digest)$": { + "type": "string" + }, + "^(blocking_policies)$": { + "description": "policies that blocked a push", + "items": { + "type": "string" + }, + "type": "array" + }, + "^(cli_version)$": { + "type": "string" + }, + "^(contract_name)$": { + "type": "string" + }, + "^(contract_revision)$": { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + "^(remote_state)$": { + "type": "boolean" + }, + "^(runner_type)$": { + "type": "string" + } + }, + "properties": { + "attestationDigest": { + "type": "string" + }, + "blockingPolicies": { + "description": "policies that blocked a push", + "items": { + "type": "string" + }, + "type": "array" + }, + "cliVersion": { + "type": "string" + }, + "contractName": { + "type": "string" + }, + "contractRevision": { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + "remoteState": { + "type": "boolean" + }, + "runnerType": { + "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..904431301 --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.AttestationAttributes.schema.json @@ -0,0 +1,65 @@ +{ + "$id": "controlplane.v1.WorkflowRunEvent.AttestationAttributes.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "patternProperties": { + "^(attestationDigest)$": { + "type": "string" + }, + "^(blockingPolicies)$": { + "description": "policies that blocked a push", + "items": { + "type": "string" + }, + "type": "array" + }, + "^(cliVersion)$": { + "type": "string" + }, + "^(contractName)$": { + "type": "string" + }, + "^(contractRevision)$": { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + "^(remoteState)$": { + "type": "boolean" + }, + "^(runnerType)$": { + "type": "string" + } + }, + "properties": { + "attestation_digest": { + "type": "string" + }, + "blocking_policies": { + "description": "policies that blocked a push", + "items": { + "type": "string" + }, + "type": "array" + }, + "cli_version": { + "type": "string" + }, + "contract_name": { + "type": "string" + }, + "contract_revision": { + "maximum": 2147483647, + "minimum": -2147483648, + "type": "integer" + }, + "remote_state": { + "type": "boolean" + }, + "runner_type": { + "type": "string" + } + }, + "title": "Attestation Attributes", + "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..64c8c0f9b --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.MaterialAttributes.jsonschema.json @@ -0,0 +1,43 @@ +{ + "$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)$": { + "type": "string" + } + }, + "properties": { + "addedByCollector": { + "type": "boolean" + }, + "digest": { + "type": "string" + }, + "inContract": { + "type": "boolean" + }, + "materialType": { + "type": "string" + }, + "name": { + "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..a81a878e6 --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.MaterialAttributes.schema.json @@ -0,0 +1,43 @@ +{ + "$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)$": { + "type": "string" + } + }, + "properties": { + "added_by_collector": { + "type": "boolean" + }, + "digest": { + "type": "string" + }, + "in_contract": { + "type": "boolean" + }, + "material_type": { + "type": "string" + }, + "name": { + "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.PoliciesAttributes.jsonschema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PoliciesAttributes.jsonschema.json new file mode 100644 index 000000000..870cfe38a --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PoliciesAttributes.jsonschema.json @@ -0,0 +1,16 @@ +{ + "$id": "controlplane.v1.WorkflowRunEvent.PoliciesAttributes.jsonschema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "phase": { + "description": "init or push", + "type": "string" + }, + "policies": { + "$ref": "controlplane.v1.WorkflowRunEvent.PolicyCounts.jsonschema.json" + } + }, + "title": "Policies Attributes", + "type": "object" +} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PoliciesAttributes.schema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PoliciesAttributes.schema.json new file mode 100644 index 000000000..96cf39eb1 --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PoliciesAttributes.schema.json @@ -0,0 +1,16 @@ +{ + "$id": "controlplane.v1.WorkflowRunEvent.PoliciesAttributes.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "phase": { + "description": "init or push", + "type": "string" + }, + "policies": { + "$ref": "controlplane.v1.WorkflowRunEvent.PolicyCounts.schema.json" + } + }, + "title": "Policies 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..7a1b2bd48 --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PolicyCounts.jsonschema.json @@ -0,0 +1,43 @@ +{ + "$id": "controlplane.v1.WorkflowRunEvent.PolicyCounts.jsonschema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "patternProperties": { + "^(violated_policies)$": { + "items": { + "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": { + "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..fdd81c1d5 --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PolicyCounts.schema.json @@ -0,0 +1,43 @@ +{ + "$id": "controlplane.v1.WorkflowRunEvent.PolicyCounts.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "patternProperties": { + "^(violatedPolicies)$": { + "items": { + "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": { + "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..2f2b4a673 --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.jsonschema.json @@ -0,0 +1,98 @@ +{ + "$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", + "minLength": 1, + "type": "string" + }, + "material": { + "$ref": "controlplane.v1.WorkflowRunEvent.MaterialAttributes.jsonschema.json" + }, + "message": { + "maxLength": 1024, + "type": "string" + }, + "policies": { + "$ref": "controlplane.v1.WorkflowRunEvent.PoliciesAttributes.jsonschema.json" + }, + "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", + "TYPE_POLICIES" + ], + "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..d4117149e --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.schema.json @@ -0,0 +1,98 @@ +{ + "$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", + "minLength": 1, + "type": "string" + }, + "material": { + "$ref": "controlplane.v1.WorkflowRunEvent.MaterialAttributes.schema.json" + }, + "message": { + "maxLength": 1024, + "type": "string" + }, + "policies": { + "$ref": "controlplane.v1.WorkflowRunEvent.PoliciesAttributes.schema.json" + }, + "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", + "TYPE_POLICIES" + ], + "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.WorkflowRunServiceListEventsRequest.jsonschema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceListEventsRequest.jsonschema.json new file mode 100644 index 000000000..8204f8dcf --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceListEventsRequest.jsonschema.json @@ -0,0 +1,29 @@ +{ + "$id": "controlplane.v1.WorkflowRunServiceListEventsRequest.jsonschema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "patternProperties": { + "^(after_event_id)$": { + "description": "Optional. Return only the events recorded after this one.", + "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" + }, + "^(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": { + "afterEventId": { + "description": "Optional. Return only the events recorded after this one.", + "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" + }, + "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 List Events Request", + "type": "object" +} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceListEventsRequest.schema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceListEventsRequest.schema.json new file mode 100644 index 000000000..f4855db29 --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceListEventsRequest.schema.json @@ -0,0 +1,29 @@ +{ + "$id": "controlplane.v1.WorkflowRunServiceListEventsRequest.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "patternProperties": { + "^(afterEventId)$": { + "description": "Optional. Return only the events recorded after this one.", + "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" + }, + "^(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": { + "after_event_id": { + "description": "Optional. Return only the events recorded after this one.", + "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" + }, + "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 List Events Request", + "type": "object" +} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceListEventsResponse.jsonschema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceListEventsResponse.jsonschema.json new file mode 100644 index 000000000..88751148f --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceListEventsResponse.jsonschema.json @@ -0,0 +1,15 @@ +{ + "$id": "controlplane.v1.WorkflowRunServiceListEventsResponse.jsonschema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "events": { + "items": { + "$ref": "controlplane.v1.WorkflowRunEvent.jsonschema.json" + }, + "type": "array" + } + }, + "title": "Workflow Run Service List Events Response", + "type": "object" +} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceListEventsResponse.schema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceListEventsResponse.schema.json new file mode 100644 index 000000000..5ecf1973d --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceListEventsResponse.schema.json @@ -0,0 +1,15 @@ +{ + "$id": "controlplane.v1.WorkflowRunServiceListEventsResponse.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "events": { + "items": { + "$ref": "controlplane.v1.WorkflowRunEvent.schema.json" + }, + "type": "array" + } + }, + "title": "Workflow Run Service List Events Response", + "type": "object" +} diff --git a/app/controlplane/cmd/wire_gen.go b/app/controlplane/cmd/wire_gen.go index 1775e07b6..0e63be87a 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, 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/workflowrun.go b/app/controlplane/internal/service/workflowrun.go index 052f8ef8c..695ed833d 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, } } @@ -600,3 +603,198 @@ func (s *WorkflowRunService) validateAndGetProjectID(ctx context.Context, orgID, return project.ID, nil } + +// ListEvents returns the progress events of a run, oldest first. It applies the same checks as View. +func (s *WorkflowRunService) ListEvents(ctx context.Context, req *pb.WorkflowRunServiceListEventsRequest) (*pb.WorkflowRunServiceListEventsResponse, 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(), req.GetAfterEventId()) + if err != nil { + return nil, handleUseCaseErr(ctx, err, s.log) + } + + result := make([]*pb.WorkflowRunEvent, 0, len(events)) + for _, e := range events { + result = append(result, bizWorkflowRunEventToPb(e)) + } + + return &pb.WorkflowRunServiceListEventsResponse{Events: result}, nil +} + +var ( + pbToBizRunEventType = map[pb.WorkflowRunEvent_Type]biz.WorkflowRunEventType{ + pb.WorkflowRunEvent_TYPE_ATTESTATION: biz.WorkflowRunEventTypeAttestation, + pb.WorkflowRunEvent_TYPE_MATERIAL: biz.WorkflowRunEventTypeMaterial, + pb.WorkflowRunEvent_TYPE_POLICIES: biz.WorkflowRunEventTypePolicies, + } + bizToPbRunEventType = map[biz.WorkflowRunEventType]pb.WorkflowRunEvent_Type{ + biz.WorkflowRunEventTypeAttestation: pb.WorkflowRunEvent_TYPE_ATTESTATION, + biz.WorkflowRunEventTypeMaterial: pb.WorkflowRunEvent_TYPE_MATERIAL, + biz.WorkflowRunEventTypePolicies: pb.WorkflowRunEvent_TYPE_POLICIES, + } + 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) { + if in == nil { + return nil, biz.NewErrValidationStr("event is required") + } + + 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(), + BlockingPolicies: a.GetBlockingPolicies(), + }} + 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()), + }} + case *pb.WorkflowRunEvent_Policies: + p := attrs.Policies + out.Attributes = &biz.WorkflowRunEventAttributes{Policies: &biz.WorkflowRunEventPoliciesAttributes{ + Phase: p.GetPhase(), + Policies: pbPolicyCountsToBiz(p.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, + BlockingPolicies: a.BlockingPolicies, + }} + 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), + }} + case attrs.Policies != nil: + p := attrs.Policies + out.Attributes = &pb.WorkflowRunEvent_Policies{Policies: &pb.WorkflowRunEvent_PoliciesAttributes{ + Phase: p.Phase, + Policies: bizPolicyCountsToPb(p.Policies), + }} + } + + 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..adc8e90e3 --- /dev/null +++ b/app/controlplane/internal/service/workflowrunevent_integration_test.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 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 ListEvents 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: "workflow-a", OrgID: s.org.ID, Project: "project-a"}) + s.Require().NoError(err) + s.workflowC, err = s.Workflow.Create(ctx, &biz.WorkflowCreateOpts{Name: "workflow-c", OrgID: s.org.ID, Project: "project-a"}) + s.Require().NoError(err) + _, err = s.Workflow.Create(ctx, &biz.WorkflowCreateOpts{Name: "workflow-b", OrgID: s.org.ID, Project: "project-b"}) + s.Require().NoError(err) + otherWorkflow, err := s.Workflow.Create(ctx, &biz.WorkflowCreateOpts{Name: "workflow-a", OrgID: s.otherOrg.ID, Project: "project-a"}) + s.Require().NoError(err) + + s.projectA, err = s.Project.FindProjectByReference(ctx, s.org.ID, &biz.IdentityReference{Name: ptr("project-a")}) + s.Require().NoError(err) + s.projectB, err = s.Project.FindProjectByReference(ctx, s.org.ID, &biz.IdentityReference{Name: ptr("project-b")}) + 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)}, + }) +} + +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) + 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: "sbom", 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 + wantList 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, + wantList: 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, + wantList: 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 + wantList: 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, + wantList: 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, + wantList: 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, + wantList: 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, + wantList: 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, + wantList: 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.ListEvents(tc.apiCtx(), &pb.WorkflowRunServiceListEventsRequest{WorkflowRunId: tc.runID()}) + s.assertOutcome(tc.wantList, err) + + _, viewErr := s.runSvc.View(tc.apiCtx(), &pb.WorkflowRunServiceViewRequest{Ref: &pb.WorkflowRunServiceViewRequest_Id{Id: tc.runID()}}) + s.assertOutcome(tc.wantList, viewErr) + }) + } +} + +func (s *workflowRunEventRBACIntegrationSuite) TestRecordAndList() { + ctx := s.attCtxForToken(s.org, s.orgToken) + runID := s.runA.ID.String() + + _, err := s.attSvc.RecordEvent(ctx, materialEventRequest(runID)) + s.Require().NoError(err) + + resp, err := s.runSvc.ListEvents(s.apiCtxForToken(s.org, s.orgToken), &pb.WorkflowRunServiceListEventsRequest{WorkflowRunId: runID}) + s.Require().NoError(err) + s.Require().Len(resp.GetEvents(), 1) + + got := resp.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("sbom", got.GetMaterial().GetName()) + s.Equal("sbom.json", got.GetMaterial().GetValue()) + + // 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") + + resp, err = s.runSvc.ListEvents(s.apiCtxForToken(s.org, s.orgToken), &pb.WorkflowRunServiceListEventsRequest{ + WorkflowRunId: runID, AfterEventId: got.GetId(), + }) + s.Require().NoError(err) + s.Require().Len(resp.GetEvents(), 1) + s.Equal(pb.WorkflowRunEvent_SOURCE_CONTROL_PLANE, resp.GetEvents()[0].GetSource()) + s.Equal(pb.WorkflowRunEvent_STATUS_SUCCEEDED, resp.GetEvents()[0].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_POLICIES, Key: "chainloop.policies.init", Status: pb.WorkflowRunEvent_STATUS_SUCCEEDED, + Attributes: &pb.WorkflowRunEvent_Material{Material: &pb.WorkflowRunEvent_MaterialAttributes{Name: "sbom"}}, + }, + }, + { + 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..0765e01fd 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/ListEvents": {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/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/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/workflowrunevent.go b/app/controlplane/pkg/biz/workflowrunevent.go new file mode 100644 index 000000000..1864932cc --- /dev/null +++ b/app/controlplane/pkg/biz/workflowrunevent.go @@ -0,0 +1,308 @@ +// +// 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" + "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" + WorkflowRunEventTypePolicies WorkflowRunEventType = "policies" +) + +// Values implements the ent enum interface +func (WorkflowRunEventType) Values() []string { + return []string{string(WorkflowRunEventTypeAttestation), string(WorkflowRunEventTypeMaterial), string(WorkflowRunEventTypePolicies)} +} + +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"` + Policies *WorkflowRunEventPoliciesAttributes `json:"policies,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"` + BlockingPolicies []string `json:"blocking_policies,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 WorkflowRunEventPoliciesAttributes struct { + Phase string `json:"phase,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. When afterID is set, it returns only + // the events recorded after that one. An afterID of another run returns no events. + List(ctx context.Context, runID uuid.UUID, afterID *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)) + } + + attrs := ev.Attributes + var match bool + switch ev.Type { + case WorkflowRunEventTypeAttestation: + match = attrs == nil || (attrs.Material == nil && attrs.Policies == nil) + case WorkflowRunEventTypeMaterial: + match = attrs == nil || (attrs.Attestation == nil && attrs.Policies == nil) + case WorkflowRunEventTypePolicies: + match = attrs == nil || (attrs.Attestation == nil && attrs.Material == nil) + default: + return NewErrValidationStr(fmt.Sprintf("unsupported event type %q", ev.Type)) + } + + if !match { + 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, afterID 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) + } + + var afterUUID *uuid.UUID + if afterID != "" { + id, err := uuid.Parse(afterID) + if err != nil { + return nil, NewErrInvalidUUID(err) + } + afterUUID = &id + } + + return uc.repo.List(ctx, runUUID, afterUUID) +} + +// 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, + Message: truncateBytes(reason, MaxWorkflowRunEventMessageBytes), + } + + switch runStatus { + case WorkflowRunSuccess: + ev.Status = WorkflowRunEventStatusSucceeded + // Automatic events that succeed have no message + ev.Message = "" + if attestationDigest != "" { + ev.Attributes = &WorkflowRunEventAttributes{ + Attestation: &WorkflowRunEventAttestationAttributes{AttestationDigest: attestationDigest}, + } + } + case WorkflowRunCancelled: + ev.Status = WorkflowRunEventStatusCanceled + case WorkflowRunError: + ev.Status = WorkflowRunEventStatusFailed + 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..0715931e8 --- /dev/null +++ b/app/controlplane/pkg/biz/workflowrunevent_test.go @@ -0,0 +1,145 @@ +// +// 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" +) + +func TestValidateWorkflowRunEvent(t *testing.T) { + material := &WorkflowRunEventAttributes{Material: &WorkflowRunEventMaterialAttributes{Name: "sbom"}} + policies := &WorkflowRunEventAttributes{Policies: &WorkflowRunEventPoliciesAttributes{Phase: "init"}} + + testCases := []struct { + name string + event *WorkflowRunEvent + wantErr string + }{ + { + name: "material event", + event: &WorkflowRunEvent{Type: WorkflowRunEventTypeMaterial, Key: "chainloop.material.sbom", Attributes: material}, + }, + { + name: "event with no attributes", + event: &WorkflowRunEvent{Type: WorkflowRunEventTypeAttestation, Key: "chainloop.push"}, + }, + { + 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: "chainloop.material.sbom", Attributes: policies}, + 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: "chainloop.material.sbom", 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: "abc", n: 5, want: "abc"}, + {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/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..040af037f 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", "policies"}}, + {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..fcc7fb109 --- /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: "CURRENT_TIMESTAMP"}), + 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..89b22d3ff --- /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", "policies": + 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..776420596 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)).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)).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 + if run.State != biz.WorkflowRunInitialized { + return nil + } + + 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..1a47c14d2 --- /dev/null +++ b/app/controlplane/pkg/data/workflowrunevent.go @@ -0,0 +1,183 @@ +// +// 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)).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, afterID *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)) + + if afterID != nil { + // The reference event must belong to the same run + after, err := r.data.DB.WorkflowRunEvent.Query(). + Where(workflowrunevent.ID(*afterID), workflowrunevent.WorkflowRunID(runID)). + Only(ctx) + if err != nil { + if ent.IsNotFound(err) { + return []*biz.WorkflowRunEvent{}, nil + } + return nil, fmt.Errorf("failed to find workflow run event: %w", err) + } + + // Newer than the reference event, with the ID as a tie breaker of the same time + q = q.Where(func(s *sql.Selector) { + s.Where(sql.Or( + sql.GT(s.C(workflowrunevent.FieldCreatedAt), after.CreatedAt), + sql.And( + sql.EQ(s.C(workflowrunevent.FieldCreatedAt), after.CreatedAt), + sql.GT(s.C(workflowrunevent.FieldID), after.ID), + ), + )) + }) + } + + 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() + + ids, err := r.data.DB.WorkflowRunEvent.Query(). + Where(workflowrunevent.CreatedAtLT(t)). + Limit(limit). + IDs(ctx) + if err != nil { + return 0, fmt.Errorf("failed to find old workflow run events: %w", err) + } + + if len(ids) == 0 { + return 0, nil + } + + n, err := r.data.DB.WorkflowRunEvent.Delete().Where(workflowrunevent.IDIn(ids...)).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..4acd8aacd --- /dev/null +++ b/app/controlplane/pkg/data/workflowrunevent_integration_test.go @@ -0,0 +1,346 @@ +// +// 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() + var ids []uuid.UUID + 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) + } + + otherRunID := s.newRun() + otherEv, err := repo.Create(ctx, materialEvent(otherRunID, "x", biz.WorkflowRunEventStatusSucceeded), 10) + s.Require().NoError(err) + + unknown := uuid.New() + testCases := []struct { + name string + runID uuid.UUID + afterID *uuid.UUID + want []uuid.UUID + }{ + {name: "all events, oldest first", runID: runID, want: ids}, + {name: "after the first event", runID: runID, afterID: &ids[0], want: ids[1:]}, + {name: "after the last event", runID: runID, afterID: &ids[2], want: nil}, + {name: "after an event of another run", runID: runID, afterID: &otherEv.ID, want: nil}, + {name: "after an unknown event", runID: runID, afterID: &unknown, want: nil}, + {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, tc.afterID) + 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, nil) + 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, "")) + + s.Require().NoError(s.Repos.WorkflowRunRepo.Expire(ctx, runID)) + + 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, nil) + s.Require().NoError(err) + s.Require().Len(events, 1) + s.Equal(biz.WorkflowRunEventStatusSucceeded, events[0].Status) +} From 3f1b486d79f4511d68a78027b6cab87b766f8547 Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Mon, 30 Nov 2026 20:24:10 +0100 Subject: [PATCH 02/20] feat(controlplane): delete workflow run events after a retention period The run expiry job also deletes run events older than the new workflow_run_events_retention setting, 90 days by default. The Helm chart exposes it as controlplane.attestations.workflowRunEventsRetention. Refs #3825 (M1, R-007) Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1cdb3220-119c-4a14-ac50-52d5437ee4eb --- app/controlplane/cmd/main.go | 3 + app/controlplane/cmd/main_test.go | 10 +- app/controlplane/cmd/wire_gen.go | 2 +- .../conf/controlplane/config/v1/conf.pb.go | 64 +++-- .../conf/controlplane/config/v1/conf.proto | 6 + app/controlplane/pkg/biz/.mockery.yml | 1 + .../pkg/biz/mocks/WorkflowRunEventRepo.go | 270 ++++++++++++++++++ app/controlplane/pkg/biz/workflowrun.go | 41 ++- .../pkg/biz/workflowrun_options_test.go | 14 + app/controlplane/pkg/biz/workflowrun_test.go | 22 +- deployment/chainloop/Chart.yaml | 2 +- deployment/chainloop/README.md | 1 + .../templates/controlplane/configmap.yaml | 1 + deployment/chainloop/values.yaml | 2 + 14 files changed, 406 insertions(+), 33 deletions(-) create mode 100644 app/controlplane/pkg/biz/mocks/WorkflowRunEventRepo.go 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 0e63be87a..d7d6c05c3 100644 --- a/app/controlplane/cmd/wire_gen.go +++ b/app/controlplane/cmd/wire_gen.go @@ -405,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/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/mocks/WorkflowRunEventRepo.go b/app/controlplane/pkg/biz/mocks/WorkflowRunEventRepo.go new file mode 100644 index 000000000..77276923a --- /dev/null +++ b/app/controlplane/pkg/biz/mocks/WorkflowRunEventRepo.go @@ -0,0 +1,270 @@ +// 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, afterID *uuid.UUID) ([]*biz.WorkflowRunEvent, error) { + ret := _mock.Called(ctx, runID, afterID) + + 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, *uuid.UUID) ([]*biz.WorkflowRunEvent, error)); ok { + return returnFunc(ctx, runID, afterID) + } + if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, *uuid.UUID) []*biz.WorkflowRunEvent); ok { + r0 = returnFunc(ctx, runID, afterID) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]*biz.WorkflowRunEvent) + } + } + if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, *uuid.UUID) error); ok { + r1 = returnFunc(ctx, runID, afterID) + } 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 +// - afterID *uuid.UUID +func (_e *WorkflowRunEventRepo_Expecter) List(ctx any, runID any, afterID any) *WorkflowRunEventRepo_List_Call { + return &WorkflowRunEventRepo_List_Call{Call: _e.mock.On("List", ctx, runID, afterID)} +} + +func (_c *WorkflowRunEventRepo_List_Call) Run(run func(ctx context.Context, runID uuid.UUID, afterID *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) + } + var arg2 *uuid.UUID + if args[2] != nil { + arg2 = args[2].(*uuid.UUID) + } + run( + arg0, + arg1, + arg2, + ) + }) + 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, afterID *uuid.UUID) ([]*biz.WorkflowRunEvent, error)) *WorkflowRunEventRepo_List_Call { + _c.Call.Return(run) + return _c +} diff --git a/app/controlplane/pkg/biz/workflowrun.go b/app/controlplane/pkg/biz/workflowrun.go index 521319b25..c4b042760 100644 --- a/app/controlplane/pkg/biz/workflowrun.go +++ b/app/controlplane/pkg/biz/workflowrun.go @@ -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 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..5eccd90c5 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,23 @@ func (s *workflowrunExpirerTestSuite) TestSweepExpireOK() { assert.NoError(err) } +// 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/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 From 5c9a84d01febc469bca9c30c6254407f4451d8a1 Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Mon, 30 Nov 2026 20:33:34 +0100 Subject: [PATCH 03/20] feat(cli): record attestation progress and show it in workflow run describe The attestation commands record a best-effort progress event on init, on each add, and on the policy evaluations. workflow run describe shows a run in progress with its provided and missing materials, the policy results so far, and its timeline. Against a control plane without run events, the recorder turns off and describe shows the run as before. Refs #3825 (M1, R-001, R-002, R-004, R-005, R-008) Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1cdb3220-119c-4a14-ac50-52d5437ee4eb --- app/cli/cmd/workflow_workflow_run_describe.go | 107 +++++ app/cli/pkg/action/attestation_add.go | 17 + app/cli/pkg/action/attestation_init.go | 8 + app/cli/pkg/action/attestation_push.go | 4 + app/cli/pkg/action/runevents.go | 277 +++++++++++++ app/cli/pkg/action/runevents_compat_test.go | 96 +++++ app/cli/pkg/action/runevents_test.go | 370 ++++++++++++++++++ app/cli/pkg/action/workflow_run_describe.go | 291 ++++++++++++++ .../pkg/action/workflow_run_describe_test.go | 206 ++++++++++ 9 files changed, 1376 insertions(+) create mode 100644 app/cli/pkg/action/runevents.go create mode 100644 app/cli/pkg/action/runevents_compat_test.go create mode 100644 app/cli/pkg/action/runevents_test.go diff --git a/app/cli/cmd/workflow_workflow_run_describe.go b/app/cli/cmd/workflow_workflow_run_describe.go index 45c4d7486..5cb60257c 100644 --- a/app/cli/cmd/workflow_workflow_run_describe.go +++ b/app/cli/cmd/workflow_workflow_run_describe.go @@ -134,8 +134,16 @@ 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.AppendRow(table.Row{"Running for", time.Since(*wr.CreatedAt).Round(time.Second).String()}) + gt.Render() + runProgressTables(run.Progress, run.Events) + return nil + } + if run.WorkflowRun.FinishedAt == nil { gt.Render() + runTimelineTable(run.Events, nil) logger.Info().Msg("the attestation crafting process is in progress, it has not been received yet") return nil } @@ -143,6 +151,7 @@ func workflowRunDescribeTableOutput(run *action.WorkflowRunItemFull) error { att := run.Attestation if att == nil { gt.Render() + runTimelineTable(run.Events, nil) logger.Warn().Msg("there was an issue retrieving the attestation") return nil } @@ -175,10 +184,108 @@ func workflowRunDescribeTableOutput(run *action.WorkflowRunItemFull) error { gt.Render() predicateV1Table(att) + // The timeline is history: the signed attestation above is the source of truth + runTimelineTable(run.Events, nil) logger.Info().Msg("you can use the flag \"--output statement\" to see the full in-toto statement") return nil } +// runProgressTables shows the reported progress of a run in progress +func runProgressTables(progress *action.RunProgress, events []*action.RunEvent) { + mt := output.NewTableWriter() + mt.SetTitle(fmt.Sprintf("Materials (reported progress) %d of %d required provided", progress.RequiredProvided, progress.RequiredTotal)) + for _, m := range progress.Materials { + requirement := "optional" + switch { + case !m.InContract: + requirement = "not in contract" + case m.Required: + requirement = "required" + } + + state := text.FgHiRed.Sprint("missing") + if m.Provided { + state = text.FgHiGreen.Sprint("provided") + } + + var notes []string + if s := runPolicyCountSummary(m.Policies); s != "" { + notes = append(notes, s) + } + if m.FailedAdds > 0 { + notes = append(notes, fmt.Sprintf("(%d failed add)", m.FailedAdds)) + } + if m.Error != "" { + notes = append(notes, m.Error) + } + + mt.AppendRow(table.Row{m.Name, m.Type, requirement, state, wrap.String(strings.Join(notes, " "), 80)}) + } + mt.Render() + + if s := runPolicyCountSummary(progress.AttestationPolicies); s != "" { + pt := output.NewTableWriter() + pt.AppendRow(table.Row{"Policies (reported progress)", "attestation: " + s}) + pt.Render() + } + + runTimelineTable(events, progress.Steps) +} + +// runTimelineTable shows the events of a run in order. The duration of a step shows on its first event. +func runTimelineTable(events []*action.RunEvent, steps []*action.RunProgressStep) { + if len(events) == 0 { + return + } + + durations := make(map[string]time.Duration, len(steps)) + for _, s := range steps { + durations[s.Key] = s.Duration + } + + tt := output.NewTableWriter() + tt.SetTitle("Timeline") + seen := make(map[string]bool) + for _, e := range events { + var at, duration string + if e.CreatedAt != nil { + at = e.CreatedAt.Local().Format(time.TimeOnly) + } + if !seen[e.Key] && durations[e.Key] > 0 { + duration = durations[e.Key].Round(time.Second).String() + } + seen[e.Key] = true + + status := e.Status + if status == "failed" { + status = text.FgHiRed.Sprint(status) + } + + tt.AppendRow(table.Row{at, action.RunStepName(e.Key), status, duration, wrap.String(e.Message, 80)}) + } + tt.Render() +} + +// 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..e40abc497 100644 --- a/app/cli/pkg/action/attestation_add.go +++ b/app/cli/pkg/action/attestation_add.go @@ -147,6 +147,23 @@ 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 + } + + for _, r := range results { + _ = events.Record(ctx, materialAddedEvent(crafter, r, false)) + } + + return results, nil +} + +// 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..4fa0cffe0 100644 --- a/app/cli/pkg/action/attestation_init.go +++ b/app/cli/pkg/action/attestation_init.go @@ -338,6 +338,10 @@ func (action *AttestationInit) Run(ctx context.Context, opts *AttestationInitRun return "", err } + // Progress events are best effort, they never stop the attestation + events := newRunEventRecorder(action.CPConnection, attestationID, action.Logger) + _ = events.Record(ctx, attestationStartedEvent(action.c.CraftingState.CraftingState, action.useRemoteState, action.CLIVersion)) + // gate: false can not relax organization or contract enforcement (R-006) if msg := ignoredGateOptOutsWarning(action.c.CraftingState.CraftingState); msg != "" { action.Logger.Warn().Msg(msg) @@ -372,6 +376,9 @@ func (action *AttestationInit) Run(ctx context.Context, opts *AttestationInitRun } action.c.RegisterCollectors(collectors...) action.c.RunCollectors(ctx, attestationID, casBackend) + for _, ev := range collectedMaterialEvents(action.c, action.Logger) { + _ = events.Record(ctx, ev) + } // Evaluate attestation-level policies at init phase attClient := pb.NewAttestationServiceClient(action.CPConnection) @@ -388,6 +395,7 @@ func (action *AttestationInit) Run(ctx context.Context, opts *AttestationInitRun if err := action.c.EvaluateAttestationPolicies(ctx, attestationID, statement, policies.EvalPhaseInit); err != nil { return "", fmt.Errorf("evaluating attestation policies: %w", err) } + _ = events.Record(ctx, policiesEvent(action.c.CraftingState.CraftingState, policies.EvalPhaseInit)) return attestationID, nil } diff --git a/app/cli/pkg/action/attestation_push.go b/app/cli/pkg/action/attestation_push.go index a706856c3..a662a6079 100644 --- a/app/cli/pkg/action/attestation_push.go +++ b/app/cli/pkg/action/attestation_push.go @@ -237,6 +237,10 @@ func (action *AttestationPush) Run(ctx context.Context, attestationID string, ru return nil, fmt.Errorf("evaluating attestation policies: %w", err) } + // Progress events are best effort, they never stop the push + events := newRunEventRecorderFromState(action.CPConnection, crafter.CraftingState.CraftingState, action.Logger) + _ = events.Record(ctx, policiesEvent(crafter.CraftingState.CraftingState, policies.EvalPhasePush)) + // Update the status result with the definitive push-phase evaluation against the final statement attestationStatus.PolicyEvaluations, attestationStatus.HasPolicyViolations = getPolicyEvaluations(crafter) diff --git a/app/cli/pkg/action/runevents.go b/app/cli/pkg/action/runevents.go new file mode 100644 index 000000000..83f3854f7 --- /dev/null +++ b/app/cli/pkg/action/runevents.go @@ -0,0 +1,277 @@ +// +// 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" + "os" + "path/filepath" + "strconv" + "time" + "unicode/utf8" + + pb "github.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/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/policies" + "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 + runEventMaxMessageBytes = 1024 + // runEventMaxValueChars is the limit of the control plane for a material value + runEventMaxValueChars = 256 + + runEventKeyAttestation = "chainloop.attestation" + runEventKeyMaterialPrefix = "chainloop.material." + runEventKeyPoliciesPrefix = "chainloop.policies." +) + +// 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) + } + + 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 +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, + }}, + } +} + +// policiesEvent holds the results of the attestation policies after an evaluation phase +func policiesEvent(state *api.CraftingState, phase policies.EvalPhase) *pb.WorkflowRunEvent { + name := "push" + if phase == policies.EvalPhaseInit { + name = "init" + } + + return &pb.WorkflowRunEvent{ + Type: pb.WorkflowRunEvent_TYPE_POLICIES, + Key: runEventKeyPoliciesPrefix + name, + Status: pb.WorkflowRunEvent_STATUS_SUCCEEDED, + Attributes: &pb.WorkflowRunEvent_Policies{Policies: &pb.WorkflowRunEvent_PoliciesAttributes{ + Phase: name, + Policies: policyCounts(state, ""), + }}, + } +} + +// 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.Material.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.Material.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 = "chainloop.material" + } + + 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), + }}, + } +} + +// 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 +} + +// 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..a3b7b837c --- /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, "ListEvents") + 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..f7d91d9e0 --- /dev/null +++ b/app/cli/pkg/action/runevents_test.go @@ -0,0 +1,370 @@ +// +// 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" + "net" + "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/chainloop-dev/chainloop/pkg/policies" + "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 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: "chainloop.material.sbom", + 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: "sbom", 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) +} + +func TestPolicyCounts(t *testing.T) { + violation := []*api.PolicyEvaluation_Violation{{Message: "bad"}} + 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: "sbom"}, + {Name: "sbom-skipped", MaterialName: "sbom", Skipped: true}, + {Name: "sbom-violated", MaterialName: "sbom", Violations: violation}, + {Name: "sbom-suppressed", MaterialName: "sbom", 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: "sbom", + want: &pb.WorkflowRunEvent_PolicyCounts{Evaluated: 4, Passed: 2, Violated: 1, Skipped: 1, ViolatedPolicies: []string{"sbom-violated"}}, + }, + { + name: "material with no policies", + material: "image", + 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" + materialValueText = "commit-1234" + ) + 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", materialValueText, 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"), + policiesEvent(c.CraftingState.CraftingState, policies.EvalPhaseInit), + } + + 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, materialValueText, 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: "commit-1234", wantEvent: pb.WorkflowRunEvent_STATUS_SUCCEEDED}, + {name: "add succeeds, event rejected", value: "commit-1234", eventErr: status.Error(codes.FailedPrecondition, "not in progress"), wantEvent: pb.WorkflowRunEvent_STATUS_SUCCEEDED}, + {name: "add succeeds, older control plane", value: "commit-1234", eventErr: status.Error(codes.Unimplemented, "unknown method"), wantEvent: pb.WorkflowRunEvent_STATUS_SUCCEEDED}, + {name: "add fails", value: "/does/not/exist.json", kind: "SBOM_CYCLONEDX_JSON", wantErr: true, wantEvent: pb.WorkflowRunEvent_STATUS_FAILED}, + {name: "add fails, event fails", value: "/does/not/exist.json", kind: "SBOM_CYCLONEDX_JSON", 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 = "sbom" + } + 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()) + } + }) + } +} diff --git a/app/cli/pkg/action/workflow_run_describe.go b/app/cli/pkg/action/workflow_run_describe.go index 0f64ff021..c3a098783 100644 --- a/app/cli/pkg/action/workflow_run_describe.go +++ b/app/cli/pkg/action/workflow_run_describe.go @@ -23,9 +23,11 @@ import ( "fmt" "sort" "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" attv1 "github.com/chainloop-dev/chainloop/pkg/attestation/crafter/api/attestation/v1" "github.com/chainloop-dev/chainloop/pkg/attestation/renderer/chainloop" "github.com/chainloop-dev/chainloop/pkg/attestation/verifier" @@ -37,6 +39,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 +52,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 from the contract and the events + Progress *RunProgress `json:"progress,omitempty"` } type WorkflowRunAttestationItem struct { @@ -209,6 +217,12 @@ func (action *WorkflowRunDescribe) Run(ctx context.Context, opts *WorkflowRunDes item.WorkflowRun.FinishedAt = toTimePtr(wr.FinishedAt.AsTime()) } + // Progress events are optional: with no events, describe shows the run as before + item.Events = action.listRunEvents(ctx, wr.GetId()) + if wr.GetStatus() == pb.RunStatus_RUN_STATUS_INITIALIZED && len(item.Events) > 0 { + item.Progress = buildRunProgress(runContractMaterials(wr.GetContractVersion()), item.Events, time.Now()) + } + att := resp.GetResult().GetAttestation() // The item does not have associated attestation if att == nil { @@ -514,3 +528,280 @@ 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"` + Policies *RunEventPoliciesAttribute `json:"policies,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,omitempty"` + CLIVersion string `json:"cli_version,omitempty"` + AttestationDigest string `json:"attestation_digest,omitempty"` + BlockingPolicies []string `json:"blocking_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,omitempty"` + Policies *RunEventPolicyCount `json:"policies,omitempty"` +} + +type RunEventPoliciesAttribute struct { + Phase string `json:"phase"` + 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, built from the contract and the reported events +type RunProgress struct { + Materials []*RunProgressMaterial `json:"materials"` + // Results of the attestation policies of the latest evaluation phase + AttestationPolicies *RunEventPolicyCount `json:"attestation_policies,omitempty"` + RequiredTotal int `json:"required_total"` + RequiredProvided int `json:"required_provided"` + Steps []*RunProgressStep `json:"steps"` +} + +type RunProgressMaterial struct { + Name string `json:"name"` + Type string `json:"type"` + InContract bool `json:"in_contract"` + Required bool `json:"required"` + Provided bool `json:"provided"` + Value string `json:"value,omitempty"` + Policies *RunEventPolicyCount `json:"policies,omitempty"` + FailedAdds int `json:"failed_adds,omitempty"` + // error of the latest add, when it failed + Error string `json:"error,omitempty"` +} + +// RunProgressStep groups the events with the same key +type RunProgressStep struct { + Key string `json:"key"` + Name string `json:"name"` + StartedAt *time.Time `json:"started_at,omitempty"` + Duration time.Duration `json:"duration"` + Status string `json:"status"` + Events int `json:"events"` +} + +// listRunEvents returns the events of the run. It returns nil when the control plane cannot +// return them, for example an older one, so that describe shows the run as before. +func (action *WorkflowRunDescribe) listRunEvents(ctx context.Context, runID string) []*RunEvent { + client := pb.NewWorkflowRunServiceClient(action.cfg.CPConnection) + resp, err := client.ListEvents(ctx, &pb.WorkflowRunServiceListEventsRequest{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 events") + } else { + action.cfg.Logger.Warn().Err(err).Msg("failed to retrieve the progress events of the run") + } + return nil + } + + events := make([]*RunEvent, 0, len(resp.GetEvents())) + for _, e := range resp.GetEvents() { + events = append(events, pbRunEventToAction(e)) + } + + return events +} + +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(), + BlockingPolicies: a.GetBlockingPolicies(), + } + } + + 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()), + } + } + + if p := in.GetPolicies(); p != nil { + out.Policies = &RunEventPoliciesAttribute{Phase: p.GetPhase(), Policies: pbRunEventPolicyCountToAction(p.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(), + } +} + +// runContractMaterials returns the materials of the contract of the run, from the V2 schema when present +func runContractMaterials(cv *pb.WorkflowContractVersionItem) []*schemaapi.CraftingSchema_Material { + if v2 := parseContractV2(cv.GetRawContract()); v2 != nil && v2.GetSpec() != nil { + return v2.GetSpec().GetMaterials() + } + + //nolint:staticcheck // the V1 schema is the fallback for contracts with no V2 body + return cv.GetV1().GetMaterials() +} + +// buildRunProgress joins the contract materials with the latest event of each material, and +// groups the events by key into steps. now is the time used for the duration of open steps. +func buildRunProgress(contractMaterials []*schemaapi.CraftingSchema_Material, events []*RunEvent, now time.Time) *RunProgress { + progress := &RunProgress{Materials: make([]*RunProgressMaterial, 0)} + + // latest event and failed adds of each material, in the order they were first reported + latest := make(map[string]*RunEvent) + failed := make(map[string]int) + var order []string + for _, e := range events { + switch { + case e.Material != nil && e.Material.Name != "": + name := e.Material.Name + if _, ok := latest[name]; !ok { + order = append(order, name) + } + latest[name] = e + if e.Status == "failed" { + failed[name]++ + } + case e.Policies != nil: + progress.AttestationPolicies = e.Policies.Policies + } + } + + fill := func(m *RunProgressMaterial) { + e, ok := latest[m.Name] + if !ok { + return + } + + m.FailedAdds = failed[m.Name] + if e.Status == "failed" { + m.Error = e.Message + return + } + + m.Provided = true + m.Value = e.Material.Value + m.Policies = e.Material.Policies + if m.Type == "" { + m.Type = e.Material.MaterialType + } + } + + inContract := make(map[string]struct{}, len(contractMaterials)) + for _, cm := range contractMaterials { + inContract[cm.GetName()] = struct{}{} + // Grouped materials are required at the group level, as attestation status shows them + m := &RunProgressMaterial{ + Name: cm.GetName(), Type: cm.GetType().String(), InContract: true, + Required: !cm.GetOptional() && cm.GetGroup() == "", + } + fill(m) + if m.Required { + progress.RequiredTotal++ + if m.Provided { + progress.RequiredProvided++ + } + } + progress.Materials = append(progress.Materials, m) + } + + for _, name := range order { + if _, ok := inContract[name]; ok { + continue + } + m := &RunProgressMaterial{Name: name} + fill(m) + progress.Materials = append(progress.Materials, m) + } + + progress.Steps = buildRunSteps(events, now) + + return progress +} + +// buildRunSteps groups the events by key, in the order of their first event +func buildRunSteps(events []*RunEvent, now time.Time) []*RunProgressStep { + steps := make([]*RunProgressStep, 0) + byKey := make(map[string]*RunProgressStep) + last := make(map[string]*time.Time) + + for _, e := range events { + step, ok := byKey[e.Key] + if !ok { + step = &RunProgressStep{Key: e.Key, Name: RunStepName(e.Key), StartedAt: e.CreatedAt} + byKey[e.Key] = step + steps = append(steps, step) + } + step.Events++ + step.Status = e.Status + last[e.Key] = e.CreatedAt + } + + for _, s := range steps { + end := last[s.Key] + if s.Status == "started" { + end = &now + } + if s.StartedAt != nil && end != nil && end.After(*s.StartedAt) { + s.Duration = end.Sub(*s.StartedAt) + } + } + + return steps +} + +// RunStepName is the name of a step shown to the user: the key with no automatic prefix +func RunStepName(key string) string { + name := strings.TrimPrefix(key, "chainloop.") + if material, ok := strings.CutPrefix(name, "material."); ok { + return material + } + + return name +} diff --git a/app/cli/pkg/action/workflow_run_describe_test.go b/app/cli/pkg/action/workflow_run_describe_test.go index ff5266fe1..bd2aba42c 100644 --- a/app/cli/pkg/action/workflow_run_describe_test.go +++ b/app/cli/pkg/action/workflow_run_describe_test.go @@ -20,11 +20,19 @@ import ( "encoding/json" "os" "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/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 +164,201 @@ func TestPBPolicyEvaluationsRefToAction(t *testing.T) { }) } } + +func materialRunEvent(at time.Time, name, status, message string) *RunEvent { + return &RunEvent{ + CreatedAt: &at, Type: "material", Key: "chainloop.material." + name, Status: status, Message: message, + Material: &RunEventMaterial{Name: name, MaterialType: "SBOM_CYCLONEDX_JSON", Value: name + ".json"}, + } +} + +func TestBuildRunProgress(t *testing.T) { + start := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC) + now := start.Add(5*time.Minute + 45*time.Second) + contract := []*schemaapi.CraftingSchema_Material{ + {Name: "sbom", Type: schemaapi.CraftingSchema_Material_SBOM_CYCLONEDX_JSON}, + {Name: "image", Type: schemaapi.CraftingSchema_Material_CONTAINER_IMAGE}, + {Name: "sast-report", Type: schemaapi.CraftingSchema_Material_SARIF, Optional: true}, + } + started := &RunEvent{CreatedAt: &start, Type: "attestation", Key: "chainloop.attestation", Status: "started"} + + testCases := []struct { + name string + events []*RunEvent + // expected state of each material, by name + want map[string]RunProgressMaterial + wantRequired [2]int // provided, total + wantStepDuration map[string]time.Duration + }{ + { + name: "failed add shows the material as missing with the error", + events: []*RunEvent{ + started, + materialRunEvent(start.Add(3*time.Minute), "sbom", "failed", "invalid CycloneDX document"), + }, + want: map[string]RunProgressMaterial{ + "sbom": {Required: true, InContract: true, Provided: false, FailedAdds: 1, Error: "invalid CycloneDX document"}, + "image": {Required: true, InContract: true}, + "sast-report": {InContract: true}, + }, + wantRequired: [2]int{0, 2}, + wantStepDuration: map[string]time.Duration{"chainloop.attestation": 5*time.Minute + 45*time.Second}, + }, + { + name: "failed then repeated add shows the material as provided", + events: []*RunEvent{ + started, + materialRunEvent(start.Add(3*time.Minute), "sbom", "failed", "invalid CycloneDX document"), + materialRunEvent(start.Add(4*time.Minute), "sbom", "succeeded", ""), + }, + want: map[string]RunProgressMaterial{ + "sbom": {Required: true, InContract: true, Provided: true, FailedAdds: 1, Value: "sbom.json"}, + "image": {Required: true, InContract: true}, + }, + wantRequired: [2]int{1, 2}, + wantStepDuration: map[string]time.Duration{"chainloop.material.sbom": time.Minute}, + }, + { + name: "material not in the contract", + events: []*RunEvent{ + started, + materialRunEvent(start.Add(time.Minute), "build-log", "succeeded", ""), + }, + want: map[string]RunProgressMaterial{ + "build-log": {InContract: false, Provided: true, Value: "build-log.json"}, + "sbom": {Required: true, InContract: true}, + }, + wantRequired: [2]int{0, 2}, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + got := buildRunProgress(contract, tc.events, now) + + byName := make(map[string]*RunProgressMaterial) + for _, m := range got.Materials { + byName[m.Name] = m + } + + for name, want := range tc.want { + m, ok := byName[name] + require.True(t, ok, "material %q", name) + assert.Equal(t, want.Required, m.Required, "required %q", name) + assert.Equal(t, want.InContract, m.InContract, "in contract %q", name) + assert.Equal(t, want.Provided, m.Provided, "provided %q", name) + assert.Equal(t, want.FailedAdds, m.FailedAdds, "failed adds %q", name) + assert.Equal(t, want.Error, m.Error, "error %q", name) + assert.Equal(t, want.Value, m.Value, "value %q", name) + } + + assert.Equal(t, tc.wantRequired[0], got.RequiredProvided) + assert.Equal(t, tc.wantRequired[1], got.RequiredTotal) + + for key, d := range tc.wantStepDuration { + var found bool + for _, s := range got.Steps { + if s.Key == key { + found = true + assert.Equal(t, d, s.Duration, "duration of %q", key) + } + } + assert.True(t, found, "step %q", key) + } + }) + } +} + +// fakeRunViewServer serves View for one run, and ListEvents with a configured answer +type fakeRunViewServer struct { + pb.UnimplementedWorkflowRunServiceServer + status pb.RunStatus + events []*pb.WorkflowRunEvent + eventsErr 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(), + ContractVersion: &pb.WorkflowContractVersionItem{ + Contract: &pb.WorkflowContractVersionItem_V1{V1: &schemaapi.CraftingSchema{Materials: []*schemaapi.CraftingSchema_Material{ + {Name: "sbom", Type: schemaapi.CraftingSchema_Material_SBOM_CYCLONEDX_JSON}, + }}}, + }, + }, + }}, nil +} + +func (f *fakeRunViewServer) ListEvents(context.Context, *pb.WorkflowRunServiceListEventsRequest) (*pb.WorkflowRunServiceListEventsResponse, error) { + if f.eventsErr != nil { + return nil, f.eventsErr + } + + return &pb.WorkflowRunServiceListEventsResponse{Events: f.events}, 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: "chainloop.material.sbom", Status: pb.WorkflowRunEvent_STATUS_FAILED, Message: "invalid CycloneDX document", + Attributes: &pb.WorkflowRunEvent_Material{Material: &pb.WorkflowRunEvent_MaterialAttributes{Name: "sbom", InContract: true}}, + } + expired := &pb.WorkflowRunEvent{ + Id: "2", CreatedAt: timestamppb.Now(), Source: pb.WorkflowRunEvent_SOURCE_CONTROL_PLANE, Type: pb.WorkflowRunEvent_TYPE_ATTESTATION, + Key: "chainloop.attestation", Status: pb.WorkflowRunEvent_STATUS_FAILED, Message: "expired", + } + + testCases := []struct { + name string + server *fakeRunViewServer + wantEvents int + wantProgress bool + }{ + { + name: "run in progress", + server: &fakeRunViewServer{status: pb.RunStatus_RUN_STATUS_INITIALIZED, events: []*pb.WorkflowRunEvent{sbomFailed}}, + wantEvents: 1, + wantProgress: true, + }, + { + 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 in progress 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, eventsErr: status.Error(codes.Unimplemented, "unknown method")}, + }, + { + name: "other error", + server: &fakeRunViewServer{status: pb.RunStatus_RUN_STATUS_INITIALIZED, eventsErr: 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 events") + + assert.Len(t, got.Events, tc.wantEvents) + if !tc.wantProgress { + assert.Nil(t, got.Progress) + return + } + + require.NotNil(t, got.Progress) + require.Len(t, got.Progress.Materials, 1) + sbom := got.Progress.Materials[0] + assert.False(t, sbom.Provided) + assert.Equal(t, "invalid CycloneDX document", sbom.Error) + }) + } +} From 09fd46e2f40b19a62b66d99d81ede3194aeb41dd Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Mon, 30 Nov 2026 21:25:40 +0100 Subject: [PATCH 04/20] refactor: fold policy results into the attestation and push events Drop the chainloop.policies.* events. The started event, now sent at the end of init, carries the init policy results. A new chainloop.push event, sent before the attestation is stored, carries the push policy results and fails with the blocking policies when a gate blocks the push. Refs #3825 (M1, R-001) Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1cdb3220-119c-4a14-ac50-52d5437ee4eb --- app/cli/pkg/action/attestation_init.go | 16 +- app/cli/pkg/action/attestation_push.go | 2 +- app/cli/pkg/action/runevents.go | 47 +++-- app/cli/pkg/action/runevents_test.go | 65 ++++++- app/cli/pkg/action/workflow_run_describe.go | 55 +++--- .../pkg/action/workflow_run_describe_test.go | 12 ++ .../api/controlplane/v1/workflow_run.pb.go | 170 +++++++++--------- .../api/controlplane/v1/workflow_run.proto | 17 +- .../frontend/controlplane/v1/workflow_run.ts | 116 ++++++------ ...vent.AttestationAttributes.jsonschema.json | 18 +- ...RunEvent.AttestationAttributes.schema.json | 18 +- ...unEvent.PoliciesAttributes.jsonschema.json | 16 -- ...lowRunEvent.PoliciesAttributes.schema.json | 16 -- ...lowRunEvent.PushAttributes.jsonschema.json | 29 +++ ...orkflowRunEvent.PushAttributes.schema.json | 29 +++ ...lplane.v1.WorkflowRunEvent.jsonschema.json | 6 +- ...ntrolplane.v1.WorkflowRunEvent.schema.json | 6 +- .../internal/service/workflowrun.go | 28 +-- .../workflowrunevent_integration_test.go | 2 +- .../biz/attestationstate_integration_test.go | 12 +- app/controlplane/pkg/biz/workflowrunevent.go | 33 ++-- .../pkg/biz/workflowrunevent_test.go | 4 +- .../pkg/data/ent/migrate/schema.go | 2 +- .../ent/workflowrunevent/workflowrunevent.go | 2 +- 24 files changed, 417 insertions(+), 304 deletions(-) delete mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PoliciesAttributes.jsonschema.json delete mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PoliciesAttributes.schema.json create mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PushAttributes.jsonschema.json create mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PushAttributes.schema.json diff --git a/app/cli/pkg/action/attestation_init.go b/app/cli/pkg/action/attestation_init.go index 4fa0cffe0..d895f0636 100644 --- a/app/cli/pkg/action/attestation_init.go +++ b/app/cli/pkg/action/attestation_init.go @@ -338,10 +338,6 @@ func (action *AttestationInit) Run(ctx context.Context, opts *AttestationInitRun return "", err } - // Progress events are best effort, they never stop the attestation - events := newRunEventRecorder(action.CPConnection, attestationID, action.Logger) - _ = events.Record(ctx, attestationStartedEvent(action.c.CraftingState.CraftingState, action.useRemoteState, action.CLIVersion)) - // gate: false can not relax organization or contract enforcement (R-006) if msg := ignoredGateOptOutsWarning(action.c.CraftingState.CraftingState); msg != "" { action.Logger.Warn().Msg(msg) @@ -376,9 +372,6 @@ func (action *AttestationInit) Run(ctx context.Context, opts *AttestationInitRun } action.c.RegisterCollectors(collectors...) action.c.RunCollectors(ctx, attestationID, casBackend) - for _, ev := range collectedMaterialEvents(action.c, action.Logger) { - _ = events.Record(ctx, ev) - } // Evaluate attestation-level policies at init phase attClient := pb.NewAttestationServiceClient(action.CPConnection) @@ -395,7 +388,14 @@ func (action *AttestationInit) Run(ctx context.Context, opts *AttestationInitRun if err := action.c.EvaluateAttestationPolicies(ctx, attestationID, statement, policies.EvalPhaseInit); err != nil { return "", fmt.Errorf("evaluating attestation policies: %w", err) } - _ = events.Record(ctx, policiesEvent(action.c.CraftingState.CraftingState, policies.EvalPhaseInit)) + + // 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/attestation_push.go b/app/cli/pkg/action/attestation_push.go index a662a6079..86a755a42 100644 --- a/app/cli/pkg/action/attestation_push.go +++ b/app/cli/pkg/action/attestation_push.go @@ -239,7 +239,7 @@ func (action *AttestationPush) Run(ctx context.Context, attestationID string, ru // Progress events are best effort, they never stop the push events := newRunEventRecorderFromState(action.CPConnection, crafter.CraftingState.CraftingState, action.Logger) - _ = events.Record(ctx, policiesEvent(crafter.CraftingState.CraftingState, policies.EvalPhasePush)) + _ = events.Record(ctx, pushEvent(crafter.CraftingState.CraftingState, bypassPolicyCheck)) // Update the status result with the definitive push-phase evaluation against the final statement attestationStatus.PolicyEvaluations, attestationStatus.HasPolicyViolations = getPolicyEvaluations(crafter) diff --git a/app/cli/pkg/action/runevents.go b/app/cli/pkg/action/runevents.go index 83f3854f7..689f6eaaa 100644 --- a/app/cli/pkg/action/runevents.go +++ b/app/cli/pkg/action/runevents.go @@ -20,13 +20,14 @@ import ( "os" "path/filepath" "strconv" + "strings" "time" "unicode/utf8" pb "github.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/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/policies" + "github.com/rs/zerolog" "google.golang.org/grpc" "google.golang.org/grpc/codes" @@ -43,7 +44,7 @@ const ( runEventKeyAttestation = "chainloop.attestation" runEventKeyMaterialPrefix = "chainloop.material." - runEventKeyPoliciesPrefix = "chainloop.policies." + runEventKeyPush = "chainloop.push" ) // runEventRecorder sends progress events of an attestation to the control plane. @@ -112,7 +113,8 @@ func (r *runEventRecorder) Record(ctx context.Context, event *pb.WorkflowRunEven return err } -// attestationStartedEvent opens the timeline of the run +// 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 @@ -130,26 +132,39 @@ func attestationStartedEvent(state *api.CraftingState, remoteState bool, cliVers RunnerType: att.GetRunnerType().String(), RemoteState: remoteState, CliVersion: cliVersion, + Policies: policyCounts(state, ""), }}, } } -// policiesEvent holds the results of the attestation policies after an evaluation phase -func policiesEvent(state *api.CraftingState, phase policies.EvalPhase) *pb.WorkflowRunEvent { - name := "push" - if phase == policies.EvalPhaseInit { - name = "init" +// pushEvent is sent after the push-phase policies and before the attestation is stored. +// It fails when a policy gate blocks the push, unless the check is bypassed. +func pushEvent(state *api.CraftingState, bypassPolicyCheck bool) *pb.WorkflowRunEvent { + ev := &pb.WorkflowRunEvent{ + Type: pb.WorkflowRunEvent_TYPE_PUSH, + Key: runEventKeyPush, + Status: pb.WorkflowRunEvent_STATUS_SUCCEEDED, } + attrs := &pb.WorkflowRunEvent_PushAttributes{Policies: policyCounts(state, "")} + ev.Attributes = &pb.WorkflowRunEvent_Push{Push: attrs} - return &pb.WorkflowRunEvent{ - Type: pb.WorkflowRunEvent_TYPE_POLICIES, - Key: runEventKeyPoliciesPrefix + name, - Status: pb.WorkflowRunEvent_STATUS_SUCCEEDED, - Attributes: &pb.WorkflowRunEvent_Policies{Policies: &pb.WorkflowRunEvent_PoliciesAttributes{ - Phase: name, - Policies: policyCounts(state, ""), - }}, + if bypassPolicyCheck { + return ev } + + // The same rule as the gate check of the push command + for _, e := range state.GetAttestation().GetPolicyEvaluations() { + if e.GetGate() && hasUnsuppressedViolation(e) { + attrs.BlockingPolicies = append(attrs.BlockingPolicies, e.GetName()) + } + } + + if len(attrs.BlockingPolicies) > 0 { + ev.Status = pb.WorkflowRunEvent_STATUS_FAILED + ev.Message = "blocked by policy gates: " + strings.Join(attrs.BlockingPolicies, ", ") + } + + return ev } // materialAddedEvent describes a material in the crafting state. It holds only the diff --git a/app/cli/pkg/action/runevents_test.go b/app/cli/pkg/action/runevents_test.go index f7d91d9e0..40e6951f7 100644 --- a/app/cli/pkg/action/runevents_test.go +++ b/app/cli/pkg/action/runevents_test.go @@ -30,7 +30,6 @@ import ( 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/chainloop-dev/chainloop/pkg/policies" "github.com/rs/zerolog" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -208,6 +207,68 @@ func TestRunEventRecorderLimits(t *testing.T) { assert.Len(t, got[0].GetEvent().GetMaterial().GetValue(), 256) } +// The push event fails when a gate blocks the push, with the same rule as the push command +func TestPushEvent(t *testing.T) { + violation := []*api.PolicyEvaluation_Violation{{Message: "bad"}} + suppressed := []*api.PolicyEvaluation_Violation{{Message: "not affected", Suppress: true}} + + testCases := []struct { + name string + evaluations []*api.PolicyEvaluation + bypass bool + wantStatus pb.WorkflowRunEvent_Status + wantBlocking []string + }{ + { + name: "no gate", + evaluations: []*api.PolicyEvaluation{{Name: "advisory", Violations: violation}}, + wantStatus: pb.WorkflowRunEvent_STATUS_SUCCEEDED, + }, + { + name: "gated attestation policy with violations", + evaluations: []*api.PolicyEvaluation{{Name: "att-gate", Gate: true, Violations: violation}, {Name: "ok", Gate: true}}, + wantStatus: pb.WorkflowRunEvent_STATUS_FAILED, + wantBlocking: []string{"att-gate"}, + }, + { + name: "gated material policy with violations", + evaluations: []*api.PolicyEvaluation{{Name: "sbom-gate", MaterialName: "sbom", Gate: true, Violations: violation}}, + wantStatus: pb.WorkflowRunEvent_STATUS_FAILED, + wantBlocking: []string{"sbom-gate"}, + }, + { + name: "gated policy with suppressed violations only", + evaluations: []*api.PolicyEvaluation{{Name: "att-gate", Gate: true, Violations: suppressed}}, + wantStatus: pb.WorkflowRunEvent_STATUS_SUCCEEDED, + }, + { + name: "gate bypassed", + evaluations: []*api.PolicyEvaluation{{Name: "att-gate", Gate: true, Violations: violation}}, + bypass: true, + wantStatus: pb.WorkflowRunEvent_STATUS_SUCCEEDED, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + state := &api.CraftingState{Attestation: &api.Attestation{PolicyEvaluations: tc.evaluations}} + ev := pushEvent(state, tc.bypass) + + assert.Equal(t, "chainloop.push", ev.GetKey()) + assert.Equal(t, pb.WorkflowRunEvent_TYPE_PUSH, ev.GetType()) + assert.Equal(t, tc.wantStatus, ev.GetStatus()) + assert.Equal(t, tc.wantBlocking, ev.GetPush().GetBlockingPolicies()) + if tc.wantStatus == pb.WorkflowRunEvent_STATUS_FAILED { + assert.Contains(t, ev.GetMessage(), tc.wantBlocking[0]) + } else { + assert.Empty(t, ev.GetMessage()) + } + // the counts cover the attestation policies only, material policies are in material events + assert.Equal(t, policyCounts(state, ""), ev.GetPush().GetPolicies()) + }) + } +} + func TestPolicyCounts(t *testing.T) { violation := []*api.PolicyEvaluation_Violation{{Message: "bad"}} suppressed := []*api.PolicyEvaluation_Violation{{Message: "not affected", Suppress: true}} @@ -288,7 +349,7 @@ func TestMaterialEventHoldsOnlySafeData(t *testing.T) { events := []*pb.WorkflowRunEvent{ materialAddedEvent(c, res, false), attestationStartedEvent(c.CraftingState.CraftingState, true, "v1.2.3"), - policiesEvent(c.CraftingState.CraftingState, policies.EvalPhaseInit), + pushEvent(c.CraftingState.CraftingState, false), } for _, ev := range events { diff --git a/app/cli/pkg/action/workflow_run_describe.go b/app/cli/pkg/action/workflow_run_describe.go index c3a098783..0e773cfab 100644 --- a/app/cli/pkg/action/workflow_run_describe.go +++ b/app/cli/pkg/action/workflow_run_describe.go @@ -531,26 +531,27 @@ func loadCertificates(certPath string) ([]*x509.Certificate, error) { // 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"` - Policies *RunEventPoliciesAttribute `json:"policies,omitempty"` + 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"` + Push *RunEventPush `json:"push,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,omitempty"` - CLIVersion string `json:"cli_version,omitempty"` - AttestationDigest string `json:"attestation_digest,omitempty"` - BlockingPolicies []string `json:"blocking_policies,omitempty"` + 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 *RunEventPolicyCount `json:"policies,omitempty"` } type RunEventMaterial struct { @@ -563,9 +564,10 @@ type RunEventMaterial struct { Policies *RunEventPolicyCount `json:"policies,omitempty"` } -type RunEventPoliciesAttribute struct { - Phase string `json:"phase"` - Policies *RunEventPolicyCount `json:"policies,omitempty"` +type RunEventPush struct { + // results of the attestation policies evaluated at push + Policies *RunEventPolicyCount `json:"policies,omitempty"` + BlockingPolicies []string `json:"blocking_policies,omitempty"` } type RunEventPolicyCount struct { @@ -649,7 +651,7 @@ func pbRunEventToAction(in *pb.WorkflowRunEvent) *RunEvent { out.Attestation = &RunEventAttestation{ ContractName: a.GetContractName(), ContractRevision: a.GetContractRevision(), RunnerType: a.GetRunnerType(), RemoteState: a.GetRemoteState(), CLIVersion: a.GetCliVersion(), AttestationDigest: a.GetAttestationDigest(), - BlockingPolicies: a.GetBlockingPolicies(), + Policies: pbRunEventPolicyCountToAction(a.GetPolicies()), } } @@ -660,8 +662,8 @@ func pbRunEventToAction(in *pb.WorkflowRunEvent) *RunEvent { } } - if p := in.GetPolicies(); p != nil { - out.Policies = &RunEventPoliciesAttribute{Phase: p.GetPhase(), Policies: pbRunEventPolicyCountToAction(p.GetPolicies())} + if p := in.GetPush(); p != nil { + out.Push = &RunEventPush{Policies: pbRunEventPolicyCountToAction(p.GetPolicies()), BlockingPolicies: p.GetBlockingPolicies()} } return out @@ -708,8 +710,11 @@ func buildRunProgress(contractMaterials []*schemaapi.CraftingSchema_Material, ev if e.Status == "failed" { failed[name]++ } - case e.Policies != nil: - progress.AttestationPolicies = e.Policies.Policies + // the latest attestation policy results: init, then push + case e.Attestation != nil && e.Attestation.Policies != nil: + progress.AttestationPolicies = e.Attestation.Policies + case e.Push != nil && e.Push.Policies != nil: + progress.AttestationPolicies = e.Push.Policies } } diff --git a/app/cli/pkg/action/workflow_run_describe_test.go b/app/cli/pkg/action/workflow_run_describe_test.go index bd2aba42c..27f034ad6 100644 --- a/app/cli/pkg/action/workflow_run_describe_test.go +++ b/app/cli/pkg/action/workflow_run_describe_test.go @@ -269,6 +269,18 @@ func TestBuildRunProgress(t *testing.T) { } } +// The attestation policy results come from the started event, then from the push event +func TestBuildRunProgressAttestationPolicies(t *testing.T) { + now := time.Now() + initCounts := &RunEventPolicyCount{Evaluated: 2, Passed: 2} + pushCounts := &RunEventPolicyCount{Evaluated: 3, Passed: 2, Violated: 1} + started := &RunEvent{CreatedAt: &now, Key: "chainloop.attestation", Status: "started", Attestation: &RunEventAttestation{Policies: initCounts}} + push := &RunEvent{CreatedAt: &now, Key: "chainloop.push", Status: "failed", Push: &RunEventPush{Policies: pushCounts, BlockingPolicies: []string{"gate"}}} + + assert.Equal(t, initCounts, buildRunProgress(nil, []*RunEvent{started}, now).AttestationPolicies) + assert.Equal(t, pushCounts, buildRunProgress(nil, []*RunEvent{started, push}, now).AttestationPolicies) +} + // fakeRunViewServer serves View for one run, and ListEvents with a configured answer type fakeRunViewServer struct { pb.UnimplementedWorkflowRunServiceServer diff --git a/app/controlplane/api/controlplane/v1/workflow_run.pb.go b/app/controlplane/api/controlplane/v1/workflow_run.pb.go index 92ee26b56..e4436cc06 100644 --- a/app/controlplane/api/controlplane/v1/workflow_run.pb.go +++ b/app/controlplane/api/controlplane/v1/workflow_run.pb.go @@ -143,7 +143,7 @@ const ( WorkflowRunEvent_TYPE_UNSPECIFIED WorkflowRunEvent_Type = 0 WorkflowRunEvent_TYPE_ATTESTATION WorkflowRunEvent_Type = 1 WorkflowRunEvent_TYPE_MATERIAL WorkflowRunEvent_Type = 2 - WorkflowRunEvent_TYPE_POLICIES WorkflowRunEvent_Type = 3 + WorkflowRunEvent_TYPE_PUSH WorkflowRunEvent_Type = 3 ) // Enum value maps for WorkflowRunEvent_Type. @@ -152,13 +152,13 @@ var ( 0: "TYPE_UNSPECIFIED", 1: "TYPE_ATTESTATION", 2: "TYPE_MATERIAL", - 3: "TYPE_POLICIES", + 3: "TYPE_PUSH", } WorkflowRunEvent_Type_value = map[string]int32{ "TYPE_UNSPECIFIED": 0, "TYPE_ATTESTATION": 1, "TYPE_MATERIAL": 2, - "TYPE_POLICIES": 3, + "TYPE_PUSH": 3, } ) @@ -1312,7 +1312,7 @@ type WorkflowRunEvent struct { // // *WorkflowRunEvent_Attestation // *WorkflowRunEvent_Material - // *WorkflowRunEvent_Policies + // *WorkflowRunEvent_Push Attributes isWorkflowRunEvent_Attributes `protobuf_oneof:"attributes"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache @@ -1422,10 +1422,10 @@ func (x *WorkflowRunEvent) GetMaterial() *WorkflowRunEvent_MaterialAttributes { return nil } -func (x *WorkflowRunEvent) GetPolicies() *WorkflowRunEvent_PoliciesAttributes { +func (x *WorkflowRunEvent) GetPush() *WorkflowRunEvent_PushAttributes { if x != nil { - if x, ok := x.Attributes.(*WorkflowRunEvent_Policies); ok { - return x.Policies + if x, ok := x.Attributes.(*WorkflowRunEvent_Push); ok { + return x.Push } } return nil @@ -1443,15 +1443,15 @@ type WorkflowRunEvent_Material struct { Material *WorkflowRunEvent_MaterialAttributes `protobuf:"bytes,11,opt,name=material,proto3,oneof"` } -type WorkflowRunEvent_Policies struct { - Policies *WorkflowRunEvent_PoliciesAttributes `protobuf:"bytes,12,opt,name=policies,proto3,oneof"` +type WorkflowRunEvent_Push struct { + Push *WorkflowRunEvent_PushAttributes `protobuf:"bytes,12,opt,name=push,proto3,oneof"` } func (*WorkflowRunEvent_Attestation) isWorkflowRunEvent_Attributes() {} func (*WorkflowRunEvent_Material) isWorkflowRunEvent_Attributes() {} -func (*WorkflowRunEvent_Policies) isWorkflowRunEvent_Attributes() {} +func (*WorkflowRunEvent_Push) isWorkflowRunEvent_Attributes() {} type WorkflowRunServiceListRequest struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -2137,10 +2137,10 @@ type WorkflowRunEvent_AttestationAttributes struct { 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"` - // policies that blocked a push - BlockingPolicies []string `protobuf:"bytes,7,rep,name=blocking_policies,json=blockingPolicies,proto3" json:"blocking_policies,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // results of the attestation policies evaluated at init + Policies *WorkflowRunEvent_PolicyCounts `protobuf:"bytes,7,opt,name=policies,proto3" json:"policies,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *WorkflowRunEvent_AttestationAttributes) Reset() { @@ -2215,9 +2215,9 @@ func (x *WorkflowRunEvent_AttestationAttributes) GetAttestationDigest() string { return "" } -func (x *WorkflowRunEvent_AttestationAttributes) GetBlockingPolicies() []string { +func (x *WorkflowRunEvent_AttestationAttributes) GetPolicies() *WorkflowRunEvent_PolicyCounts { if x != nil { - return x.BlockingPolicies + return x.Policies } return nil } @@ -2315,29 +2315,30 @@ func (x *WorkflowRunEvent_MaterialAttributes) GetPolicies() *WorkflowRunEvent_Po return nil } -type WorkflowRunEvent_PoliciesAttributes struct { +type WorkflowRunEvent_PushAttributes struct { state protoimpl.MessageState `protogen:"open.v1"` - // init or push - Phase string `protobuf:"bytes,1,opt,name=phase,proto3" json:"phase,omitempty"` - Policies *WorkflowRunEvent_PolicyCounts `protobuf:"bytes,2,opt,name=policies,proto3" json:"policies,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // results of the attestation policies evaluated at push + Policies *WorkflowRunEvent_PolicyCounts `protobuf:"bytes,1,opt,name=policies,proto3" json:"policies,omitempty"` + // gated policies with violations that block the push + BlockingPolicies []string `protobuf:"bytes,2,rep,name=blocking_policies,json=blockingPolicies,proto3" json:"blocking_policies,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } -func (x *WorkflowRunEvent_PoliciesAttributes) Reset() { - *x = WorkflowRunEvent_PoliciesAttributes{} +func (x *WorkflowRunEvent_PushAttributes) Reset() { + *x = WorkflowRunEvent_PushAttributes{} mi := &file_controlplane_v1_workflow_run_proto_msgTypes[32] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } -func (x *WorkflowRunEvent_PoliciesAttributes) String() string { +func (x *WorkflowRunEvent_PushAttributes) String() string { return protoimpl.X.MessageStringOf(x) } -func (*WorkflowRunEvent_PoliciesAttributes) ProtoMessage() {} +func (*WorkflowRunEvent_PushAttributes) ProtoMessage() {} -func (x *WorkflowRunEvent_PoliciesAttributes) ProtoReflect() protoreflect.Message { +func (x *WorkflowRunEvent_PushAttributes) ProtoReflect() protoreflect.Message { mi := &file_controlplane_v1_workflow_run_proto_msgTypes[32] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) @@ -2349,21 +2350,21 @@ func (x *WorkflowRunEvent_PoliciesAttributes) ProtoReflect() protoreflect.Messag return mi.MessageOf(x) } -// Deprecated: Use WorkflowRunEvent_PoliciesAttributes.ProtoReflect.Descriptor instead. -func (*WorkflowRunEvent_PoliciesAttributes) Descriptor() ([]byte, []int) { +// Deprecated: Use WorkflowRunEvent_PushAttributes.ProtoReflect.Descriptor instead. +func (*WorkflowRunEvent_PushAttributes) Descriptor() ([]byte, []int) { return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{19, 2} } -func (x *WorkflowRunEvent_PoliciesAttributes) GetPhase() string { +func (x *WorkflowRunEvent_PushAttributes) GetPolicies() *WorkflowRunEvent_PolicyCounts { if x != nil { - return x.Phase + return x.Policies } - return "" + return nil } -func (x *WorkflowRunEvent_PoliciesAttributes) GetPolicies() *WorkflowRunEvent_PolicyCounts { +func (x *WorkflowRunEvent_PushAttributes) GetBlockingPolicies() []string { if x != nil { - return x.Policies + return x.BlockingPolicies } return nil } @@ -2713,7 +2714,7 @@ const file_controlplane_v1_workflow_run_proto_rawDesc = "" + "\x0fworkflow_run_id\x18\x01 \x01(\tB\b\xbaH\x05r\x03\xb0\x01\x01R\rworkflowRunId\x121\n" + "\x0eafter_event_id\x18\x02 \x01(\tB\v\xbaH\b\xd8\x01\x01r\x03\xb0\x01\x01R\fafterEventId\"a\n" + "$WorkflowRunServiceListEventsResponse\x129\n" + - "\x06events\x18\x01 \x03(\v2!.controlplane.v1.WorkflowRunEventR\x06events\"\x93\x0e\n" + + "\x06events\x18\x01 \x03(\v2!.controlplane.v1.WorkflowRunEventR\x06events\"\xb6\x0e\n" + "\x10WorkflowRunEvent\x12\x0e\n" + "\x02id\x18\x01 \x01(\tR\x02id\x129\n" + "\n" + @@ -2727,8 +2728,8 @@ const file_controlplane_v1_workflow_run_proto_rawDesc = "" + "\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\x12R\n" + - "\bpolicies\x18\f \x01(\v24.controlplane.v1.WorkflowRunEvent.PoliciesAttributesH\x00R\bpolicies\x1a\xaa\x02\n" + + "\bmaterial\x18\v \x01(\v24.controlplane.v1.WorkflowRunEvent.MaterialAttributesH\x00R\bmaterial\x12F\n" + + "\x04push\x18\f \x01(\v20.controlplane.v1.WorkflowRunEvent.PushAttributesH\x00R\x04push\x1a\xc9\x02\n" + "\x15AttestationAttributes\x12#\n" + "\rcontract_name\x18\x01 \x01(\tR\fcontractName\x12+\n" + "\x11contract_revision\x18\x02 \x01(\x05R\x10contractRevision\x12\x1f\n" + @@ -2737,8 +2738,8 @@ const file_controlplane_v1_workflow_run_proto_rawDesc = "" + "\fremote_state\x18\x04 \x01(\bR\vremoteState\x12\x1f\n" + "\vcli_version\x18\x05 \x01(\tR\n" + "cliVersion\x12-\n" + - "\x12attestation_digest\x18\x06 \x01(\tR\x11attestationDigest\x12+\n" + - "\x11blocking_policies\x18\a \x03(\tR\x10blockingPolicies\x1a\xa0\x02\n" + + "\x12attestation_digest\x18\x06 \x01(\tR\x11attestationDigest\x12J\n" + + "\bpolicies\x18\a \x01(\v2..controlplane.v1.WorkflowRunEvent.PolicyCountsR\bpolicies\x1a\xa0\x02\n" + "\x12MaterialAttributes\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12#\n" + "\rmaterial_type\x18\x02 \x01(\tR\fmaterialType\x12\x1e\n" + @@ -2747,10 +2748,10 @@ const file_controlplane_v1_workflow_run_proto_rawDesc = "" + "\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\x1av\n" + - "\x12PoliciesAttributes\x12\x14\n" + - "\x05phase\x18\x01 \x01(\tR\x05phase\x12J\n" + - "\bpolicies\x18\x02 \x01(\v2..controlplane.v1.WorkflowRunEvent.PolicyCountsR\bpolicies\x1a\xa7\x01\n" + + "\bpolicies\x18\a \x01(\v2..controlplane.v1.WorkflowRunEvent.PolicyCountsR\bpolicies\x1a\x89\x01\n" + + "\x0ePushAttributes\x12J\n" + + "\bpolicies\x18\x01 \x01(\v2..controlplane.v1.WorkflowRunEvent.PolicyCountsR\bpolicies\x12+\n" + + "\x11blocking_policies\x18\x02 \x03(\tR\x10blockingPolicies\x1a\xa7\x01\n" + "\fPolicyCounts\x12\x1c\n" + "\tevaluated\x18\x01 \x01(\x05R\tevaluated\x12\x16\n" + "\x06passed\x18\x02 \x01(\x05R\x06passed\x12\x1a\n" + @@ -2761,12 +2762,12 @@ const file_controlplane_v1_workflow_run_proto_rawDesc = "" + "\x12SOURCE_UNSPECIFIED\x10\x00\x12\x0e\n" + "\n" + "SOURCE_CLI\x10\x01\x12\x18\n" + - "\x14SOURCE_CONTROL_PLANE\x10\x02\"X\n" + + "\x14SOURCE_CONTROL_PLANE\x10\x02\"T\n" + "\x04Type\x12\x14\n" + "\x10TYPE_UNSPECIFIED\x10\x00\x12\x14\n" + "\x10TYPE_ATTESTATION\x10\x01\x12\x11\n" + - "\rTYPE_MATERIAL\x10\x02\x12\x11\n" + - "\rTYPE_POLICIES\x10\x03\"r\n" + + "\rTYPE_MATERIAL\x10\x02\x12\r\n" + + "\tTYPE_PUSH\x10\x03\"r\n" + "\x06Status\x12\x16\n" + "\x12STATUS_UNSPECIFIED\x10\x00\x12\x12\n" + "\x0eSTATUS_STARTED\x10\x01\x12\x14\n" + @@ -2884,7 +2885,7 @@ var file_controlplane_v1_workflow_run_proto_goTypes = []any{ (*AttestationServiceStoreResponse_Result)(nil), // 33: controlplane.v1.AttestationServiceStoreResponse.Result (*WorkflowRunEvent_AttestationAttributes)(nil), // 34: controlplane.v1.WorkflowRunEvent.AttestationAttributes (*WorkflowRunEvent_MaterialAttributes)(nil), // 35: controlplane.v1.WorkflowRunEvent.MaterialAttributes - (*WorkflowRunEvent_PoliciesAttributes)(nil), // 36: controlplane.v1.WorkflowRunEvent.PoliciesAttributes + (*WorkflowRunEvent_PushAttributes)(nil), // 36: controlplane.v1.WorkflowRunEvent.PushAttributes (*WorkflowRunEvent_PolicyCounts)(nil), // 37: controlplane.v1.WorkflowRunEvent.PolicyCounts (*WorkflowRunServiceViewResponse_Result)(nil), // 38: controlplane.v1.WorkflowRunServiceViewResponse.Result (*WorkflowRunServiceViewResponse_VerificationResult)(nil), // 39: controlplane.v1.WorkflowRunServiceViewResponse.VerificationResult @@ -2924,7 +2925,7 @@ var file_controlplane_v1_workflow_run_proto_depIdxs = []int32{ 3, // 15: controlplane.v1.WorkflowRunEvent.status:type_name -> controlplane.v1.WorkflowRunEvent.Status 34, // 16: controlplane.v1.WorkflowRunEvent.attestation:type_name -> controlplane.v1.WorkflowRunEvent.AttestationAttributes 35, // 17: controlplane.v1.WorkflowRunEvent.material:type_name -> controlplane.v1.WorkflowRunEvent.MaterialAttributes - 36, // 18: controlplane.v1.WorkflowRunEvent.policies:type_name -> controlplane.v1.WorkflowRunEvent.PoliciesAttributes + 36, // 18: controlplane.v1.WorkflowRunEvent.push:type_name -> controlplane.v1.WorkflowRunEvent.PushAttributes 46, // 19: controlplane.v1.WorkflowRunServiceListRequest.status:type_name -> controlplane.v1.RunStatus 47, // 20: controlplane.v1.WorkflowRunServiceListRequest.policy_violations:type_name -> controlplane.v1.PolicyViolationsFilter 48, // 21: controlplane.v1.WorkflowRunServiceListRequest.policy_status:type_name -> controlplane.v1.PolicyStatusFilter @@ -2938,41 +2939,42 @@ var file_controlplane_v1_workflow_run_proto_depIdxs = []int32{ 53, // 29: controlplane.v1.AttestationServiceGetContractResponse.Result.contract:type_name -> controlplane.v1.WorkflowContractVersionItem 51, // 30: controlplane.v1.AttestationServiceInitResponse.Result.workflow_run:type_name -> controlplane.v1.WorkflowRunItem 32, // 31: controlplane.v1.AttestationServiceInitResponse.Result.signing_options:type_name -> controlplane.v1.AttestationServiceInitResponse.SigningOptions - 37, // 32: controlplane.v1.WorkflowRunEvent.MaterialAttributes.policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts - 37, // 33: controlplane.v1.WorkflowRunEvent.PoliciesAttributes.policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts - 51, // 34: controlplane.v1.WorkflowRunServiceViewResponse.Result.workflow_run:type_name -> controlplane.v1.WorkflowRunItem - 54, // 35: controlplane.v1.WorkflowRunServiceViewResponse.Result.attestation:type_name -> controlplane.v1.AttestationItem - 39, // 36: controlplane.v1.WorkflowRunServiceViewResponse.Result.verification:type_name -> controlplane.v1.WorkflowRunServiceViewResponse.VerificationResult - 55, // 37: controlplane.v1.AttestationServiceGetUploadCredsResponse.Result.backend:type_name -> controlplane.v1.CASBackendItem - 4, // 38: controlplane.v1.AttestationService.FindOrCreateWorkflow:input_type -> controlplane.v1.FindOrCreateWorkflowRequest - 11, // 39: controlplane.v1.AttestationService.GetContract:input_type -> controlplane.v1.AttestationServiceGetContractRequest - 13, // 40: controlplane.v1.AttestationService.Init:input_type -> controlplane.v1.AttestationServiceInitRequest - 15, // 41: controlplane.v1.AttestationService.Store:input_type -> controlplane.v1.AttestationServiceStoreRequest - 28, // 42: controlplane.v1.AttestationService.GetUploadCreds:input_type -> controlplane.v1.AttestationServiceGetUploadCredsRequest - 17, // 43: controlplane.v1.AttestationService.Cancel:input_type -> controlplane.v1.AttestationServiceCancelRequest - 19, // 44: controlplane.v1.AttestationService.RecordEvent:input_type -> controlplane.v1.AttestationServiceRecordEventRequest - 6, // 45: controlplane.v1.AttestationService.GetPolicy:input_type -> controlplane.v1.AttestationServiceGetPolicyRequest - 9, // 46: controlplane.v1.AttestationService.GetPolicyGroup:input_type -> controlplane.v1.AttestationServiceGetPolicyGroupRequest - 24, // 47: controlplane.v1.WorkflowRunService.List:input_type -> controlplane.v1.WorkflowRunServiceListRequest - 26, // 48: controlplane.v1.WorkflowRunService.View:input_type -> controlplane.v1.WorkflowRunServiceViewRequest - 21, // 49: controlplane.v1.WorkflowRunService.ListEvents:input_type -> controlplane.v1.WorkflowRunServiceListEventsRequest - 5, // 50: controlplane.v1.AttestationService.FindOrCreateWorkflow:output_type -> controlplane.v1.FindOrCreateWorkflowResponse - 12, // 51: controlplane.v1.AttestationService.GetContract:output_type -> controlplane.v1.AttestationServiceGetContractResponse - 14, // 52: controlplane.v1.AttestationService.Init:output_type -> controlplane.v1.AttestationServiceInitResponse - 16, // 53: controlplane.v1.AttestationService.Store:output_type -> controlplane.v1.AttestationServiceStoreResponse - 29, // 54: controlplane.v1.AttestationService.GetUploadCreds:output_type -> controlplane.v1.AttestationServiceGetUploadCredsResponse - 18, // 55: controlplane.v1.AttestationService.Cancel:output_type -> controlplane.v1.AttestationServiceCancelResponse - 20, // 56: controlplane.v1.AttestationService.RecordEvent:output_type -> controlplane.v1.AttestationServiceRecordEventResponse - 7, // 57: controlplane.v1.AttestationService.GetPolicy:output_type -> controlplane.v1.AttestationServiceGetPolicyResponse - 10, // 58: controlplane.v1.AttestationService.GetPolicyGroup:output_type -> controlplane.v1.AttestationServiceGetPolicyGroupResponse - 25, // 59: controlplane.v1.WorkflowRunService.List:output_type -> controlplane.v1.WorkflowRunServiceListResponse - 27, // 60: controlplane.v1.WorkflowRunService.View:output_type -> controlplane.v1.WorkflowRunServiceViewResponse - 22, // 61: controlplane.v1.WorkflowRunService.ListEvents:output_type -> controlplane.v1.WorkflowRunServiceListEventsResponse - 50, // [50:62] is the sub-list for method output_type - 38, // [38:50] is the sub-list for method input_type - 38, // [38:38] is the sub-list for extension type_name - 38, // [38:38] is the sub-list for extension extendee - 0, // [0:38] is the sub-list for field type_name + 37, // 32: controlplane.v1.WorkflowRunEvent.AttestationAttributes.policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts + 37, // 33: controlplane.v1.WorkflowRunEvent.MaterialAttributes.policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts + 37, // 34: controlplane.v1.WorkflowRunEvent.PushAttributes.policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts + 51, // 35: controlplane.v1.WorkflowRunServiceViewResponse.Result.workflow_run:type_name -> controlplane.v1.WorkflowRunItem + 54, // 36: controlplane.v1.WorkflowRunServiceViewResponse.Result.attestation:type_name -> controlplane.v1.AttestationItem + 39, // 37: controlplane.v1.WorkflowRunServiceViewResponse.Result.verification:type_name -> controlplane.v1.WorkflowRunServiceViewResponse.VerificationResult + 55, // 38: controlplane.v1.AttestationServiceGetUploadCredsResponse.Result.backend:type_name -> controlplane.v1.CASBackendItem + 4, // 39: controlplane.v1.AttestationService.FindOrCreateWorkflow:input_type -> controlplane.v1.FindOrCreateWorkflowRequest + 11, // 40: controlplane.v1.AttestationService.GetContract:input_type -> controlplane.v1.AttestationServiceGetContractRequest + 13, // 41: controlplane.v1.AttestationService.Init:input_type -> controlplane.v1.AttestationServiceInitRequest + 15, // 42: controlplane.v1.AttestationService.Store:input_type -> controlplane.v1.AttestationServiceStoreRequest + 28, // 43: controlplane.v1.AttestationService.GetUploadCreds:input_type -> controlplane.v1.AttestationServiceGetUploadCredsRequest + 17, // 44: controlplane.v1.AttestationService.Cancel:input_type -> controlplane.v1.AttestationServiceCancelRequest + 19, // 45: controlplane.v1.AttestationService.RecordEvent:input_type -> controlplane.v1.AttestationServiceRecordEventRequest + 6, // 46: controlplane.v1.AttestationService.GetPolicy:input_type -> controlplane.v1.AttestationServiceGetPolicyRequest + 9, // 47: controlplane.v1.AttestationService.GetPolicyGroup:input_type -> controlplane.v1.AttestationServiceGetPolicyGroupRequest + 24, // 48: controlplane.v1.WorkflowRunService.List:input_type -> controlplane.v1.WorkflowRunServiceListRequest + 26, // 49: controlplane.v1.WorkflowRunService.View:input_type -> controlplane.v1.WorkflowRunServiceViewRequest + 21, // 50: controlplane.v1.WorkflowRunService.ListEvents:input_type -> controlplane.v1.WorkflowRunServiceListEventsRequest + 5, // 51: controlplane.v1.AttestationService.FindOrCreateWorkflow:output_type -> controlplane.v1.FindOrCreateWorkflowResponse + 12, // 52: controlplane.v1.AttestationService.GetContract:output_type -> controlplane.v1.AttestationServiceGetContractResponse + 14, // 53: controlplane.v1.AttestationService.Init:output_type -> controlplane.v1.AttestationServiceInitResponse + 16, // 54: controlplane.v1.AttestationService.Store:output_type -> controlplane.v1.AttestationServiceStoreResponse + 29, // 55: controlplane.v1.AttestationService.GetUploadCreds:output_type -> controlplane.v1.AttestationServiceGetUploadCredsResponse + 18, // 56: controlplane.v1.AttestationService.Cancel:output_type -> controlplane.v1.AttestationServiceCancelResponse + 20, // 57: controlplane.v1.AttestationService.RecordEvent:output_type -> controlplane.v1.AttestationServiceRecordEventResponse + 7, // 58: controlplane.v1.AttestationService.GetPolicy:output_type -> controlplane.v1.AttestationServiceGetPolicyResponse + 10, // 59: controlplane.v1.AttestationService.GetPolicyGroup:output_type -> controlplane.v1.AttestationServiceGetPolicyGroupResponse + 25, // 60: controlplane.v1.WorkflowRunService.List:output_type -> controlplane.v1.WorkflowRunServiceListResponse + 27, // 61: controlplane.v1.WorkflowRunService.View:output_type -> controlplane.v1.WorkflowRunServiceViewResponse + 22, // 62: controlplane.v1.WorkflowRunService.ListEvents:output_type -> controlplane.v1.WorkflowRunServiceListEventsResponse + 51, // [51:63] is the sub-list for method output_type + 39, // [39:51] is the sub-list for method input_type + 39, // [39:39] is the sub-list for extension type_name + 39, // [39:39] is the sub-list for extension extendee + 0, // [0:39] is the sub-list for field type_name } func init() { file_controlplane_v1_workflow_run_proto_init() } @@ -2987,7 +2989,7 @@ func file_controlplane_v1_workflow_run_proto_init() { file_controlplane_v1_workflow_run_proto_msgTypes[19].OneofWrappers = []any{ (*WorkflowRunEvent_Attestation)(nil), (*WorkflowRunEvent_Material)(nil), - (*WorkflowRunEvent_Policies)(nil), + (*WorkflowRunEvent_Push)(nil), } file_controlplane_v1_workflow_run_proto_msgTypes[22].OneofWrappers = []any{ (*WorkflowRunServiceViewRequest_Id)(nil), diff --git a/app/controlplane/api/controlplane/v1/workflow_run.proto b/app/controlplane/api/controlplane/v1/workflow_run.proto index e3925cb3e..9c345768a 100644 --- a/app/controlplane/api/controlplane/v1/workflow_run.proto +++ b/app/controlplane/api/controlplane/v1/workflow_run.proto @@ -252,7 +252,7 @@ message WorkflowRunEvent { oneof attributes { AttestationAttributes attestation = 10; MaterialAttributes material = 11; - PoliciesAttributes policies = 12; + PushAttributes push = 12; } enum Source { @@ -265,7 +265,7 @@ message WorkflowRunEvent { TYPE_UNSPECIFIED = 0; TYPE_ATTESTATION = 1; TYPE_MATERIAL = 2; - TYPE_POLICIES = 3; + TYPE_PUSH = 3; } enum Status { @@ -283,8 +283,8 @@ message WorkflowRunEvent { bool remote_state = 4; string cli_version = 5; string attestation_digest = 6; - // policies that blocked a push - repeated string blocking_policies = 7; + // results of the attestation policies evaluated at init + PolicyCounts policies = 7; } message MaterialAttributes { @@ -298,10 +298,11 @@ message WorkflowRunEvent { PolicyCounts policies = 7; } - message PoliciesAttributes { - // init or push - string phase = 1; - PolicyCounts policies = 2; + message PushAttributes { + // results of the attestation policies evaluated at push + PolicyCounts policies = 1; + // gated policies with violations that block the push + repeated string blocking_policies = 2; } message PolicyCounts { 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 cd5940e68..b6549f464 100644 --- a/app/controlplane/api/gen/frontend/controlplane/v1/workflow_run.ts +++ b/app/controlplane/api/gen/frontend/controlplane/v1/workflow_run.ts @@ -259,7 +259,7 @@ export interface WorkflowRunEvent { message: string; attestation?: WorkflowRunEvent_AttestationAttributes | undefined; material?: WorkflowRunEvent_MaterialAttributes | undefined; - policies?: WorkflowRunEvent_PoliciesAttributes | undefined; + push?: WorkflowRunEvent_PushAttributes | undefined; } export enum WorkflowRunEvent_Source { @@ -305,7 +305,7 @@ export enum WorkflowRunEvent_Type { TYPE_UNSPECIFIED = 0, TYPE_ATTESTATION = 1, TYPE_MATERIAL = 2, - TYPE_POLICIES = 3, + TYPE_PUSH = 3, UNRECOGNIZED = -1, } @@ -321,8 +321,8 @@ export function workflowRunEvent_TypeFromJSON(object: any): WorkflowRunEvent_Typ case "TYPE_MATERIAL": return WorkflowRunEvent_Type.TYPE_MATERIAL; case 3: - case "TYPE_POLICIES": - return WorkflowRunEvent_Type.TYPE_POLICIES; + case "TYPE_PUSH": + return WorkflowRunEvent_Type.TYPE_PUSH; case -1: case "UNRECOGNIZED": default: @@ -338,8 +338,8 @@ export function workflowRunEvent_TypeToJSON(object: WorkflowRunEvent_Type): stri return "TYPE_ATTESTATION"; case WorkflowRunEvent_Type.TYPE_MATERIAL: return "TYPE_MATERIAL"; - case WorkflowRunEvent_Type.TYPE_POLICIES: - return "TYPE_POLICIES"; + case WorkflowRunEvent_Type.TYPE_PUSH: + return "TYPE_PUSH"; case WorkflowRunEvent_Type.UNRECOGNIZED: default: return "UNRECOGNIZED"; @@ -404,8 +404,8 @@ export interface WorkflowRunEvent_AttestationAttributes { remoteState: boolean; cliVersion: string; attestationDigest: string; - /** policies that blocked a push */ - blockingPolicies: string[]; + /** results of the attestation policies evaluated at init */ + policies?: WorkflowRunEvent_PolicyCounts; } export interface WorkflowRunEvent_MaterialAttributes { @@ -419,10 +419,11 @@ export interface WorkflowRunEvent_MaterialAttributes { policies?: WorkflowRunEvent_PolicyCounts; } -export interface WorkflowRunEvent_PoliciesAttributes { - /** init or push */ - phase: string; +export interface WorkflowRunEvent_PushAttributes { + /** results of the attestation policies evaluated at push */ policies?: WorkflowRunEvent_PolicyCounts; + /** gated policies with violations that block the push */ + blockingPolicies: string[]; } export interface WorkflowRunEvent_PolicyCounts { @@ -2449,7 +2450,7 @@ function createBaseWorkflowRunEvent(): WorkflowRunEvent { message: "", attestation: undefined, material: undefined, - policies: undefined, + push: undefined, }; } @@ -2482,8 +2483,8 @@ export const WorkflowRunEvent = { if (message.material !== undefined) { WorkflowRunEvent_MaterialAttributes.encode(message.material, writer.uint32(90).fork()).ldelim(); } - if (message.policies !== undefined) { - WorkflowRunEvent_PoliciesAttributes.encode(message.policies, writer.uint32(98).fork()).ldelim(); + if (message.push !== undefined) { + WorkflowRunEvent_PushAttributes.encode(message.push, writer.uint32(98).fork()).ldelim(); } return writer; }, @@ -2563,7 +2564,7 @@ export const WorkflowRunEvent = { break; } - message.policies = WorkflowRunEvent_PoliciesAttributes.decode(reader, reader.uint32()); + message.push = WorkflowRunEvent_PushAttributes.decode(reader, reader.uint32()); continue; } if ((tag & 7) === 4 || tag === 0) { @@ -2587,7 +2588,7 @@ export const WorkflowRunEvent = { ? WorkflowRunEvent_AttestationAttributes.fromJSON(object.attestation) : undefined, material: isSet(object.material) ? WorkflowRunEvent_MaterialAttributes.fromJSON(object.material) : undefined, - policies: isSet(object.policies) ? WorkflowRunEvent_PoliciesAttributes.fromJSON(object.policies) : undefined, + push: isSet(object.push) ? WorkflowRunEvent_PushAttributes.fromJSON(object.push) : undefined, }; }, @@ -2605,8 +2606,8 @@ export const WorkflowRunEvent = { : undefined); message.material !== undefined && (obj.material = message.material ? WorkflowRunEvent_MaterialAttributes.toJSON(message.material) : undefined); - message.policies !== undefined && - (obj.policies = message.policies ? WorkflowRunEvent_PoliciesAttributes.toJSON(message.policies) : undefined); + message.push !== undefined && + (obj.push = message.push ? WorkflowRunEvent_PushAttributes.toJSON(message.push) : undefined); return obj; }, @@ -2629,8 +2630,8 @@ export const WorkflowRunEvent = { message.material = (object.material !== undefined && object.material !== null) ? WorkflowRunEvent_MaterialAttributes.fromPartial(object.material) : undefined; - message.policies = (object.policies !== undefined && object.policies !== null) - ? WorkflowRunEvent_PoliciesAttributes.fromPartial(object.policies) + message.push = (object.push !== undefined && object.push !== null) + ? WorkflowRunEvent_PushAttributes.fromPartial(object.push) : undefined; return message; }, @@ -2644,7 +2645,7 @@ function createBaseWorkflowRunEvent_AttestationAttributes(): WorkflowRunEvent_At remoteState: false, cliVersion: "", attestationDigest: "", - blockingPolicies: [], + policies: undefined, }; } @@ -2668,8 +2669,8 @@ export const WorkflowRunEvent_AttestationAttributes = { if (message.attestationDigest !== "") { writer.uint32(50).string(message.attestationDigest); } - for (const v of message.blockingPolicies) { - writer.uint32(58).string(v!); + if (message.policies !== undefined) { + WorkflowRunEvent_PolicyCounts.encode(message.policies, writer.uint32(58).fork()).ldelim(); } return writer; }, @@ -2728,7 +2729,7 @@ export const WorkflowRunEvent_AttestationAttributes = { break; } - message.blockingPolicies.push(reader.string()); + message.policies = WorkflowRunEvent_PolicyCounts.decode(reader, reader.uint32()); continue; } if ((tag & 7) === 4 || tag === 0) { @@ -2747,9 +2748,7 @@ export const WorkflowRunEvent_AttestationAttributes = { remoteState: isSet(object.remoteState) ? Boolean(object.remoteState) : false, cliVersion: isSet(object.cliVersion) ? String(object.cliVersion) : "", attestationDigest: isSet(object.attestationDigest) ? String(object.attestationDigest) : "", - blockingPolicies: Array.isArray(object?.blockingPolicies) - ? object.blockingPolicies.map((e: any) => String(e)) - : [], + policies: isSet(object.policies) ? WorkflowRunEvent_PolicyCounts.fromJSON(object.policies) : undefined, }; }, @@ -2761,11 +2760,8 @@ export const WorkflowRunEvent_AttestationAttributes = { message.remoteState !== undefined && (obj.remoteState = message.remoteState); message.cliVersion !== undefined && (obj.cliVersion = message.cliVersion); message.attestationDigest !== undefined && (obj.attestationDigest = message.attestationDigest); - if (message.blockingPolicies) { - obj.blockingPolicies = message.blockingPolicies.map((e) => e); - } else { - obj.blockingPolicies = []; - } + message.policies !== undefined && + (obj.policies = message.policies ? WorkflowRunEvent_PolicyCounts.toJSON(message.policies) : undefined); return obj; }, @@ -2785,7 +2781,9 @@ export const WorkflowRunEvent_AttestationAttributes = { message.remoteState = object.remoteState ?? false; message.cliVersion = object.cliVersion ?? ""; message.attestationDigest = object.attestationDigest ?? ""; - message.blockingPolicies = object.blockingPolicies?.map((e) => e) || []; + message.policies = (object.policies !== undefined && object.policies !== null) + ? WorkflowRunEvent_PolicyCounts.fromPartial(object.policies) + : undefined; return message; }, }; @@ -2941,25 +2939,25 @@ export const WorkflowRunEvent_MaterialAttributes = { }, }; -function createBaseWorkflowRunEvent_PoliciesAttributes(): WorkflowRunEvent_PoliciesAttributes { - return { phase: "", policies: undefined }; +function createBaseWorkflowRunEvent_PushAttributes(): WorkflowRunEvent_PushAttributes { + return { policies: undefined, blockingPolicies: [] }; } -export const WorkflowRunEvent_PoliciesAttributes = { - encode(message: WorkflowRunEvent_PoliciesAttributes, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { - if (message.phase !== "") { - writer.uint32(10).string(message.phase); - } +export const WorkflowRunEvent_PushAttributes = { + encode(message: WorkflowRunEvent_PushAttributes, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { if (message.policies !== undefined) { - WorkflowRunEvent_PolicyCounts.encode(message.policies, writer.uint32(18).fork()).ldelim(); + WorkflowRunEvent_PolicyCounts.encode(message.policies, writer.uint32(10).fork()).ldelim(); + } + for (const v of message.blockingPolicies) { + writer.uint32(18).string(v!); } return writer; }, - decode(input: _m0.Reader | Uint8Array, length?: number): WorkflowRunEvent_PoliciesAttributes { + decode(input: _m0.Reader | Uint8Array, length?: number): WorkflowRunEvent_PushAttributes { const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input); let end = length === undefined ? reader.len : reader.pos + length; - const message = createBaseWorkflowRunEvent_PoliciesAttributes(); + const message = createBaseWorkflowRunEvent_PushAttributes(); while (reader.pos < end) { const tag = reader.uint32(); switch (tag >>> 3) { @@ -2968,14 +2966,14 @@ export const WorkflowRunEvent_PoliciesAttributes = { break; } - message.phase = reader.string(); + message.policies = WorkflowRunEvent_PolicyCounts.decode(reader, reader.uint32()); continue; case 2: if (tag !== 18) { break; } - message.policies = WorkflowRunEvent_PolicyCounts.decode(reader, reader.uint32()); + message.blockingPolicies.push(reader.string()); continue; } if ((tag & 7) === 4 || tag === 0) { @@ -2986,35 +2984,39 @@ export const WorkflowRunEvent_PoliciesAttributes = { return message; }, - fromJSON(object: any): WorkflowRunEvent_PoliciesAttributes { + fromJSON(object: any): WorkflowRunEvent_PushAttributes { return { - phase: isSet(object.phase) ? String(object.phase) : "", policies: isSet(object.policies) ? WorkflowRunEvent_PolicyCounts.fromJSON(object.policies) : undefined, + blockingPolicies: Array.isArray(object?.blockingPolicies) + ? object.blockingPolicies.map((e: any) => String(e)) + : [], }; }, - toJSON(message: WorkflowRunEvent_PoliciesAttributes): unknown { + toJSON(message: WorkflowRunEvent_PushAttributes): unknown { const obj: any = {}; - message.phase !== undefined && (obj.phase = message.phase); message.policies !== undefined && (obj.policies = message.policies ? WorkflowRunEvent_PolicyCounts.toJSON(message.policies) : undefined); + if (message.blockingPolicies) { + obj.blockingPolicies = message.blockingPolicies.map((e) => e); + } else { + obj.blockingPolicies = []; + } return obj; }, - create, I>>( - base?: I, - ): WorkflowRunEvent_PoliciesAttributes { - return WorkflowRunEvent_PoliciesAttributes.fromPartial(base ?? {}); + create, I>>(base?: I): WorkflowRunEvent_PushAttributes { + return WorkflowRunEvent_PushAttributes.fromPartial(base ?? {}); }, - fromPartial, I>>( + fromPartial, I>>( object: I, - ): WorkflowRunEvent_PoliciesAttributes { - const message = createBaseWorkflowRunEvent_PoliciesAttributes(); - message.phase = object.phase ?? ""; + ): WorkflowRunEvent_PushAttributes { + const message = createBaseWorkflowRunEvent_PushAttributes(); message.policies = (object.policies !== undefined && object.policies !== null) ? WorkflowRunEvent_PolicyCounts.fromPartial(object.policies) : undefined; + message.blockingPolicies = object.blockingPolicies?.map((e) => e) || []; return message; }, }; 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 index 58c07241e..e3baaea54 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.AttestationAttributes.jsonschema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.AttestationAttributes.jsonschema.json @@ -6,13 +6,6 @@ "^(attestation_digest)$": { "type": "string" }, - "^(blocking_policies)$": { - "description": "policies that blocked a push", - "items": { - "type": "string" - }, - "type": "array" - }, "^(cli_version)$": { "type": "string" }, @@ -35,13 +28,6 @@ "attestationDigest": { "type": "string" }, - "blockingPolicies": { - "description": "policies that blocked a push", - "items": { - "type": "string" - }, - "type": "array" - }, "cliVersion": { "type": "string" }, @@ -53,6 +39,10 @@ "minimum": -2147483648, "type": "integer" }, + "policies": { + "$ref": "controlplane.v1.WorkflowRunEvent.PolicyCounts.jsonschema.json", + "description": "results of the attestation policies evaluated at init" + }, "remoteState": { "type": "boolean" }, 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 index 904431301..d05f6633f 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.AttestationAttributes.schema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.AttestationAttributes.schema.json @@ -6,13 +6,6 @@ "^(attestationDigest)$": { "type": "string" }, - "^(blockingPolicies)$": { - "description": "policies that blocked a push", - "items": { - "type": "string" - }, - "type": "array" - }, "^(cliVersion)$": { "type": "string" }, @@ -35,13 +28,6 @@ "attestation_digest": { "type": "string" }, - "blocking_policies": { - "description": "policies that blocked a push", - "items": { - "type": "string" - }, - "type": "array" - }, "cli_version": { "type": "string" }, @@ -53,6 +39,10 @@ "minimum": -2147483648, "type": "integer" }, + "policies": { + "$ref": "controlplane.v1.WorkflowRunEvent.PolicyCounts.schema.json", + "description": "results of the attestation policies evaluated at init" + }, "remote_state": { "type": "boolean" }, diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PoliciesAttributes.jsonschema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PoliciesAttributes.jsonschema.json deleted file mode 100644 index 870cfe38a..000000000 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PoliciesAttributes.jsonschema.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "$id": "controlplane.v1.WorkflowRunEvent.PoliciesAttributes.jsonschema.json", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "additionalProperties": false, - "properties": { - "phase": { - "description": "init or push", - "type": "string" - }, - "policies": { - "$ref": "controlplane.v1.WorkflowRunEvent.PolicyCounts.jsonschema.json" - } - }, - "title": "Policies Attributes", - "type": "object" -} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PoliciesAttributes.schema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PoliciesAttributes.schema.json deleted file mode 100644 index 96cf39eb1..000000000 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PoliciesAttributes.schema.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "$id": "controlplane.v1.WorkflowRunEvent.PoliciesAttributes.schema.json", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "additionalProperties": false, - "properties": { - "phase": { - "description": "init or push", - "type": "string" - }, - "policies": { - "$ref": "controlplane.v1.WorkflowRunEvent.PolicyCounts.schema.json" - } - }, - "title": "Policies Attributes", - "type": "object" -} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PushAttributes.jsonschema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PushAttributes.jsonschema.json new file mode 100644 index 000000000..017922583 --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PushAttributes.jsonschema.json @@ -0,0 +1,29 @@ +{ + "$id": "controlplane.v1.WorkflowRunEvent.PushAttributes.jsonschema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "patternProperties": { + "^(blocking_policies)$": { + "description": "gated policies with violations that block the push", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "properties": { + "blockingPolicies": { + "description": "gated policies with violations that block the push", + "items": { + "type": "string" + }, + "type": "array" + }, + "policies": { + "$ref": "controlplane.v1.WorkflowRunEvent.PolicyCounts.jsonschema.json", + "description": "results of the attestation policies evaluated at push" + } + }, + "title": "Push Attributes", + "type": "object" +} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PushAttributes.schema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PushAttributes.schema.json new file mode 100644 index 000000000..f5b822ea3 --- /dev/null +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PushAttributes.schema.json @@ -0,0 +1,29 @@ +{ + "$id": "controlplane.v1.WorkflowRunEvent.PushAttributes.schema.json", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "patternProperties": { + "^(blockingPolicies)$": { + "description": "gated policies with violations that block the push", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "properties": { + "blocking_policies": { + "description": "gated policies with violations that block the push", + "items": { + "type": "string" + }, + "type": "array" + }, + "policies": { + "$ref": "controlplane.v1.WorkflowRunEvent.PolicyCounts.schema.json", + "description": "results of the attestation policies evaluated at push" + } + }, + "title": "Push Attributes", + "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 index 2f2b4a673..b8a1dbd15 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.jsonschema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.jsonschema.json @@ -32,8 +32,8 @@ "maxLength": 1024, "type": "string" }, - "policies": { - "$ref": "controlplane.v1.WorkflowRunEvent.PoliciesAttributes.jsonschema.json" + "push": { + "$ref": "controlplane.v1.WorkflowRunEvent.PushAttributes.jsonschema.json" }, "source": { "anyOf": [ @@ -80,7 +80,7 @@ "TYPE_UNSPECIFIED", "TYPE_ATTESTATION", "TYPE_MATERIAL", - "TYPE_POLICIES" + "TYPE_PUSH" ], "title": "Type", "type": "string" diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.schema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.schema.json index d4117149e..721f0fe92 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.schema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.schema.json @@ -32,8 +32,8 @@ "maxLength": 1024, "type": "string" }, - "policies": { - "$ref": "controlplane.v1.WorkflowRunEvent.PoliciesAttributes.schema.json" + "push": { + "$ref": "controlplane.v1.WorkflowRunEvent.PushAttributes.schema.json" }, "source": { "anyOf": [ @@ -80,7 +80,7 @@ "TYPE_UNSPECIFIED", "TYPE_ATTESTATION", "TYPE_MATERIAL", - "TYPE_POLICIES" + "TYPE_PUSH" ], "title": "Type", "type": "string" diff --git a/app/controlplane/internal/service/workflowrun.go b/app/controlplane/internal/service/workflowrun.go index 695ed833d..cefbf5047 100644 --- a/app/controlplane/internal/service/workflowrun.go +++ b/app/controlplane/internal/service/workflowrun.go @@ -638,12 +638,12 @@ var ( pbToBizRunEventType = map[pb.WorkflowRunEvent_Type]biz.WorkflowRunEventType{ pb.WorkflowRunEvent_TYPE_ATTESTATION: biz.WorkflowRunEventTypeAttestation, pb.WorkflowRunEvent_TYPE_MATERIAL: biz.WorkflowRunEventTypeMaterial, - pb.WorkflowRunEvent_TYPE_POLICIES: biz.WorkflowRunEventTypePolicies, + pb.WorkflowRunEvent_TYPE_PUSH: biz.WorkflowRunEventTypePush, } bizToPbRunEventType = map[biz.WorkflowRunEventType]pb.WorkflowRunEvent_Type{ biz.WorkflowRunEventTypeAttestation: pb.WorkflowRunEvent_TYPE_ATTESTATION, biz.WorkflowRunEventTypeMaterial: pb.WorkflowRunEvent_TYPE_MATERIAL, - biz.WorkflowRunEventTypePolicies: pb.WorkflowRunEvent_TYPE_POLICIES, + biz.WorkflowRunEventTypePush: pb.WorkflowRunEvent_TYPE_PUSH, } pbToBizRunEventStatus = map[pb.WorkflowRunEvent_Status]biz.WorkflowRunEventStatus{ pb.WorkflowRunEvent_STATUS_STARTED: biz.WorkflowRunEventStatusStarted, @@ -697,7 +697,7 @@ func pbWorkflowRunEventToBiz(in *pb.WorkflowRunEvent) (*biz.WorkflowRunEvent, er RemoteState: a.GetRemoteState(), CLIVersion: a.GetCliVersion(), AttestationDigest: a.GetAttestationDigest(), - BlockingPolicies: a.GetBlockingPolicies(), + Policies: pbPolicyCountsToBiz(a.GetPolicies()), }} case *pb.WorkflowRunEvent_Material: m := attrs.Material @@ -710,11 +710,11 @@ func pbWorkflowRunEventToBiz(in *pb.WorkflowRunEvent) (*biz.WorkflowRunEvent, er AddedByCollector: m.GetAddedByCollector(), Policies: pbPolicyCountsToBiz(m.GetPolicies()), }} - case *pb.WorkflowRunEvent_Policies: - p := attrs.Policies - out.Attributes = &biz.WorkflowRunEventAttributes{Policies: &biz.WorkflowRunEventPoliciesAttributes{ - Phase: p.GetPhase(), - Policies: pbPolicyCountsToBiz(p.GetPolicies()), + case *pb.WorkflowRunEvent_Push: + p := attrs.Push + out.Attributes = &biz.WorkflowRunEventAttributes{Push: &biz.WorkflowRunEventPushAttributes{ + Policies: pbPolicyCountsToBiz(p.GetPolicies()), + BlockingPolicies: p.GetBlockingPolicies(), }} } @@ -775,7 +775,7 @@ func bizWorkflowRunEventToPb(in *biz.WorkflowRunEvent) *pb.WorkflowRunEvent { RemoteState: a.RemoteState, CliVersion: a.CLIVersion, AttestationDigest: a.AttestationDigest, - BlockingPolicies: a.BlockingPolicies, + Policies: bizPolicyCountsToPb(a.Policies), }} case attrs.Material != nil: m := attrs.Material @@ -788,11 +788,11 @@ func bizWorkflowRunEventToPb(in *biz.WorkflowRunEvent) *pb.WorkflowRunEvent { AddedByCollector: m.AddedByCollector, Policies: bizPolicyCountsToPb(m.Policies), }} - case attrs.Policies != nil: - p := attrs.Policies - out.Attributes = &pb.WorkflowRunEvent_Policies{Policies: &pb.WorkflowRunEvent_PoliciesAttributes{ - Phase: p.Phase, - Policies: bizPolicyCountsToPb(p.Policies), + case attrs.Push != nil: + p := attrs.Push + out.Attributes = &pb.WorkflowRunEvent_Push{Push: &pb.WorkflowRunEvent_PushAttributes{ + Policies: bizPolicyCountsToPb(p.Policies), + BlockingPolicies: p.BlockingPolicies, }} } diff --git a/app/controlplane/internal/service/workflowrunevent_integration_test.go b/app/controlplane/internal/service/workflowrunevent_integration_test.go index adc8e90e3..ab4355e3c 100644 --- a/app/controlplane/internal/service/workflowrunevent_integration_test.go +++ b/app/controlplane/internal/service/workflowrunevent_integration_test.go @@ -317,7 +317,7 @@ func (s *workflowRunEventRBACIntegrationSuite) TestRecordEventValidation() { { name: "attributes that do not match the type", event: &pb.WorkflowRunEvent{ - Type: pb.WorkflowRunEvent_TYPE_POLICIES, Key: "chainloop.policies.init", Status: pb.WorkflowRunEvent_STATUS_SUCCEEDED, + Type: pb.WorkflowRunEvent_TYPE_PUSH, Key: "chainloop.push", Status: pb.WorkflowRunEvent_STATUS_SUCCEEDED, Attributes: &pb.WorkflowRunEvent_Material{Material: &pb.WorkflowRunEvent_MaterialAttributes{Name: "sbom"}}, }, }, 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/workflowrunevent.go b/app/controlplane/pkg/biz/workflowrunevent.go index 1864932cc..6bb9fa7e2 100644 --- a/app/controlplane/pkg/biz/workflowrunevent.go +++ b/app/controlplane/pkg/biz/workflowrunevent.go @@ -59,12 +59,12 @@ type WorkflowRunEventType string const ( WorkflowRunEventTypeAttestation WorkflowRunEventType = "attestation" WorkflowRunEventTypeMaterial WorkflowRunEventType = "material" - WorkflowRunEventTypePolicies WorkflowRunEventType = "policies" + WorkflowRunEventTypePush WorkflowRunEventType = "push" ) // Values implements the ent enum interface func (WorkflowRunEventType) Values() []string { - return []string{string(WorkflowRunEventTypeAttestation), string(WorkflowRunEventTypeMaterial), string(WorkflowRunEventTypePolicies)} + return []string{string(WorkflowRunEventTypeAttestation), string(WorkflowRunEventTypeMaterial), string(WorkflowRunEventTypePush)} } type WorkflowRunEventStatus string @@ -105,17 +105,18 @@ type WorkflowRunEvent struct { type WorkflowRunEventAttributes struct { Attestation *WorkflowRunEventAttestationAttributes `json:"attestation,omitempty"` Material *WorkflowRunEventMaterialAttributes `json:"material,omitempty"` - Policies *WorkflowRunEventPoliciesAttributes `json:"policies,omitempty"` + Push *WorkflowRunEventPushAttributes `json:"push,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"` - BlockingPolicies []string `json:"blocking_policies,omitempty"` + 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"` } type WorkflowRunEventMaterialAttributes struct { @@ -128,9 +129,11 @@ type WorkflowRunEventMaterialAttributes struct { Policies *WorkflowRunEventPolicyCounts `json:"policies,omitempty"` } -type WorkflowRunEventPoliciesAttributes struct { - Phase string `json:"phase,omitempty"` +type WorkflowRunEventPushAttributes struct { + // Results of the attestation policies evaluated at push Policies *WorkflowRunEventPolicyCounts `json:"policies,omitempty"` + // Gated policies with violations that block the push + BlockingPolicies []string `json:"blocking_policies,omitempty"` } type WorkflowRunEventPolicyCounts struct { @@ -199,10 +202,10 @@ func validateWorkflowRunEvent(ev *WorkflowRunEvent) error { var match bool switch ev.Type { case WorkflowRunEventTypeAttestation: - match = attrs == nil || (attrs.Material == nil && attrs.Policies == nil) + match = attrs == nil || (attrs.Material == nil && attrs.Push == nil) case WorkflowRunEventTypeMaterial: - match = attrs == nil || (attrs.Attestation == nil && attrs.Policies == nil) - case WorkflowRunEventTypePolicies: + match = attrs == nil || (attrs.Attestation == nil && attrs.Push == nil) + case WorkflowRunEventTypePush: match = attrs == nil || (attrs.Attestation == nil && attrs.Material == nil) default: return NewErrValidationStr(fmt.Sprintf("unsupported event type %q", ev.Type)) diff --git a/app/controlplane/pkg/biz/workflowrunevent_test.go b/app/controlplane/pkg/biz/workflowrunevent_test.go index 0715931e8..875fd7646 100644 --- a/app/controlplane/pkg/biz/workflowrunevent_test.go +++ b/app/controlplane/pkg/biz/workflowrunevent_test.go @@ -27,7 +27,7 @@ import ( func TestValidateWorkflowRunEvent(t *testing.T) { material := &WorkflowRunEventAttributes{Material: &WorkflowRunEventMaterialAttributes{Name: "sbom"}} - policies := &WorkflowRunEventAttributes{Policies: &WorkflowRunEventPoliciesAttributes{Phase: "init"}} + push := &WorkflowRunEventAttributes{Push: &WorkflowRunEventPushAttributes{BlockingPolicies: []string{"gate"}}} testCases := []struct { name string @@ -49,7 +49,7 @@ func TestValidateWorkflowRunEvent(t *testing.T) { }, { name: "attributes of another type", - event: &WorkflowRunEvent{Type: WorkflowRunEventTypeMaterial, Key: "chainloop.material.sbom", Attributes: policies}, + event: &WorkflowRunEvent{Type: WorkflowRunEventTypeMaterial, Key: "chainloop.material.sbom", Attributes: push}, wantErr: "do not match", }, { diff --git a/app/controlplane/pkg/data/ent/migrate/schema.go b/app/controlplane/pkg/data/ent/migrate/schema.go index 040af037f..bb88a1a26 100644 --- a/app/controlplane/pkg/data/ent/migrate/schema.go +++ b/app/controlplane/pkg/data/ent/migrate/schema.go @@ -1001,7 +1001,7 @@ var ( {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", "policies"}}, + {Name: "type", Type: field.TypeEnum, Enums: []string{"attestation", "material", "push"}}, {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}, diff --git a/app/controlplane/pkg/data/ent/workflowrunevent/workflowrunevent.go b/app/controlplane/pkg/data/ent/workflowrunevent/workflowrunevent.go index 89b22d3ff..88b8e109f 100644 --- a/app/controlplane/pkg/data/ent/workflowrunevent/workflowrunevent.go +++ b/app/controlplane/pkg/data/ent/workflowrunevent/workflowrunevent.go @@ -89,7 +89,7 @@ func SourceValidator(s biz.WorkflowRunEventSource) error { // 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", "policies": + case "attestation", "material", "push": return nil default: return fmt.Errorf("workflowrunevent: invalid enum value for type field: %q", _type) From 80312ef9c641967bb1db1feecfdb48c5ad46714e Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Mon, 30 Nov 2026 21:34:19 +0100 Subject: [PATCH 05/20] refactor: simplify run events after review Share one gate rule between the push event and the push command, select only the columns the run locks need, delete old events in one statement, and replace literals with constants. Refs #3825 (M1) Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1cdb3220-119c-4a14-ac50-52d5437ee4eb --- app/cli/cmd/attestation_push.go | 31 +--- app/cli/pkg/action/attestation_push.go | 13 +- app/cli/pkg/action/runevents.go | 69 ++++++--- app/cli/pkg/action/runevents_test.go | 137 ++++++++++-------- app/cli/pkg/action/workflow_run_describe.go | 11 +- .../pkg/action/workflow_run_describe_test.go | 39 ++--- .../internal/service/workflowrun.go | 5 +- .../workflowrunevent_integration_test.go | 27 ++-- app/controlplane/pkg/biz/workflowrunevent.go | 34 +++-- .../pkg/biz/workflowrunevent_test.go | 13 +- .../pkg/data/ent/schema/workflowrunevent.go | 2 +- app/controlplane/pkg/data/workflowrun.go | 4 +- app/controlplane/pkg/data/workflowrunevent.go | 23 ++- .../data/workflowrunevent_integration_test.go | 2 +- 14 files changed, 223 insertions(+), 187 deletions(-) diff --git a/app/cli/cmd/attestation_push.go b/app/cli/cmd/attestation_push.go index 2442fb74c..7594f13a0 100644 --- a/app/cli/cmd/attestation_push.go +++ b/app/cli/cmd/attestation_push.go @@ -186,35 +186,20 @@ func (e *GateError) Error() string { return fmt.Sprintf("the policy %q is configured as a gate and has violations", e.PolicyName) } -// hasGatingViolation reports whether any of the supplied violations should -// count toward the policy gate. Entries flagged Suppress (typically because -// an assessment renders the finding NOT_AFFECTED) are excluded. -func hasGatingViolation(violations []*action.PolicyViolation) bool { - for _, v := range violations { - if !v.Suppress { - return true - } - } - return false -} - func validatePolicyEnforcement(status *action.AttestationStatusResult, bypassPolicyCheck bool) error { // Block if any of the policies acts as a gate. Organization and contract // enforcement are already resolved into each evaluation's gate. Entries // flagged Suppress are excluded from the gate count but remain in // eval.Violations for CAS storage and ingestion (audit trail preserved). - for _, evaluations := range status.PolicyEvaluations { - for _, eval := range evaluations { - if eval.Gate && hasGatingViolation(eval.Violations) { - if bypassPolicyCheck { - logger.Warn().Msg(exceptionBypassPolicyCheck) - continue - } + blocking := action.BlockingPolicies(status.PolicyEvaluations) + if len(blocking) == 0 { + return nil + } - return NewGateError(eval.Name) - } - } + if bypassPolicyCheck { + logger.Warn().Msg(exceptionBypassPolicyCheck) + return nil } - return nil + return NewGateError(blocking[0]) } diff --git a/app/cli/pkg/action/attestation_push.go b/app/cli/pkg/action/attestation_push.go index 86a755a42..a483efcf6 100644 --- a/app/cli/pkg/action/attestation_push.go +++ b/app/cli/pkg/action/attestation_push.go @@ -237,13 +237,18 @@ func (action *AttestationPush) Run(ctx context.Context, attestationID string, ru return nil, fmt.Errorf("evaluating attestation policies: %w", err) } - // Progress events are best effort, they never stop the push - events := newRunEventRecorderFromState(action.CPConnection, crafter.CraftingState.CraftingState, action.Logger) - _ = events.Record(ctx, pushEvent(crafter.CraftingState.CraftingState, bypassPolicyCheck)) - // Update the status result with the definitive push-phase evaluation against the final statement attestationStatus.PolicyEvaluations, attestationStatus.HasPolicyViolations = getPolicyEvaluations(crafter) + // Progress events are best effort, they never stop the push. The push command + // enforces the same gates after the attestation is stored. + var blocking []string + if !bypassPolicyCheck { + blocking = BlockingPolicies(attestationStatus.PolicyEvaluations) + } + events := newRunEventRecorderFromState(action.CPConnection, crafter.CraftingState.CraftingState, action.Logger) + _ = events.Record(ctx, pushEvent(crafter.CraftingState.CraftingState, blocking)) + // Upload policy evaluations bundle to CAS when an external backend is available if evaluations := crafter.CraftingState.GetAttestation().GetPolicyEvaluations(); !crafter.CraftingState.DryRun && len(evaluations) > 0 { casBackend := &casclient.CASBackend{Name: "not-set"} diff --git a/app/cli/pkg/action/runevents.go b/app/cli/pkg/action/runevents.go index 689f6eaaa..193d1f222 100644 --- a/app/cli/pkg/action/runevents.go +++ b/app/cli/pkg/action/runevents.go @@ -19,6 +19,7 @@ import ( "context" "os" "path/filepath" + "sort" "strconv" "strings" "time" @@ -37,14 +38,21 @@ import ( 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 + // 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 + // 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 - runEventKeyAttestation = "chainloop.attestation" - runEventKeyMaterialPrefix = "chainloop.material." - runEventKeyPush = "chainloop.push" + runEventKeyPrefix = "chainloop." + runEventKeyAttestation = runEventKeyPrefix + "attestation" + runEventKeyMaterial = runEventKeyPrefix + "material" + runEventKeyMaterialPrefix = runEventKeyMaterial + "." + runEventKeyPush = runEventKeyPrefix + "push" + + runEventStatusStarted = "started" + runEventStatusFailed = "failed" ) // runEventRecorder sends progress events of an attestation to the control plane. @@ -138,46 +146,59 @@ func attestationStartedEvent(state *api.CraftingState, remoteState bool, cliVers } // pushEvent is sent after the push-phase policies and before the attestation is stored. -// It fails when a policy gate blocks the push, unless the check is bypassed. -func pushEvent(state *api.CraftingState, bypassPolicyCheck bool) *pb.WorkflowRunEvent { +// It fails when policy gates block the push, that is when blocking is not empty. +func pushEvent(state *api.CraftingState, blocking []string) *pb.WorkflowRunEvent { ev := &pb.WorkflowRunEvent{ Type: pb.WorkflowRunEvent_TYPE_PUSH, Key: runEventKeyPush, Status: pb.WorkflowRunEvent_STATUS_SUCCEEDED, + Attributes: &pb.WorkflowRunEvent_Push{Push: &pb.WorkflowRunEvent_PushAttributes{ + Policies: policyCounts(state, ""), + BlockingPolicies: blocking, + }}, } - attrs := &pb.WorkflowRunEvent_PushAttributes{Policies: policyCounts(state, "")} - ev.Attributes = &pb.WorkflowRunEvent_Push{Push: attrs} - if bypassPolicyCheck { - return ev + if len(blocking) > 0 { + ev.Status = pb.WorkflowRunEvent_STATUS_FAILED + ev.Message = "blocked by policy gates: " + strings.Join(blocking, ", ") } - // The same rule as the gate check of the push command - for _, e := range state.GetAttestation().GetPolicyEvaluations() { - if e.GetGate() && hasUnsuppressedViolation(e) { - attrs.BlockingPolicies = append(attrs.BlockingPolicies, e.GetName()) - } - } + return ev +} - if len(attrs.BlockingPolicies) > 0 { - ev.Status = pb.WorkflowRunEvent_STATUS_FAILED - ev.Message = "blocked by policy gates: " + strings.Join(attrs.BlockingPolicies, ", ") +// BlockingPolicies returns the sorted names of the gated policies with a violation that an +// assessment does not suppress. They block the push unless the check is bypassed. +func BlockingPolicies(evaluations map[string][]*PolicyEvaluation) []string { + var blocking []string + for _, evs := range evaluations { + for _, ev := range evs { + if !ev.Gate { + continue + } + for _, v := range ev.Violations { + if !v.Suppress { + blocking = append(blocking, ev.Name) + break + } + } + } } + sort.Strings(blocking) - return ev + return blocking } // 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.Material.Name + 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.Material.Type, + MaterialType: m.Type, Value: m.Value, Digest: m.Hash, InContract: c.IsMaterialInContract(name), @@ -192,7 +213,7 @@ func materialFailedEvent(c *crafter.Crafter, name, materialType, value string, a key := runEventKeyMaterialPrefix + name if name == "" { // the name is generated on add, so a failed add with no name has none - key = "chainloop.material" + key = runEventKeyMaterial } return &pb.WorkflowRunEvent{ diff --git a/app/cli/pkg/action/runevents_test.go b/app/cli/pkg/action/runevents_test.go index 40e6951f7..42ea838c1 100644 --- a/app/cli/pkg/action/runevents_test.go +++ b/app/cli/pkg/action/runevents_test.go @@ -41,6 +41,19 @@ import ( "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" +) + const testRunID = "4f8d2b7e-8c1b-4b1e-9f3a-2a6f1b2c3d4e" // fakeEventsControlPlane records the events it receives and answers with a configured error @@ -114,7 +127,7 @@ func newFakeEventsConn(t *testing.T, fake *fakeEventsControlPlane) *grpc.ClientC func testEvent() *pb.WorkflowRunEvent { return &pb.WorkflowRunEvent{ Type: pb.WorkflowRunEvent_TYPE_MATERIAL, - Key: "chainloop.material.sbom", + Key: testSBOMKey, Status: pb.WorkflowRunEvent_STATUS_SUCCEEDED, } } @@ -194,7 +207,7 @@ func TestRunEventRecorderLimits(t *testing.T) { ev.Status = pb.WorkflowRunEvent_STATUS_FAILED ev.Message = strings.Repeat("é", 1000) // 2000 bytes ev.Attributes = &pb.WorkflowRunEvent_Material{Material: &pb.WorkflowRunEvent_MaterialAttributes{ - Name: "sbom", Value: strings.Repeat("v", 300), + Name: testSBOM, Value: strings.Repeat("v", 300), }} require.NoError(t, r.Record(context.Background(), ev)) @@ -207,78 +220,79 @@ func TestRunEventRecorderLimits(t *testing.T) { assert.Len(t, got[0].GetEvent().GetMaterial().GetValue(), 256) } -// The push event fails when a gate blocks the push, with the same rule as the push command -func TestPushEvent(t *testing.T) { - violation := []*api.PolicyEvaluation_Violation{{Message: "bad"}} - suppressed := []*api.PolicyEvaluation_Violation{{Message: "not affected", Suppress: true}} +// The gate rule of the push: a gated policy with a violation that is not suppressed +func TestBlockingPolicies(t *testing.T) { + violation := []*PolicyViolation{{Message: testBad}} + suppressed := []*PolicyViolation{{Message: "not affected", Suppress: true}} testCases := []struct { - name string - evaluations []*api.PolicyEvaluation - bypass bool - wantStatus pb.WorkflowRunEvent_Status - wantBlocking []string + name string + evaluations map[string][]*PolicyEvaluation + want []string }{ + {name: "no gate", evaluations: map[string][]*PolicyEvaluation{testAtt: {{Name: "advisory", Violations: violation}}}}, { - name: "no gate", - evaluations: []*api.PolicyEvaluation{{Name: "advisory", Violations: violation}}, - wantStatus: pb.WorkflowRunEvent_STATUS_SUCCEEDED, - }, - { - name: "gated attestation policy with violations", - evaluations: []*api.PolicyEvaluation{{Name: "att-gate", Gate: true, Violations: violation}, {Name: "ok", Gate: true}}, - wantStatus: pb.WorkflowRunEvent_STATUS_FAILED, - wantBlocking: []string{"att-gate"}, - }, - { - name: "gated material policy with violations", - evaluations: []*api.PolicyEvaluation{{Name: "sbom-gate", MaterialName: "sbom", Gate: true, Violations: violation}}, - wantStatus: pb.WorkflowRunEvent_STATUS_FAILED, - wantBlocking: []string{"sbom-gate"}, - }, - { - name: "gated policy with suppressed violations only", - evaluations: []*api.PolicyEvaluation{{Name: "att-gate", Gate: true, Violations: suppressed}}, - wantStatus: pb.WorkflowRunEvent_STATUS_SUCCEEDED, - }, - { - name: "gate bypassed", - evaluations: []*api.PolicyEvaluation{{Name: "att-gate", Gate: true, Violations: violation}}, - bypass: true, - wantStatus: pb.WorkflowRunEvent_STATUS_SUCCEEDED, + name: "gated policies with violations, sorted", + evaluations: map[string][]*PolicyEvaluation{ + testSBOM: {{Name: "sbom-gate", Gate: true, Violations: violation}}, + testAtt: {{Name: testAttGate, Gate: true, Violations: violation}, {Name: "ok", Gate: true}}, + }, + want: []string{testAttGate, "sbom-gate"}, }, + {name: "suppressed violations only", evaluations: map[string][]*PolicyEvaluation{testAtt: {{Name: testAttGate, Gate: true, Violations: suppressed}}}}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, BlockingPolicies(tc.evaluations)) + }) + } +} + +func TestPushEvent(t *testing.T) { + state := &api.CraftingState{Attestation: &api.Attestation{PolicyEvaluations: []*api.PolicyEvaluation{ + {Name: testAttGate, Gate: true, Violations: []*api.PolicyEvaluation_Violation{{Message: testBad}}}, + {Name: "sbom-policy", MaterialName: testSBOM}, + }}} + + testCases := []struct { + name string + blocking []string + wantStatus pb.WorkflowRunEvent_Status + }{ + {name: "not blocked, or bypassed", wantStatus: pb.WorkflowRunEvent_STATUS_SUCCEEDED}, + {name: "blocked by a gate", blocking: []string{testAttGate}, wantStatus: pb.WorkflowRunEvent_STATUS_FAILED}, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - state := &api.CraftingState{Attestation: &api.Attestation{PolicyEvaluations: tc.evaluations}} - ev := pushEvent(state, tc.bypass) + ev := pushEvent(state, tc.blocking) assert.Equal(t, "chainloop.push", ev.GetKey()) assert.Equal(t, pb.WorkflowRunEvent_TYPE_PUSH, ev.GetType()) assert.Equal(t, tc.wantStatus, ev.GetStatus()) - assert.Equal(t, tc.wantBlocking, ev.GetPush().GetBlockingPolicies()) - if tc.wantStatus == pb.WorkflowRunEvent_STATUS_FAILED { - assert.Contains(t, ev.GetMessage(), tc.wantBlocking[0]) + assert.Equal(t, tc.blocking, ev.GetPush().GetBlockingPolicies()) + if tc.blocking != nil { + assert.Contains(t, ev.GetMessage(), testAttGate) } else { assert.Empty(t, ev.GetMessage()) } // the counts cover the attestation policies only, material policies are in material events - assert.Equal(t, policyCounts(state, ""), ev.GetPush().GetPolicies()) + assert.Equal(t, int32(1), ev.GetPush().GetPolicies().GetEvaluated()) }) } } func TestPolicyCounts(t *testing.T) { - violation := []*api.PolicyEvaluation_Violation{{Message: "bad"}} + 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: "sbom"}, - {Name: "sbom-skipped", MaterialName: "sbom", Skipped: true}, - {Name: "sbom-violated", MaterialName: "sbom", Violations: violation}, - {Name: "sbom-suppressed", MaterialName: "sbom", Violations: suppressed}, + {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 { @@ -292,12 +306,12 @@ func TestPolicyCounts(t *testing.T) { }, { name: "material policies", - material: "sbom", + material: testSBOM, want: &pb.WorkflowRunEvent_PolicyCounts{Evaluated: 4, Passed: 2, Violated: 1, Skipped: 1, ViolatedPolicies: []string{"sbom-violated"}}, }, { name: "material with no policies", - material: "image", + material: testImage, want: &pb.WorkflowRunEvent_PolicyCounts{}, }, } @@ -331,9 +345,8 @@ func newLocalCrafter(t *testing.T, conn *grpc.ClientConn, statePath string) *cra // 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" - materialValueText = "commit-1234" + secretEnvValue = "env-secret-value" + annotationValue = "annotation-secret-value" ) t.Setenv("SOME_ENV_VAR", secretEnvValue) @@ -341,7 +354,7 @@ func TestMaterialEventHoldsOnlySafeData(t *testing.T) { 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", materialValueText, nil, map[string]string{"owner": annotationValue}) + 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) @@ -349,7 +362,7 @@ func TestMaterialEventHoldsOnlySafeData(t *testing.T) { events := []*pb.WorkflowRunEvent{ materialAddedEvent(c, res, false), attestationStartedEvent(c.CraftingState.CraftingState, true, "v1.2.3"), - pushEvent(c.CraftingState.CraftingState, false), + pushEvent(c.CraftingState.CraftingState, nil), } for _, ev := range events { @@ -361,7 +374,7 @@ func TestMaterialEventHoldsOnlySafeData(t *testing.T) { m := events[0].GetMaterial() assert.Equal(t, "chainloop.material.build-ref", events[0].GetKey()) - assert.Equal(t, materialValueText, m.GetValue()) + assert.Equal(t, testCommit, m.GetValue()) assert.Equal(t, "STRING", m.GetMaterialType()) assert.True(t, m.GetInContract()) assert.NotEmpty(t, m.GetDigest()) @@ -383,11 +396,11 @@ func TestAttestationAddRecordsEvents(t *testing.T) { wantErr bool wantEvent pb.WorkflowRunEvent_Status }{ - {name: "add succeeds", value: "commit-1234", wantEvent: pb.WorkflowRunEvent_STATUS_SUCCEEDED}, - {name: "add succeeds, event rejected", value: "commit-1234", eventErr: status.Error(codes.FailedPrecondition, "not in progress"), wantEvent: pb.WorkflowRunEvent_STATUS_SUCCEEDED}, - {name: "add succeeds, older control plane", value: "commit-1234", eventErr: status.Error(codes.Unimplemented, "unknown method"), wantEvent: pb.WorkflowRunEvent_STATUS_SUCCEEDED}, - {name: "add fails", value: "/does/not/exist.json", kind: "SBOM_CYCLONEDX_JSON", wantErr: true, wantEvent: pb.WorkflowRunEvent_STATUS_FAILED}, - {name: "add fails, event fails", value: "/does/not/exist.json", kind: "SBOM_CYCLONEDX_JSON", eventErr: status.Error(codes.Unavailable, "down"), wantErr: true, wantEvent: pb.WorkflowRunEvent_STATUS_FAILED}, + {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 { @@ -405,7 +418,7 @@ func TestAttestationAddRecordsEvents(t *testing.T) { name := "build-ref" if tc.kind != "" { - name = "sbom" + name = testSBOM } res, err := add.Run(context.Background(), "", name, tc.value, tc.kind, nil, nil, nil) if tc.wantErr { diff --git a/app/cli/pkg/action/workflow_run_describe.go b/app/cli/pkg/action/workflow_run_describe.go index 0e773cfab..ae20d884e 100644 --- a/app/cli/pkg/action/workflow_run_describe.go +++ b/app/cli/pkg/action/workflow_run_describe.go @@ -707,7 +707,7 @@ func buildRunProgress(contractMaterials []*schemaapi.CraftingSchema_Material, ev order = append(order, name) } latest[name] = e - if e.Status == "failed" { + if e.Status == runEventStatusFailed { failed[name]++ } // the latest attestation policy results: init, then push @@ -725,7 +725,7 @@ func buildRunProgress(contractMaterials []*schemaapi.CraftingSchema_Material, ev } m.FailedAdds = failed[m.Name] - if e.Status == "failed" { + if e.Status == runEventStatusFailed { m.Error = e.Message return } @@ -790,7 +790,7 @@ func buildRunSteps(events []*RunEvent, now time.Time) []*RunProgressStep { for _, s := range steps { end := last[s.Key] - if s.Status == "started" { + if s.Status == runEventStatusStarted { end = &now } if s.StartedAt != nil && end != nil && end.After(*s.StartedAt) { @@ -803,10 +803,9 @@ func buildRunSteps(events []*RunEvent, now time.Time) []*RunProgressStep { // RunStepName is the name of a step shown to the user: the key with no automatic prefix func RunStepName(key string) string { - name := strings.TrimPrefix(key, "chainloop.") - if material, ok := strings.CutPrefix(name, "material."); ok { + if material, ok := strings.CutPrefix(key, runEventKeyMaterialPrefix); ok { return material } - return name + return strings.TrimPrefix(key, runEventKeyPrefix) } diff --git a/app/cli/pkg/action/workflow_run_describe_test.go b/app/cli/pkg/action/workflow_run_describe_test.go index 27f034ad6..e0758964b 100644 --- a/app/cli/pkg/action/workflow_run_describe_test.go +++ b/app/cli/pkg/action/workflow_run_describe_test.go @@ -168,7 +168,7 @@ func TestPBPolicyEvaluationsRefToAction(t *testing.T) { func materialRunEvent(at time.Time, name, status, message string) *RunEvent { return &RunEvent{ CreatedAt: &at, Type: "material", Key: "chainloop.material." + name, Status: status, Message: message, - Material: &RunEventMaterial{Name: name, MaterialType: "SBOM_CYCLONEDX_JSON", Value: name + ".json"}, + Material: &RunEventMaterial{Name: name, MaterialType: testSBOMKind, Value: name + ".json"}, } } @@ -176,11 +176,11 @@ func TestBuildRunProgress(t *testing.T) { start := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC) now := start.Add(5*time.Minute + 45*time.Second) contract := []*schemaapi.CraftingSchema_Material{ - {Name: "sbom", Type: schemaapi.CraftingSchema_Material_SBOM_CYCLONEDX_JSON}, - {Name: "image", Type: schemaapi.CraftingSchema_Material_CONTAINER_IMAGE}, + {Name: testSBOM, Type: schemaapi.CraftingSchema_Material_SBOM_CYCLONEDX_JSON}, + {Name: testImage, Type: schemaapi.CraftingSchema_Material_CONTAINER_IMAGE}, {Name: "sast-report", Type: schemaapi.CraftingSchema_Material_SARIF, Optional: true}, } - started := &RunEvent{CreatedAt: &start, Type: "attestation", Key: "chainloop.attestation", Status: "started"} + started := &RunEvent{CreatedAt: &start, Type: "attestation", Key: testAttKey, Status: "started"} testCases := []struct { name string @@ -194,29 +194,29 @@ func TestBuildRunProgress(t *testing.T) { name: "failed add shows the material as missing with the error", events: []*RunEvent{ started, - materialRunEvent(start.Add(3*time.Minute), "sbom", "failed", "invalid CycloneDX document"), + materialRunEvent(start.Add(3*time.Minute), testSBOM, "failed", "invalid CycloneDX document"), }, want: map[string]RunProgressMaterial{ - "sbom": {Required: true, InContract: true, Provided: false, FailedAdds: 1, Error: "invalid CycloneDX document"}, - "image": {Required: true, InContract: true}, + testSBOM: {Required: true, InContract: true, Provided: false, FailedAdds: 1, Error: "invalid CycloneDX document"}, + testImage: {Required: true, InContract: true}, "sast-report": {InContract: true}, }, wantRequired: [2]int{0, 2}, - wantStepDuration: map[string]time.Duration{"chainloop.attestation": 5*time.Minute + 45*time.Second}, + wantStepDuration: map[string]time.Duration{testAttKey: 5*time.Minute + 45*time.Second}, }, { name: "failed then repeated add shows the material as provided", events: []*RunEvent{ started, - materialRunEvent(start.Add(3*time.Minute), "sbom", "failed", "invalid CycloneDX document"), - materialRunEvent(start.Add(4*time.Minute), "sbom", "succeeded", ""), + materialRunEvent(start.Add(3*time.Minute), testSBOM, "failed", "invalid CycloneDX document"), + materialRunEvent(start.Add(4*time.Minute), testSBOM, "succeeded", ""), }, want: map[string]RunProgressMaterial{ - "sbom": {Required: true, InContract: true, Provided: true, FailedAdds: 1, Value: "sbom.json"}, - "image": {Required: true, InContract: true}, + testSBOM: {Required: true, InContract: true, Provided: true, FailedAdds: 1, Value: testSBOMFile}, + testImage: {Required: true, InContract: true}, }, wantRequired: [2]int{1, 2}, - wantStepDuration: map[string]time.Duration{"chainloop.material.sbom": time.Minute}, + wantStepDuration: map[string]time.Duration{testSBOMKey: time.Minute}, }, { name: "material not in the contract", @@ -226,7 +226,7 @@ func TestBuildRunProgress(t *testing.T) { }, want: map[string]RunProgressMaterial{ "build-log": {InContract: false, Provided: true, Value: "build-log.json"}, - "sbom": {Required: true, InContract: true}, + testSBOM: {Required: true, InContract: true}, }, wantRequired: [2]int{0, 2}, }, @@ -274,7 +274,7 @@ func TestBuildRunProgressAttestationPolicies(t *testing.T) { now := time.Now() initCounts := &RunEventPolicyCount{Evaluated: 2, Passed: 2} pushCounts := &RunEventPolicyCount{Evaluated: 3, Passed: 2, Violated: 1} - started := &RunEvent{CreatedAt: &now, Key: "chainloop.attestation", Status: "started", Attestation: &RunEventAttestation{Policies: initCounts}} + started := &RunEvent{CreatedAt: &now, Key: testAttKey, Status: "started", Attestation: &RunEventAttestation{Policies: initCounts}} push := &RunEvent{CreatedAt: &now, Key: "chainloop.push", Status: "failed", Push: &RunEventPush{Policies: pushCounts, BlockingPolicies: []string{"gate"}}} assert.Equal(t, initCounts, buildRunProgress(nil, []*RunEvent{started}, now).AttestationPolicies) @@ -294,8 +294,9 @@ func (f *fakeRunViewServer) View(context.Context, *pb.WorkflowRunServiceViewRequ WorkflowRun: &pb.WorkflowRunItem{ Id: testRunID, Status: f.status, CreatedAt: timestamppb.Now(), ContractVersion: &pb.WorkflowContractVersionItem{ + //nolint:staticcheck // the V1 body is the fallback that describe reads Contract: &pb.WorkflowContractVersionItem_V1{V1: &schemaapi.CraftingSchema{Materials: []*schemaapi.CraftingSchema_Material{ - {Name: "sbom", Type: schemaapi.CraftingSchema_Material_SBOM_CYCLONEDX_JSON}, + {Name: testSBOM, Type: schemaapi.CraftingSchema_Material_SBOM_CYCLONEDX_JSON}, }}}, }, }, @@ -313,12 +314,12 @@ func (f *fakeRunViewServer) ListEvents(context.Context, *pb.WorkflowRunServiceLi func TestWorkflowRunDescribeEvents(t *testing.T) { sbomFailed := &pb.WorkflowRunEvent{ Id: "1", CreatedAt: timestamppb.Now(), Source: pb.WorkflowRunEvent_SOURCE_CLI, Type: pb.WorkflowRunEvent_TYPE_MATERIAL, - Key: "chainloop.material.sbom", Status: pb.WorkflowRunEvent_STATUS_FAILED, Message: "invalid CycloneDX document", - Attributes: &pb.WorkflowRunEvent_Material{Material: &pb.WorkflowRunEvent_MaterialAttributes{Name: "sbom", InContract: true}}, + Key: testSBOMKey, Status: pb.WorkflowRunEvent_STATUS_FAILED, Message: "invalid CycloneDX document", + 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: "chainloop.attestation", Status: pb.WorkflowRunEvent_STATUS_FAILED, Message: "expired", + Key: testAttKey, Status: pb.WorkflowRunEvent_STATUS_FAILED, Message: "expired", } testCases := []struct { diff --git a/app/controlplane/internal/service/workflowrun.go b/app/controlplane/internal/service/workflowrun.go index cefbf5047..08ace5fec 100644 --- a/app/controlplane/internal/service/workflowrun.go +++ b/app/controlplane/internal/service/workflowrun.go @@ -666,10 +666,7 @@ var ( // 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) { - if in == nil { - return nil, biz.NewErrValidationStr("event is required") - } - + // 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())) diff --git a/app/controlplane/internal/service/workflowrunevent_integration_test.go b/app/controlplane/internal/service/workflowrunevent_integration_test.go index ab4355e3c..ae7f5a0d8 100644 --- a/app/controlplane/internal/service/workflowrunevent_integration_test.go +++ b/app/controlplane/internal/service/workflowrunevent_integration_test.go @@ -66,18 +66,18 @@ func (s *workflowRunEventRBACIntegrationSuite) SetupTest() { 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: "workflow-a", OrgID: s.org.ID, Project: "project-a"}) + 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: "project-a"}) + 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: "workflow-b", OrgID: s.org.ID, Project: "project-b"}) + _, 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: "workflow-a", OrgID: s.otherOrg.ID, Project: "project-a"}) + 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("project-a")}) + 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("project-b")}) + 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) @@ -118,12 +118,21 @@ func (s *workflowRunEventRBACIntegrationSuite) SetupTest() { }) } +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) @@ -143,7 +152,7 @@ func materialEventRequest(runID string) *pb.AttestationServiceRecordEventRequest Key: "chainloop.material.sbom", Status: pb.WorkflowRunEvent_STATUS_SUCCEEDED, Attributes: &pb.WorkflowRunEvent_Material{Material: &pb.WorkflowRunEvent_MaterialAttributes{ - Name: "sbom", MaterialType: "SBOM_CYCLONEDX_JSON", Value: "sbom.json", + Name: sbomMaterial, MaterialType: "SBOM_CYCLONEDX_JSON", Value: "sbom.json", }}, }, } @@ -288,7 +297,7 @@ func (s *workflowRunEventRBACIntegrationSuite) TestRecordAndList() { s.Equal(pb.WorkflowRunEvent_SOURCE_CLI, got.GetSource(), "the server sets the source") s.NotEmpty(got.GetId()) s.NotNil(got.GetCreatedAt()) - s.Equal("sbom", got.GetMaterial().GetName()) + s.Equal(sbomMaterial, got.GetMaterial().GetName()) s.Equal("sbom.json", got.GetMaterial().GetValue()) // a store closes the timeline, and the run accepts no more events @@ -318,7 +327,7 @@ func (s *workflowRunEventRBACIntegrationSuite) TestRecordEventValidation() { name: "attributes that do not match the type", event: &pb.WorkflowRunEvent{ Type: pb.WorkflowRunEvent_TYPE_PUSH, Key: "chainloop.push", Status: pb.WorkflowRunEvent_STATUS_SUCCEEDED, - Attributes: &pb.WorkflowRunEvent_Material{Material: &pb.WorkflowRunEvent_MaterialAttributes{Name: "sbom"}}, + Attributes: &pb.WorkflowRunEvent_Material{Material: &pb.WorkflowRunEvent_MaterialAttributes{Name: sbomMaterial}}, }, }, { diff --git a/app/controlplane/pkg/biz/workflowrunevent.go b/app/controlplane/pkg/biz/workflowrunevent.go index 6bb9fa7e2..1efa58100 100644 --- a/app/controlplane/pkg/biz/workflowrunevent.go +++ b/app/controlplane/pkg/biz/workflowrunevent.go @@ -18,6 +18,7 @@ package biz import ( "context" "fmt" + "slices" "strings" "time" "unicode/utf8" @@ -198,20 +199,25 @@ func validateWorkflowRunEvent(ev *WorkflowRunEvent) error { return NewErrValidationStr(fmt.Sprintf("event message is longer than %d bytes", MaxWorkflowRunEventMessageBytes)) } - attrs := ev.Attributes - var match bool - switch ev.Type { - case WorkflowRunEventTypeAttestation: - match = attrs == nil || (attrs.Material == nil && attrs.Push == nil) - case WorkflowRunEventTypeMaterial: - match = attrs == nil || (attrs.Attestation == nil && attrs.Push == nil) - case WorkflowRunEventTypePush: - match = attrs == nil || (attrs.Attestation == nil && attrs.Material == nil) - default: + // 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 attrs.Push != nil { + set = append(set, WorkflowRunEventTypePush) + } + } + + if !slices.Contains(ev.Type.Values(), string(ev.Type)) { return NewErrValidationStr(fmt.Sprintf("unsupported event type %q", ev.Type)) } - if !match { + 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)) } @@ -268,14 +274,12 @@ func ClosingWorkflowRunEvent(runID uuid.UUID, runStatus WorkflowRunStatus, reaso Source: WorkflowRunEventSourceControlPlane, Type: WorkflowRunEventTypeAttestation, Key: WorkflowRunEventKeyAttestation, - Message: truncateBytes(reason, MaxWorkflowRunEventMessageBytes), } switch runStatus { case WorkflowRunSuccess: - ev.Status = WorkflowRunEventStatusSucceeded // Automatic events that succeed have no message - ev.Message = "" + ev.Status = WorkflowRunEventStatusSucceeded if attestationDigest != "" { ev.Attributes = &WorkflowRunEventAttributes{ Attestation: &WorkflowRunEventAttestationAttributes{AttestationDigest: attestationDigest}, @@ -283,8 +287,10 @@ func ClosingWorkflowRunEvent(runID uuid.UUID, runStatus WorkflowRunStatus, reaso } 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 diff --git a/app/controlplane/pkg/biz/workflowrunevent_test.go b/app/controlplane/pkg/biz/workflowrunevent_test.go index 875fd7646..5a5237103 100644 --- a/app/controlplane/pkg/biz/workflowrunevent_test.go +++ b/app/controlplane/pkg/biz/workflowrunevent_test.go @@ -25,6 +25,11 @@ import ( "github.com/stretchr/testify/require" ) +const ( + sbomKey = "chainloop.material.sbom" + shortText = "abc" +) + func TestValidateWorkflowRunEvent(t *testing.T) { material := &WorkflowRunEventAttributes{Material: &WorkflowRunEventMaterialAttributes{Name: "sbom"}} push := &WorkflowRunEventAttributes{Push: &WorkflowRunEventPushAttributes{BlockingPolicies: []string{"gate"}}} @@ -36,7 +41,7 @@ func TestValidateWorkflowRunEvent(t *testing.T) { }{ { name: "material event", - event: &WorkflowRunEvent{Type: WorkflowRunEventTypeMaterial, Key: "chainloop.material.sbom", Attributes: material}, + event: &WorkflowRunEvent{Type: WorkflowRunEventTypeMaterial, Key: sbomKey, Attributes: material}, }, { name: "event with no attributes", @@ -49,7 +54,7 @@ func TestValidateWorkflowRunEvent(t *testing.T) { }, { name: "attributes of another type", - event: &WorkflowRunEvent{Type: WorkflowRunEventTypeMaterial, Key: "chainloop.material.sbom", Attributes: push}, + event: &WorkflowRunEvent{Type: WorkflowRunEventTypeMaterial, Key: sbomKey, Attributes: push}, wantErr: "do not match", }, { @@ -59,7 +64,7 @@ func TestValidateWorkflowRunEvent(t *testing.T) { }, { name: "message over the limit", - event: &WorkflowRunEvent{Type: WorkflowRunEventTypeMaterial, Key: "chainloop.material.sbom", Message: strings.Repeat("a", MaxWorkflowRunEventMessageBytes+1)}, + event: &WorkflowRunEvent{Type: WorkflowRunEventTypeMaterial, Key: sbomKey, Message: strings.Repeat("a", MaxWorkflowRunEventMessageBytes+1)}, wantErr: "longer than", }, } @@ -129,7 +134,7 @@ func TestTruncateBytes(t *testing.T) { n int want string }{ - {name: "short", in: "abc", n: 5, want: "abc"}, + {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"}, diff --git a/app/controlplane/pkg/data/ent/schema/workflowrunevent.go b/app/controlplane/pkg/data/ent/schema/workflowrunevent.go index fcc7fb109..f9d9a121f 100644 --- a/app/controlplane/pkg/data/ent/schema/workflowrunevent.go +++ b/app/controlplane/pkg/data/ent/schema/workflowrunevent.go @@ -41,7 +41,7 @@ func (WorkflowRunEvent) Fields() []ent.Field { field.Time("created_at"). Default(time.Now). Immutable(). - Annotations(&entsql.Annotation{Default: "CURRENT_TIMESTAMP"}), + Annotations(&entsql.Annotation{Default: currentTimestamp}), field.Enum("source").GoType(biz.WorkflowRunEventSource("")).Immutable(), field.Enum("type").GoType(biz.WorkflowRunEventType("")).Immutable(), field.String("key").Immutable(), diff --git a/app/controlplane/pkg/data/workflowrun.go b/app/controlplane/pkg/data/workflowrun.go index 776420596..fffc6527d 100644 --- a/app/controlplane/pkg/data/workflowrun.go +++ b/app/controlplane/pkg/data/workflowrun.go @@ -422,7 +422,7 @@ func (r *WorkflowRunRepo) MarkAsFinished(ctx context.Context, id uuid.UUID, stat // 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)).ForUpdate().Only(ctx) + 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) } @@ -579,7 +579,7 @@ func (r *WorkflowRunRepo) Expire(ctx context.Context, id uuid.UUID) error { defer span.End() return WithTx(ctx, r.data.DB, func(tx *ent.Tx) error { - run, err := tx.WorkflowRun.Query().Where(workflowrun.ID(id)).ForUpdate().Only(ctx) + 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) } diff --git a/app/controlplane/pkg/data/workflowrunevent.go b/app/controlplane/pkg/data/workflowrunevent.go index 1a47c14d2..3096bb4bd 100644 --- a/app/controlplane/pkg/data/workflowrunevent.go +++ b/app/controlplane/pkg/data/workflowrunevent.go @@ -48,7 +48,7 @@ func (r *WorkflowRunEventRepo) Create(ctx context.Context, event *biz.WorkflowRu 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)).ForUpdate().Only(ctx) + 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") @@ -148,19 +148,14 @@ func (r *WorkflowRunEventRepo) DeleteOlderThan(ctx context.Context, t time.Time, ctx, span := otelx.Start(ctx, workflowRunEventRepoTracer, "WorkflowRunEventRepo.DeleteOlderThan") defer span.End() - ids, err := r.data.DB.WorkflowRunEvent.Query(). - Where(workflowrunevent.CreatedAtLT(t)). - Limit(limit). - IDs(ctx) - if err != nil { - return 0, fmt.Errorf("failed to find old workflow run events: %w", err) - } - - if len(ids) == 0 { - return 0, nil - } - - n, err := r.data.DB.WorkflowRunEvent.Delete().Where(workflowrunevent.IDIn(ids...)).Exec(ctx) + // 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) } diff --git a/app/controlplane/pkg/data/workflowrunevent_integration_test.go b/app/controlplane/pkg/data/workflowrunevent_integration_test.go index 4acd8aacd..4aa53e820 100644 --- a/app/controlplane/pkg/data/workflowrunevent_integration_test.go +++ b/app/controlplane/pkg/data/workflowrunevent_integration_test.go @@ -156,7 +156,7 @@ func (s *workflowRunEventIntegrationTestSuite) TestList() { repo := s.Repos.WorkflowRunEvent runID := s.newRun() - var ids []uuid.UUID + 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) From b1cf3df18bfe567db3d26199c2e3a1d6907c73db Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Mon, 30 Nov 2026 21:43:03 +0100 Subject: [PATCH 06/20] fix(cli): record the push event just before the store The push event is recorded after the dry-run return and before the attestation is stored, so a dry run records none. The gate check now lives in the push action, and the push command uses it. Refs #3825 (M1, R-001) Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1cdb3220-119c-4a14-ac50-52d5437ee4eb --- app/cli/pkg/action/attestation_push.go | 49 +++++++++++++++++++++----- app/cli/pkg/action/runevents.go | 23 ------------ app/cli/pkg/action/runevents_test.go | 42 ++++++++++++++++++++++ 3 files changed, 82 insertions(+), 32 deletions(-) diff --git a/app/cli/pkg/action/attestation_push.go b/app/cli/pkg/action/attestation_push.go index a483efcf6..b61ca0151 100644 --- a/app/cli/pkg/action/attestation_push.go +++ b/app/cli/pkg/action/attestation_push.go @@ -23,6 +23,7 @@ import ( "encoding/json" "fmt" "os" + "sort" "time" pb "github.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1" @@ -240,15 +241,6 @@ func (action *AttestationPush) Run(ctx context.Context, attestationID string, ru // Update the status result with the definitive push-phase evaluation against the final statement attestationStatus.PolicyEvaluations, attestationStatus.HasPolicyViolations = getPolicyEvaluations(crafter) - // Progress events are best effort, they never stop the push. The push command - // enforces the same gates after the attestation is stored. - var blocking []string - if !bypassPolicyCheck { - blocking = BlockingPolicies(attestationStatus.PolicyEvaluations) - } - events := newRunEventRecorderFromState(action.CPConnection, crafter.CraftingState.CraftingState, action.Logger) - _ = events.Record(ctx, pushEvent(crafter.CraftingState.CraftingState, blocking)) - // Upload policy evaluations bundle to CAS when an external backend is available if evaluations := crafter.CraftingState.GetAttestation().GetPolicyEvaluations(); !crafter.CraftingState.DryRun && len(evaluations) > 0 { casBackend := &casclient.CASBackend{Name: "not-set"} @@ -293,6 +285,11 @@ func (action *AttestationPush) Run(ctx context.Context, attestationID string, ru workflow := crafter.CraftingState.Attestation.GetWorkflow() + // Progress events are best effort, they never stop the push. The push command + // enforces the same gates after the attestation is stored. + recordPushEvent(ctx, newRunEventRecorderFromState(action.CPConnection, crafter.CraftingState.CraftingState, action.Logger), + crafter.CraftingState.CraftingState, attestationStatus.PolicyEvaluations, bypassPolicyCheck) + attestationResult.Digest, err = pushToControlPlane(ctx, action.CPConnection, bundle, workflow.GetWorkflowRunId(), workflow.GetVersion().GetMarkAsReleased()) if err != nil { return nil, fmt.Errorf("pushing to control plane: %w", err) @@ -334,6 +331,40 @@ func (action *AttestationPush) saveBundle(bundle *protobundle.Bundle) error { return nil } +// recordPushEvent records the push event with all the attestation policies of the run. It +// fails when gates block the push and the check is not bypassed. A dry run has no run, so +// its recorder sends nothing. +func recordPushEvent(ctx context.Context, events *runEventRecorder, state *v1.CraftingState, evaluations map[string][]*PolicyEvaluation, bypassPolicyCheck bool) { + var blocking []string + if !bypassPolicyCheck { + blocking = BlockingPolicies(evaluations) + } + + _ = events.Record(ctx, pushEvent(state, blocking)) +} + +// BlockingPolicies returns the sorted names of the gated policies with a violation that an +// assessment does not suppress. They block the push unless the check is bypassed. +func BlockingPolicies(evaluations map[string][]*PolicyEvaluation) []string { + var blocking []string + for _, evs := range evaluations { + for _, ev := range evs { + if !ev.Gate { + continue + } + for _, v := range ev.Violations { + if !v.Suppress { + blocking = append(blocking, ev.Name) + break + } + } + } + } + sort.Strings(blocking) + + return blocking +} + func pushToControlPlane(ctx context.Context, conn *grpc.ClientConn, bundle *protobundle.Bundle, workflowRunID string, markVersionAsReleased bool) (string, error) { encodedBundle, err := encodeBundle(bundle) if err != nil { diff --git a/app/cli/pkg/action/runevents.go b/app/cli/pkg/action/runevents.go index 193d1f222..ec3a97c34 100644 --- a/app/cli/pkg/action/runevents.go +++ b/app/cli/pkg/action/runevents.go @@ -19,7 +19,6 @@ import ( "context" "os" "path/filepath" - "sort" "strconv" "strings" "time" @@ -166,28 +165,6 @@ func pushEvent(state *api.CraftingState, blocking []string) *pb.WorkflowRunEvent return ev } -// BlockingPolicies returns the sorted names of the gated policies with a violation that an -// assessment does not suppress. They block the push unless the check is bypassed. -func BlockingPolicies(evaluations map[string][]*PolicyEvaluation) []string { - var blocking []string - for _, evs := range evaluations { - for _, ev := range evs { - if !ev.Gate { - continue - } - for _, v := range ev.Violations { - if !v.Suppress { - blocking = append(blocking, ev.Name) - break - } - } - } - } - sort.Strings(blocking) - - return blocking -} - // 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 { diff --git a/app/cli/pkg/action/runevents_test.go b/app/cli/pkg/action/runevents_test.go index 42ea838c1..6583aa43d 100644 --- a/app/cli/pkg/action/runevents_test.go +++ b/app/cli/pkg/action/runevents_test.go @@ -249,6 +249,48 @@ func TestBlockingPolicies(t *testing.T) { } } +// The push records its event before the store: failed when a gate blocks it, succeeded +// when the gate is bypassed, and nothing in a dry run +func TestRecordPushEvent(t *testing.T) { + gated := map[string][]*PolicyEvaluation{testAtt: {{Name: testAttGate, Gate: true, Violations: []*PolicyViolation{{Message: testBad}}}}} + runState := &api.CraftingState{Attestation: &api.Attestation{Workflow: &api.WorkflowMetadata{WorkflowRunId: testRunID}}} + dryRunState := &api.CraftingState{DryRun: true, Attestation: runState.GetAttestation()} + + testCases := []struct { + name string + state *api.CraftingState + bypass bool + wantSent bool + wantStatus pb.WorkflowRunEvent_Status + wantBlocking []string + }{ + {name: "blocked push", state: runState, wantSent: true, wantStatus: pb.WorkflowRunEvent_STATUS_FAILED, wantBlocking: []string{testAttGate}}, + {name: "bypassed gate", state: runState, bypass: true, wantSent: true, wantStatus: pb.WorkflowRunEvent_STATUS_SUCCEEDED}, + {name: "dry run", state: dryRunState}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + fake := &fakeEventsControlPlane{} + events := newRunEventRecorderFromState(newFakeEventsConn(t, fake), tc.state, zerolog.Nop()) + + recordPushEvent(context.Background(), events, tc.state, gated, tc.bypass) + + got := fake.received() + if !tc.wantSent { + assert.Empty(t, got) + return + } + + require.Len(t, got, 1) + ev := got[0].GetEvent() + assert.Equal(t, "chainloop.push", ev.GetKey()) + assert.Equal(t, tc.wantStatus, ev.GetStatus()) + assert.Equal(t, tc.wantBlocking, ev.GetPush().GetBlockingPolicies()) + }) + } +} + func TestPushEvent(t *testing.T) { state := &api.CraftingState{Attestation: &api.Attestation{PolicyEvaluations: []*api.PolicyEvaluation{ {Name: testAttGate, Gate: true, Violations: []*api.PolicyEvaluation_Violation{{Message: testBad}}}, From 7a9647515f0bba6375b6e09928b85e534ff5a535 Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Mon, 30 Nov 2026 22:11:31 +0100 Subject: [PATCH 07/20] fix: address review of the run events - the expiry sweep skips a run that finished during the sweep, with no expiry metric or log - trace pushes do not enforce policy gates, so their push event never reports a block - blocking policies are listed once - describe counts a group of the contract once as required - describe JSON always has remote_state and added_by_collector - test the FailedPrecondition error mapping Refs #3825 (M1) Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1cdb3220-119c-4a14-ac50-52d5437ee4eb --- app/cli/cmd/workflow_workflow_run_describe.go | 2 ++ app/cli/pkg/action/attestation_push.go | 11 +++++-- app/cli/pkg/action/runevents_test.go | 13 ++++++-- app/cli/pkg/action/trace_attestation.go | 2 ++ app/cli/pkg/action/workflow_run_describe.go | 32 +++++++++++++------ .../pkg/action/workflow_run_describe_test.go | 29 +++++++++++++++++ .../internal/service/service_test.go | 7 ++++ app/controlplane/pkg/biz/workflowrun.go | 6 +++- app/controlplane/pkg/biz/workflowrun_test.go | 11 +++++++ app/controlplane/pkg/data/workflowrun.go | 4 +-- .../data/workflowrunevent_integration_test.go | 3 +- 11 files changed, 103 insertions(+), 17 deletions(-) diff --git a/app/cli/cmd/workflow_workflow_run_describe.go b/app/cli/cmd/workflow_workflow_run_describe.go index 5cb60257c..a14e68b50 100644 --- a/app/cli/cmd/workflow_workflow_run_describe.go +++ b/app/cli/cmd/workflow_workflow_run_describe.go @@ -199,6 +199,8 @@ func runProgressTables(progress *action.RunProgress, events []*action.RunEvent) switch { case !m.InContract: requirement = "not in contract" + case m.Group != "": + requirement = "one of " + m.Group case m.Required: requirement = "required" } diff --git a/app/cli/pkg/action/attestation_push.go b/app/cli/pkg/action/attestation_push.go index b61ca0151..ef145d80f 100644 --- a/app/cli/pkg/action/attestation_push.go +++ b/app/cli/pkg/action/attestation_push.go @@ -23,6 +23,7 @@ import ( "encoding/json" "fmt" "os" + "slices" "sort" "time" @@ -50,6 +51,9 @@ type AttestationPushOpts struct { ConnectionInsecure bool LocalStatePath string SignServerOpts *SignServerOpts + // NoPolicyGates tells that the caller does not enforce policy gates after the push, + // so the push event never reports a blocked push + NoPolicyGates bool } // SignServerOpts holds SignServer integration options @@ -88,6 +92,7 @@ type AttestationPush struct { connectionInsecure bool localStatePath string signServerOpts *SignServerOpts + noPolicyGates bool *newCrafterOpts } @@ -103,6 +108,7 @@ func NewAttestationPush(cfg *AttestationPushOpts) (*AttestationPush, error) { casCAPath: cfg.CASCAPath, connectionInsecure: cfg.ConnectionInsecure, signServerOpts: cfg.SignServerOpts, + noPolicyGates: cfg.NoPolicyGates, localStatePath: cfg.LocalStatePath, newCrafterOpts: &newCrafterOpts{cpConnection: cfg.CPConnection, opts: opts}, }, nil @@ -288,7 +294,7 @@ func (action *AttestationPush) Run(ctx context.Context, attestationID string, ru // Progress events are best effort, they never stop the push. The push command // enforces the same gates after the attestation is stored. recordPushEvent(ctx, newRunEventRecorderFromState(action.CPConnection, crafter.CraftingState.CraftingState, action.Logger), - crafter.CraftingState.CraftingState, attestationStatus.PolicyEvaluations, bypassPolicyCheck) + crafter.CraftingState.CraftingState, attestationStatus.PolicyEvaluations, bypassPolicyCheck || action.noPolicyGates) attestationResult.Digest, err = pushToControlPlane(ctx, action.CPConnection, bundle, workflow.GetWorkflowRunId(), workflow.GetVersion().GetMarkAsReleased()) if err != nil { @@ -360,9 +366,10 @@ func BlockingPolicies(evaluations map[string][]*PolicyEvaluation) []string { } } } + // A policy attached to several materials is one blocking policy sort.Strings(blocking) - return blocking + return slices.Compact(blocking) } func pushToControlPlane(ctx context.Context, conn *grpc.ClientConn, bundle *protobundle.Bundle, workflowRunID string, markVersionAsReleased bool) (string, error) { diff --git a/app/cli/pkg/action/runevents_test.go b/app/cli/pkg/action/runevents_test.go index 6583aa43d..371af1c81 100644 --- a/app/cli/pkg/action/runevents_test.go +++ b/app/cli/pkg/action/runevents_test.go @@ -52,6 +52,7 @@ const ( testBad = "bad" testAtt = "att" testCommit = "commit-1234" + testSBOMGate = "sbom-gate" ) const testRunID = "4f8d2b7e-8c1b-4b1e-9f3a-2a6f1b2c3d4e" @@ -234,10 +235,18 @@ func TestBlockingPolicies(t *testing.T) { { name: "gated policies with violations, sorted", evaluations: map[string][]*PolicyEvaluation{ - testSBOM: {{Name: "sbom-gate", Gate: true, Violations: violation}}, + testSBOM: {{Name: testSBOMGate, Gate: true, Violations: violation}}, testAtt: {{Name: testAttGate, Gate: true, Violations: violation}, {Name: "ok", Gate: true}}, }, - want: []string{testAttGate, "sbom-gate"}, + want: []string{testAttGate, testSBOMGate}, + }, + { + name: "same policy on two materials, once", + evaluations: map[string][]*PolicyEvaluation{ + testSBOM: {{Name: testSBOMGate, Gate: true, Violations: violation}}, + testImage: {{Name: testSBOMGate, Gate: true, Violations: violation}}, + }, + want: []string{testSBOMGate}, }, {name: "suppressed violations only", evaluations: map[string][]*PolicyEvaluation{testAtt: {{Name: testAttGate, Gate: true, Violations: suppressed}}}}, } diff --git a/app/cli/pkg/action/trace_attestation.go b/app/cli/pkg/action/trace_attestation.go index dbc3d754a..0b25d5f68 100644 --- a/app/cli/pkg/action/trace_attestation.go +++ b/app/cli/pkg/action/trace_attestation.go @@ -275,6 +275,8 @@ func (e *AttestationExecutor) Push(ctx context.Context) (*AttestationResult, err ConnectionInsecure: casInsecure(), CLIVersion: cliVersion, CLIDigest: cliDigest, + // Trace pushes do not enforce policy gates + NoPolicyGates: true, }) if err != nil { return nil, fmt.Errorf("create attestation push action: %w", err) diff --git a/app/cli/pkg/action/workflow_run_describe.go b/app/cli/pkg/action/workflow_run_describe.go index ae20d884e..663a65a66 100644 --- a/app/cli/pkg/action/workflow_run_describe.go +++ b/app/cli/pkg/action/workflow_run_describe.go @@ -547,7 +547,7 @@ 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,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 @@ -560,7 +560,7 @@ type RunEventMaterial struct { Value string `json:"value,omitempty"` Digest string `json:"digest,omitempty"` InContract bool `json:"in_contract"` - AddedByCollector bool `json:"added_by_collector,omitempty"` + AddedByCollector bool `json:"added_by_collector"` Policies *RunEventPolicyCount `json:"policies,omitempty"` } @@ -589,10 +589,12 @@ type RunProgress struct { } type RunProgressMaterial struct { - Name string `json:"name"` - Type string `json:"type"` - InContract bool `json:"in_contract"` - Required bool `json:"required"` + Name string `json:"name"` + Type string `json:"type"` + InContract bool `json:"in_contract"` + Required bool `json:"required"` + // a group of the contract needs at least one of its materials + Group string `json:"group,omitempty"` Provided bool `json:"provided"` Value string `json:"value,omitempty"` Policies *RunEventPolicyCount `json:"policies,omitempty"` @@ -739,15 +741,20 @@ func buildRunProgress(contractMaterials []*schemaapi.CraftingSchema_Material, ev } inContract := make(map[string]struct{}, len(contractMaterials)) + // Grouped materials are required at the group level, "at least one of", as attestation + // status shows them. So each group counts once, provided when any member is. + groupProvided := make(map[string]bool) for _, cm := range contractMaterials { inContract[cm.GetName()] = struct{}{} - // Grouped materials are required at the group level, as attestation status shows them m := &RunProgressMaterial{ Name: cm.GetName(), Type: cm.GetType().String(), InContract: true, - Required: !cm.GetOptional() && cm.GetGroup() == "", + Required: !cm.GetOptional() && cm.GetGroup() == "", Group: cm.GetGroup(), } fill(m) - if m.Required { + switch { + case m.Group != "": + groupProvided[m.Group] = groupProvided[m.Group] || m.Provided + case m.Required: progress.RequiredTotal++ if m.Provided { progress.RequiredProvided++ @@ -756,6 +763,13 @@ func buildRunProgress(contractMaterials []*schemaapi.CraftingSchema_Material, ev progress.Materials = append(progress.Materials, m) } + for _, provided := range groupProvided { + progress.RequiredTotal++ + if provided { + progress.RequiredProvided++ + } + } + for _, name := range order { if _, ok := inContract[name]; ok { continue diff --git a/app/cli/pkg/action/workflow_run_describe_test.go b/app/cli/pkg/action/workflow_run_describe_test.go index e0758964b..1ca94ae2b 100644 --- a/app/cli/pkg/action/workflow_run_describe_test.go +++ b/app/cli/pkg/action/workflow_run_describe_test.go @@ -269,6 +269,35 @@ func TestBuildRunProgress(t *testing.T) { } } +// A group counts once as required, and is provided when any member is +func TestBuildRunProgressGroups(t *testing.T) { + now := time.Now() + contract := []*schemaapi.CraftingSchema_Material{ + {Name: testImage, Type: schemaapi.CraftingSchema_Material_CONTAINER_IMAGE}, + {Name: "cdx", Type: schemaapi.CraftingSchema_Material_SBOM_CYCLONEDX_JSON, Group: testSBOM}, + {Name: "spdx", Type: schemaapi.CraftingSchema_Material_SBOM_SPDX_JSON, Group: testSBOM}, + } + + testCases := []struct { + name string + events []*RunEvent + wantProvided int + }{ + {name: "no member provided", wantProvided: 0}, + {name: "one member provided", events: []*RunEvent{materialRunEvent(now, "spdx", "succeeded", "")}, wantProvided: 1}, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + got := buildRunProgress(contract, tc.events, now) + assert.Equal(t, 2, got.RequiredTotal, "image, and the sbom group once") + assert.Equal(t, tc.wantProvided, got.RequiredProvided) + assert.Equal(t, testSBOM, got.Materials[1].Group) + assert.False(t, got.Materials[1].Required) + }) + } +} + // The attestation policy results come from the started event, then from the push event func TestBuildRunProgressAttestationPolicies(t *testing.T) { now := time.Now() 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/pkg/biz/workflowrun.go b/app/controlplane/pkg/biz/workflowrun.go index c4b042760..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 } @@ -291,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_test.go b/app/controlplane/pkg/biz/workflowrun_test.go index 5eccd90c5..d38f8fc9b 100644 --- a/app/controlplane/pkg/biz/workflowrun_test.go +++ b/app/controlplane/pkg/biz/workflowrun_test.go @@ -106,6 +106,17 @@ 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) diff --git a/app/controlplane/pkg/data/workflowrun.go b/app/controlplane/pkg/data/workflowrun.go index fffc6527d..e00b5d7bc 100644 --- a/app/controlplane/pkg/data/workflowrun.go +++ b/app/controlplane/pkg/data/workflowrun.go @@ -584,9 +584,9 @@ func (r *WorkflowRunRepo) Expire(ctx context.Context, id uuid.UUID) error { return fmt.Errorf("failed to find workflow run: %w", err) } - // A run that finished during the sweep keeps its status and its closing event + // 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 nil + return biz.NewErrFailedPreconditionStr("the workflow run is not in progress") } if err := tx.WorkflowRun.UpdateOne(run).SetState(biz.WorkflowRunExpired).ClearAttestationState().Exec(ctx); err != nil { diff --git a/app/controlplane/pkg/data/workflowrunevent_integration_test.go b/app/controlplane/pkg/data/workflowrunevent_integration_test.go index 4aa53e820..ea5bf5f48 100644 --- a/app/controlplane/pkg/data/workflowrunevent_integration_test.go +++ b/app/controlplane/pkg/data/workflowrunevent_integration_test.go @@ -333,7 +333,8 @@ func (s *workflowRunEventIntegrationTestSuite) TestExpireSkipsFinishedRun() { runID := s.newRun() s.Require().NoError(s.Repos.WorkflowRunRepo.MarkAsFinished(ctx, runID, biz.WorkflowRunSuccess, "")) - s.Require().NoError(s.Repos.WorkflowRunRepo.Expire(ctx, runID)) + 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) From 481dad5679e016160d13f7b96b22241048531237 Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Mon, 30 Nov 2026 22:18:56 +0100 Subject: [PATCH 08/20] feat(controlplane): bound the size of run event fields The key is at most 128 characters, each attribute string at most 256, and the policy name lists at most 100 names. The CLI recorder keeps the lists within the limit, and the counts stay complete. Refs #3825 (M1, R-008) Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1cdb3220-119c-4a14-ac50-52d5437ee4eb --- app/cli/pkg/action/runevents.go | 21 ++++ app/cli/pkg/action/runevents_test.go | 25 +++++ .../api/controlplane/v1/workflow_run.pb.go | 47 ++++---- .../api/controlplane/v1/workflow_run.proto | 33 ++++-- .../api/controlplane/v1/workflow_run_test.go | 101 ++++++++++++++++++ ...vent.AttestationAttributes.jsonschema.json | 8 ++ ...RunEvent.AttestationAttributes.schema.json | 8 ++ ...unEvent.MaterialAttributes.jsonschema.json | 4 + ...lowRunEvent.MaterialAttributes.schema.json | 4 + ...kflowRunEvent.PolicyCounts.jsonschema.json | 2 + ....WorkflowRunEvent.PolicyCounts.schema.json | 2 + ...lowRunEvent.PushAttributes.jsonschema.json | 2 + ...orkflowRunEvent.PushAttributes.schema.json | 2 + ...lplane.v1.WorkflowRunEvent.jsonschema.json | 1 + ...ntrolplane.v1.WorkflowRunEvent.schema.json | 1 + 15 files changed, 228 insertions(+), 33 deletions(-) create mode 100644 app/controlplane/api/controlplane/v1/workflow_run_test.go diff --git a/app/cli/pkg/action/runevents.go b/app/cli/pkg/action/runevents.go index ec3a97c34..5a076624c 100644 --- a/app/cli/pkg/action/runevents.go +++ b/app/cli/pkg/action/runevents.go @@ -43,6 +43,9 @@ const ( // 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 and PushAttributes in workflow_run.proto + runEventMaxPolicyNames = 100 runEventKeyPrefix = "chainloop." runEventKeyAttestation = runEventKeyPrefix + "attestation" @@ -96,6 +99,16 @@ func (r *runEventRecorder) Record(ctx context.Context, event *pb.WorkflowRunEven 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()) + } + if p := event.GetPush(); p != nil { + capPolicyNames(p.GetPolicies()) + if len(p.BlockingPolicies) > runEventMaxPolicyNames { + p.BlockingPolicies = p.BlockingPolicies[:runEventMaxPolicyNames] + } } ctx, cancel := context.WithTimeout(ctx, r.timeout) @@ -266,6 +279,14 @@ func displayValue(value string) string { 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 { diff --git a/app/cli/pkg/action/runevents_test.go b/app/cli/pkg/action/runevents_test.go index 371af1c81..d081eb2f5 100644 --- a/app/cli/pkg/action/runevents_test.go +++ b/app/cli/pkg/action/runevents_test.go @@ -221,6 +221,31 @@ func TestRunEventRecorderLimits(t *testing.T) { assert.Len(t, got[0].GetEvent().GetMaterial().GetValue(), 256) } +// 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_PUSH, Key: "chainloop.push", Status: pb.WorkflowRunEvent_STATUS_FAILED, + Attributes: &pb.WorkflowRunEvent_Push{Push: &pb.WorkflowRunEvent_PushAttributes{ + Policies: &pb.WorkflowRunEvent_PolicyCounts{Violated: 150, ViolatedPolicies: names}, + BlockingPolicies: names, + }}, + })) + + got := fake.received() + require.Len(t, got, 1) + push := got[0].GetEvent().GetPush() + assert.Len(t, push.GetBlockingPolicies(), 100) + assert.Len(t, push.GetPolicies().GetViolatedPolicies(), 100) + assert.Equal(t, int32(150), push.GetPolicies().GetViolated(), "the counts stay complete") +} + // The gate rule of the push: a gated policy with a violation that is not suppressed func TestBlockingPolicies(t *testing.T) { violation := []*PolicyViolation{{Message: testBad}} diff --git a/app/controlplane/api/controlplane/v1/workflow_run.pb.go b/app/controlplane/api/controlplane/v1/workflow_run.pb.go index e4436cc06..dae0659bd 100644 --- a/app/controlplane/api/controlplane/v1/workflow_run.pb.go +++ b/app/controlplane/api/controlplane/v1/workflow_run.pb.go @@ -2714,50 +2714,51 @@ const file_controlplane_v1_workflow_run_proto_rawDesc = "" + "\x0fworkflow_run_id\x18\x01 \x01(\tB\b\xbaH\x05r\x03\xb0\x01\x01R\rworkflowRunId\x121\n" + "\x0eafter_event_id\x18\x02 \x01(\tB\v\xbaH\b\xd8\x01\x01r\x03\xb0\x01\x01R\fafterEventId\"a\n" + "$WorkflowRunServiceListEventsResponse\x129\n" + - "\x06events\x18\x01 \x03(\v2!.controlplane.v1.WorkflowRunEventR\x06events\"\xb6\x0e\n" + + "\x06events\x18\x01 \x03(\v2!.controlplane.v1.WorkflowRunEventR\x06events\"\xa1\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\x19\n" + - "\x03key\x18\x05 \x01(\tB\a\xbaH\x04r\x02\x10\x01R\x03key\x12L\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\x12F\n" + - "\x04push\x18\f \x01(\v20.controlplane.v1.WorkflowRunEvent.PushAttributesH\x00R\x04push\x1a\xc9\x02\n" + - "\x15AttestationAttributes\x12#\n" + - "\rcontract_name\x18\x01 \x01(\tR\fcontractName\x12+\n" + - "\x11contract_revision\x18\x02 \x01(\x05R\x10contractRevision\x12\x1f\n" + - "\vrunner_type\x18\x03 \x01(\tR\n" + + "\x04push\x18\f \x01(\v20.controlplane.v1.WorkflowRunEvent.PushAttributesH\x00R\x04push\x1a\xf1\x02\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\x1f\n" + - "\vcli_version\x18\x05 \x01(\tR\n" + - "cliVersion\x12-\n" + - "\x12attestation_digest\x18\x06 \x01(\tR\x11attestationDigest\x12J\n" + - "\bpolicies\x18\a \x01(\v2..controlplane.v1.WorkflowRunEvent.PolicyCountsR\bpolicies\x1a\xa0\x02\n" + - "\x12MaterialAttributes\x12\x12\n" + - "\x04name\x18\x01 \x01(\tR\x04name\x12#\n" + - "\rmaterial_type\x18\x02 \x01(\tR\fmaterialType\x12\x1e\n" + - "\x05value\x18\x03 \x01(\tB\b\xbaH\x05r\x03\x18\x80\x02R\x05value\x12\x16\n" + - "\x06digest\x18\x04 \x01(\tR\x06digest\x12\x1f\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\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\x89\x01\n" + + "\bpolicies\x18\a \x01(\v2..controlplane.v1.WorkflowRunEvent.PolicyCountsR\bpolicies\x1a\x9a\x01\n" + "\x0ePushAttributes\x12J\n" + - "\bpolicies\x18\x01 \x01(\v2..controlplane.v1.WorkflowRunEvent.PolicyCountsR\bpolicies\x12+\n" + - "\x11blocking_policies\x18\x02 \x03(\tR\x10blockingPolicies\x1a\xa7\x01\n" + + "\bpolicies\x18\x01 \x01(\v2..controlplane.v1.WorkflowRunEvent.PolicyCountsR\bpolicies\x12<\n" + + "\x11blocking_policies\x18\x02 \x03(\tB\x0f\xbaH\f\x92\x01\t\x10d\"\x05r\x03\x18\x80\x02R\x10blockingPolicies\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(\tR\x10violatedPolicies\"J\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" + diff --git a/app/controlplane/api/controlplane/v1/workflow_run.proto b/app/controlplane/api/controlplane/v1/workflow_run.proto index 9c345768a..626eba36d 100644 --- a/app/controlplane/api/controlplane/v1/workflow_run.proto +++ b/app/controlplane/api/controlplane/v1/workflow_run.proto @@ -242,7 +242,10 @@ message WorkflowRunEvent { defined_only: true }]; // Events with the same key are one step of the timeline - string key = 5 [(buf.validate.field).string.min_len = 1]; + 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 @@ -277,22 +280,22 @@ message WorkflowRunEvent { } message AttestationAttributes { - string contract_name = 1; + string contract_name = 1 [(buf.validate.field).string.max_len = 256]; int32 contract_revision = 2; - string runner_type = 3; + string runner_type = 3 [(buf.validate.field).string.max_len = 256]; bool remote_state = 4; - string cli_version = 5; - string attestation_digest = 6; + 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; } message MaterialAttributes { - string name = 1; - string material_type = 2; + 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; + string digest = 4 [(buf.validate.field).string.max_len = 256]; bool in_contract = 5; bool added_by_collector = 6; PolicyCounts policies = 7; @@ -302,7 +305,12 @@ message WorkflowRunEvent { // results of the attestation policies evaluated at push PolicyCounts policies = 1; // gated policies with violations that block the push - repeated string blocking_policies = 2; + repeated string blocking_policies = 2 [(buf.validate.field).repeated = { + max_items: 100 + items: { + string: {max_len: 256} + } + }]; } message PolicyCounts { @@ -310,7 +318,12 @@ message WorkflowRunEvent { int32 passed = 2; int32 violated = 3; int32 skipped = 4; - repeated string violated_policies = 5; + repeated string violated_policies = 5 [(buf.validate.field).repeated = { + max_items: 100 + items: { + string: {max_len: 256} + } + }]; } } 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..177d41cd4 --- /dev/null +++ b/app/controlplane/api/controlplane/v1/workflow_run_test.go @@ -0,0 +1,101 @@ +// +// 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, + }, + { + desc: "over 100 blocking policies", + mutate: func(ev *v1.WorkflowRunEvent) { + ev.Type = v1.WorkflowRunEvent_TYPE_PUSH + ev.Attributes = &v1.WorkflowRunEvent_Push{Push: &v1.WorkflowRunEvent_PushAttributes{BlockingPolicies: 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/jsonschema/controlplane.v1.WorkflowRunEvent.AttestationAttributes.jsonschema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.AttestationAttributes.jsonschema.json index e3baaea54..3e3126a61 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.AttestationAttributes.jsonschema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.AttestationAttributes.jsonschema.json @@ -4,12 +4,15 @@ "additionalProperties": false, "patternProperties": { "^(attestation_digest)$": { + "maxLength": 256, "type": "string" }, "^(cli_version)$": { + "maxLength": 256, "type": "string" }, "^(contract_name)$": { + "maxLength": 256, "type": "string" }, "^(contract_revision)$": { @@ -21,17 +24,21 @@ "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": { @@ -47,6 +54,7 @@ "type": "boolean" }, "runnerType": { + "maxLength": 256, "type": "string" } }, 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 index d05f6633f..a18146e3b 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.AttestationAttributes.schema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.AttestationAttributes.schema.json @@ -4,12 +4,15 @@ "additionalProperties": false, "patternProperties": { "^(attestationDigest)$": { + "maxLength": 256, "type": "string" }, "^(cliVersion)$": { + "maxLength": 256, "type": "string" }, "^(contractName)$": { + "maxLength": 256, "type": "string" }, "^(contractRevision)$": { @@ -21,17 +24,21 @@ "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": { @@ -47,6 +54,7 @@ "type": "boolean" }, "runner_type": { + "maxLength": 256, "type": "string" } }, 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 index 64c8c0f9b..3ff751bbb 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.MaterialAttributes.jsonschema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.MaterialAttributes.jsonschema.json @@ -10,6 +10,7 @@ "type": "boolean" }, "^(material_type)$": { + "maxLength": 256, "type": "string" } }, @@ -18,15 +19,18 @@ "type": "boolean" }, "digest": { + "maxLength": 256, "type": "string" }, "inContract": { "type": "boolean" }, "materialType": { + "maxLength": 256, "type": "string" }, "name": { + "maxLength": 256, "type": "string" }, "policies": { 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 index a81a878e6..eb4562d1e 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.MaterialAttributes.schema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.MaterialAttributes.schema.json @@ -10,6 +10,7 @@ "type": "boolean" }, "^(materialType)$": { + "maxLength": 256, "type": "string" } }, @@ -18,15 +19,18 @@ "type": "boolean" }, "digest": { + "maxLength": 256, "type": "string" }, "in_contract": { "type": "boolean" }, "material_type": { + "maxLength": 256, "type": "string" }, "name": { + "maxLength": 256, "type": "string" }, "policies": { 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 index 7a1b2bd48..cefc1f7d8 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PolicyCounts.jsonschema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PolicyCounts.jsonschema.json @@ -5,6 +5,7 @@ "patternProperties": { "^(violated_policies)$": { "items": { + "maxLength": 256, "type": "string" }, "type": "array" @@ -33,6 +34,7 @@ }, "violatedPolicies": { "items": { + "maxLength": 256, "type": "string" }, "type": "array" 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 index fdd81c1d5..f2efede98 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PolicyCounts.schema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PolicyCounts.schema.json @@ -5,6 +5,7 @@ "patternProperties": { "^(violatedPolicies)$": { "items": { + "maxLength": 256, "type": "string" }, "type": "array" @@ -33,6 +34,7 @@ }, "violated_policies": { "items": { + "maxLength": 256, "type": "string" }, "type": "array" diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PushAttributes.jsonschema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PushAttributes.jsonschema.json index 017922583..99a74d48d 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PushAttributes.jsonschema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PushAttributes.jsonschema.json @@ -6,6 +6,7 @@ "^(blocking_policies)$": { "description": "gated policies with violations that block the push", "items": { + "maxLength": 256, "type": "string" }, "type": "array" @@ -15,6 +16,7 @@ "blockingPolicies": { "description": "gated policies with violations that block the push", "items": { + "maxLength": 256, "type": "string" }, "type": "array" diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PushAttributes.schema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PushAttributes.schema.json index f5b822ea3..68a5edbd7 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PushAttributes.schema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PushAttributes.schema.json @@ -6,6 +6,7 @@ "^(blockingPolicies)$": { "description": "gated policies with violations that block the push", "items": { + "maxLength": 256, "type": "string" }, "type": "array" @@ -15,6 +16,7 @@ "blocking_policies": { "description": "gated policies with violations that block the push", "items": { + "maxLength": 256, "type": "string" }, "type": "array" diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.jsonschema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.jsonschema.json index b8a1dbd15..d43b80e84 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.jsonschema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.jsonschema.json @@ -22,6 +22,7 @@ }, "key": { "description": "Events with the same key are one step of the timeline", + "maxLength": 128, "minLength": 1, "type": "string" }, diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.schema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.schema.json index 721f0fe92..5187d53f1 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.schema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.schema.json @@ -22,6 +22,7 @@ }, "key": { "description": "Events with the same key are one step of the timeline", + "maxLength": 128, "minLength": 1, "type": "string" }, From e52da9b410cca381fac09207e617530877dd1e40 Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Mon, 30 Nov 2026 22:25:25 +0100 Subject: [PATCH 09/20] feat(cli): record one summary event for a large archive add An add that expands an archive into more than 20 materials records one event for the archive, with the sum of the policy counts, instead of one event for each material. So a large archive does not use up the events of the run. Refs #3825 (M1, R-001) Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1cdb3220-119c-4a14-ac50-52d5437ee4eb --- app/cli/pkg/action/attestation_add.go | 6 ++++ app/cli/pkg/action/runevents.go | 48 +++++++++++++++++++++++++++ app/cli/pkg/action/runevents_test.go | 45 +++++++++++++++++++++++++ 3 files changed, 99 insertions(+) diff --git a/app/cli/pkg/action/attestation_add.go b/app/cli/pkg/action/attestation_add.go index e40abc497..1defb9505 100644 --- a/app/cli/pkg/action/attestation_add.go +++ b/app/cli/pkg/action/attestation_add.go @@ -155,6 +155,12 @@ func (action *AttestationAdd) Run(ctx context.Context, attestationID, materialNa return nil, err } + // A large archive records one summary event, so that it does not use up the events of the run + if len(results) > runEventMaxArchiveMaterials { + _ = events.Record(ctx, archiveAddedEvent(crafter, materialName, materialType, materialValue, results)) + return results, nil + } + for _, r := range results { _ = events.Record(ctx, materialAddedEvent(crafter, r, false)) } diff --git a/app/cli/pkg/action/runevents.go b/app/cli/pkg/action/runevents.go index 5a076624c..6db5eebfe 100644 --- a/app/cli/pkg/action/runevents.go +++ b/app/cli/pkg/action/runevents.go @@ -17,8 +17,10 @@ package action import ( "context" + "fmt" "os" "path/filepath" + "slices" "strconv" "strings" "time" @@ -46,6 +48,9 @@ const ( // runEventMaxPolicyNames is the limit of the control plane for a list of policy names, // see the max_items rules of PolicyCounts and PushAttributes in workflow_run.proto runEventMaxPolicyNames = 100 + // 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" @@ -220,6 +225,49 @@ func materialFailedEvent(c *crafter.Crafter, name, materialType, value string, a } } +// 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, + }}, + } +} + // 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() diff --git a/app/cli/pkg/action/runevents_test.go b/app/cli/pkg/action/runevents_test.go index d081eb2f5..b297c1972 100644 --- a/app/cli/pkg/action/runevents_test.go +++ b/app/cli/pkg/action/runevents_test.go @@ -17,6 +17,7 @@ package action import ( "context" + "fmt" "net" "path/filepath" "strings" @@ -53,6 +54,7 @@ const ( testAtt = "att" testCommit = "commit-1234" testSBOMGate = "sbom-gate" + testLicenses = "cdx-licenses" ) const testRunID = "4f8d2b7e-8c1b-4b1e-9f3a-2a6f1b2c3d4e" @@ -221,6 +223,49 @@ func TestRunEventRecorderLimits(t *testing.T) { assert.Len(t, got[0].GetEvent().GetMaterial().GetValue(), 256) } +// 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: "sboms", wantKey: "chainloop.material.sboms"}, + {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) From 08ac78ca2ed916802de2faa06027f1488b3b810b Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Mon, 30 Nov 2026 22:44:18 +0100 Subject: [PATCH 10/20] feat(cli): record the evidence material of an archive add An add that expands an archive also stores the archive itself as an EVIDENCE material. It now records an event for it, after the events of the expanded materials or after the summary event. Refs #3825 (M1, R-001) Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1cdb3220-119c-4a14-ac50-52d5437ee4eb --- app/cli/pkg/action/attestation_add.go | 25 ++++++++--- app/cli/pkg/action/runevents.go | 33 ++++++++++++++ app/cli/pkg/action/runevents_test.go | 63 +++++++++++++++++++++++++++ 3 files changed, 114 insertions(+), 7 deletions(-) diff --git a/app/cli/pkg/action/attestation_add.go b/app/cli/pkg/action/attestation_add.go index 1defb9505..c3dea5fb8 100644 --- a/app/cli/pkg/action/attestation_add.go +++ b/app/cli/pkg/action/attestation_add.go @@ -155,17 +155,28 @@ func (action *AttestationAdd) Run(ctx context.Context, attestationID, materialNa return nil, err } - // A large archive records one summary event, so that it does not use up the events of the run + 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(crafter, materialName, materialType, materialValue, results)) - return results, nil + _ = events.Record(ctx, archiveAddedEvent(c, materialName, materialType, materialValue, results)) + } else { + for _, r := range results { + _ = events.Record(ctx, materialAddedEvent(c, r, false)) + } } - for _, r := range results { - _ = events.Record(ctx, materialAddedEvent(crafter, 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)) + } } - - return results, nil } // addMaterial adds the material, or the materials of an archive, to the loaded crafting state diff --git a/app/cli/pkg/action/runevents.go b/app/cli/pkg/action/runevents.go index 6db5eebfe..9cf5c8ceb 100644 --- a/app/cli/pkg/action/runevents.go +++ b/app/cli/pkg/action/runevents.go @@ -27,8 +27,10 @@ import ( "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" @@ -268,6 +270,37 @@ func archiveAddedEvent(c *crafter.Crafter, name, materialType, archivePath strin } } +// 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() diff --git a/app/cli/pkg/action/runevents_test.go b/app/cli/pkg/action/runevents_test.go index b297c1972..4b2d7cca8 100644 --- a/app/cli/pkg/action/runevents_test.go +++ b/app/cli/pkg/action/runevents_test.go @@ -19,6 +19,7 @@ import ( "context" "fmt" "net" + "os" "path/filepath" "strings" "sync" @@ -223,6 +224,68 @@ func TestRunEventRecorderLimits(t *testing.T) { 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(), "", "sboms", 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{}) From 63baecf4e7b90ac1958ed1a0a8f0be002993101c Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Mon, 30 Nov 2026 23:00:20 +0100 Subject: [PATCH 11/20] feat(cli): show the run timeline as a tree in workflow run describe The timeline is one tree: the root line has the start and the end of the attestation, and each step is one line. A step with more than one event, such as a failed then repeated add, folds its events below it. For a run in progress, the tree also shows each contract material that is missing and the push that is still to come, so it replaces the materials table. Refs #3825 (M1, R-004) Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1cdb3220-119c-4a14-ac50-52d5437ee4eb --- app/cli/cmd/workflow_run_timeline.go | 294 ++++++++++++++++++ app/cli/cmd/workflow_run_timeline_test.go | 120 +++++++ app/cli/cmd/workflow_workflow_run_describe.go | 87 +----- 3 files changed, 418 insertions(+), 83 deletions(-) create mode 100644 app/cli/cmd/workflow_run_timeline.go create mode 100644 app/cli/cmd/workflow_run_timeline_test.go diff --git a/app/cli/cmd/workflow_run_timeline.go b/app/cli/cmd/workflow_run_timeline.go new file mode 100644 index 000000000..1acb68507 --- /dev/null +++ b/app/cli/cmd/workflow_run_timeline.go @@ -0,0 +1,294 @@ +// +// 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" + "strings" + "time" + "unicode/utf8" + + "github.com/chainloop-dev/chainloop/app/cli/pkg/action" + "github.com/jedib0t/go-pretty/v6/text" +) + +const ( + timelineKeyAttestation = "chainloop.attestation" + timelineKeyPush = "chainloop.push" + // timelineMaxDetail keeps each line of the tree readable. JSON output has the full text. + timelineMaxDetail = 120 + + timelineFailed = "failed" +) + +// 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. +func renderRunTimeline(w io.Writer, events []*action.RunEvent, progress *action.RunProgress, now time.Time) { + if len(events) == 0 { + 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 closing *action.RunEvent + reported := make(map[string]bool) + for _, key := range keys { + evs := groups[key] + if key == timelineKeyAttestation { + // the start is in the header, and the closing event is the last line + if last := evs[len(evs)-1]; last.Status != "started" { + closing = last + } + continue + } + + 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.InContract && !reported[m.Name] { + nodes = append(nodes, &timelineNode{ + symbol: text.Faint.Sprint("○"), name: m.Name, + details: []string{timelineRequirement(m), text.FgHiRed.Sprint("missing")}, + }) + } + } + if _, pushed := groups[timelineKeyPush]; !pushed && closing == nil { + nodes = append(nodes, &timelineNode{symbol: text.FgYellow.Sprint("●"), name: "waiting for push"}) + } + } + + if closing != nil { + nodes = append(nodes, timelineClosing(closing)) + } + + fmt.Fprintln(w, timelineHeader(groups[timelineKeyAttestation], 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(attestation, 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 + for _, e := range attestation { + if e.Status == "started" { + start = e.CreatedAt + break + } + } + + 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, " · ") +} + +// timelineStep is the line of one step. 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] + node := &timelineNode{at: timelineTime(evs[0].CreatedAt), symbol: timelineSymbol(last.Status), name: action.RunStepName(key)} + + if m := materials[node.name]; m != nil { + node.details = append(node.details, timelineRequirement(m)) + } + + switch { + case last.Material != nil: + if s := runPolicyCountSummary(last.Material.Policies); s != "" { + node.details = append(node.details, s) + } + case last.Push != nil: + if s := runPolicyCountSummary(last.Push.Policies); s != "" { + node.details = append(node.details, s) + } + if len(last.Push.BlockingPolicies) > 0 { + node.details = append(node.details, text.FgHiRed.Sprint("blocked by: "+strings.Join(last.Push.BlockingPolicies, ", "))) + } + } + + if len(evs) == 1 { + // the blocked push already shows its gates + if last.Message != "" && last.Push == nil { + 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)}) + } + if failed > 0 { + node.details = append(node.details, fmt.Sprintf("%d failed", failed)) + } + + return node +} + +// timelineClosing is the last line: how the control plane closed the attestation +func timelineClosing(e *action.RunEvent) *timelineNode { + node := &timelineNode{at: timelineTime(e.CreatedAt), symbol: timelineSymbol(e.Status), name: "attestation " + timelineStatus(e.Status)} + if a := e.Attestation; a != nil && a.AttestationDigest != "" { + node.details = append(node.details, a.AttestationDigest) + } + if e.Message != "" { + node.details = append(node.details, timelineMessage(e)) + } + return node +} + +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 { + case !m.InContract: + return "not in contract" + case m.Group != "": + return "one of " + m.Group + case m.Required: + return "required" + default: + return "optional" + } +} + +func timelineSymbol(status string) string { + switch status { + case "succeeded": + 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 == "succeeded" { + 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..8ba7bcb12 --- /dev/null +++ b/app/cli/cmd/workflow_run_timeline_test.go @@ -0,0 +1,120 @@ +// +// 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), Key: timelineKeyAttestation, Status: "started", Attestation: &action.RunEventAttestation{}} + material := func(d time.Duration, name, status, msg string, policies *action.RunEventPolicyCount) *action.RunEvent { + return &action.RunEvent{CreatedAt: at(d), 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 + 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", InContract: true, Required: true, Provided: true}, + {Name: "image", InContract: true, Required: true}, + {Name: "sast-report", InContract: true, Provided: true}, + {Name: "build-log", Provided: true}, + }, + }, + want: `Timeline (reported progress) · started 10:00:02 · running for 5m43s · 1 of 2 required provided · attestation policies: 2 passed +├─ 10:02:21 ✓ sast-report optional · 1 passed, 1 violated +├─ 10:03:10 ✓ sbom required · 2 passed · 1 failed +│ ├─ 10:03:10 ✗ invalid CycloneDX document: missing bomFormat +│ └─ 10:04:05 ✓ succeeded +├─ 10:05:30 ✓ build-log not in contract +├─ ○ image required · missing +└─ ● waiting for push +`, + }, + { + name: "finished run", + events: []*action.RunEvent{ + started, + material(451*time.Second, "vulnerability-report", "succeeded", "", nil), + {CreatedAt: at(500 * time.Second), Key: "chainloop.push", Status: "succeeded", Push: &action.RunEventPush{Policies: &action.RunEventPolicyCount{Evaluated: 1, Passed: 1}}}, + {CreatedAt: at(501 * time.Second), Key: timelineKeyAttestation, Status: "succeeded", Attestation: &action.RunEventAttestation{AttestationDigest: "sha256:4de7"}}, + }, + want: `Timeline · started 10:00:02 · finished 10:08:23 (8m21s) · stored +├─ 10:07:33 ✓ vulnerability-report +├─ 10:08:22 ✓ push 1 passed +└─ 10:08:23 ✓ attestation stored sha256:4de7 +`, + }, + { + name: "blocked push, then expired", + events: []*action.RunEvent{ + started, + {CreatedAt: at(60 * time.Second), Key: "chainloop.push", Status: "failed", Message: "blocked by policy gates: sast-no-critical", + Push: &action.RunEventPush{Policies: &action.RunEventPolicyCount{Evaluated: 1, Violated: 1}, BlockingPolicies: []string{"sast-no-critical"}}}, + {CreatedAt: at(3600 * time.Second), Key: timelineKeyAttestation, Status: "failed", Message: "expired"}, + }, + want: `Timeline · started 10:00:02 · finished 11:00:02 (1h0m0s) · failed +├─ 10:01:02 ✗ push 1 violated · blocked by: sast-no-critical +└─ 11:00:02 ✗ attestation failed expired +`, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + var buf bytes.Buffer + renderRunTimeline(&buf, tc.events, tc.progress, start.Add(343*time.Second)) + assert.Equal(t, tc.want, buf.String()) + }) + } +} + +func TestRenderRunTimelineNoEvents(t *testing.T) { + var buf bytes.Buffer + renderRunTimeline(&buf, nil, nil, time.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 a14e68b50..3b438d881 100644 --- a/app/cli/cmd/workflow_workflow_run_describe.go +++ b/app/cli/cmd/workflow_workflow_run_describe.go @@ -135,15 +135,14 @@ func workflowRunDescribeTableOutput(run *action.WorkflowRunItemFull) error { gt.AppendRow(table.Row{"Runner Link", wr.RunURL}) if run.Progress != nil { - gt.AppendRow(table.Row{"Running for", time.Since(*wr.CreatedAt).Round(time.Second).String()}) gt.Render() - runProgressTables(run.Progress, run.Events) + renderRunTimeline(os.Stdout, run.Events, run.Progress, time.Now()) return nil } if run.WorkflowRun.FinishedAt == nil { gt.Render() - runTimelineTable(run.Events, nil) + renderRunTimeline(os.Stdout, run.Events, nil, time.Now()) logger.Info().Msg("the attestation crafting process is in progress, it has not been received yet") return nil } @@ -151,7 +150,7 @@ func workflowRunDescribeTableOutput(run *action.WorkflowRunItemFull) error { att := run.Attestation if att == nil { gt.Render() - runTimelineTable(run.Events, nil) + renderRunTimeline(os.Stdout, run.Events, nil, time.Now()) logger.Warn().Msg("there was an issue retrieving the attestation") return nil } @@ -185,89 +184,11 @@ func workflowRunDescribeTableOutput(run *action.WorkflowRunItemFull) error { predicateV1Table(att) // The timeline is history: the signed attestation above is the source of truth - runTimelineTable(run.Events, nil) + renderRunTimeline(os.Stdout, run.Events, nil, time.Now()) logger.Info().Msg("you can use the flag \"--output statement\" to see the full in-toto statement") return nil } -// runProgressTables shows the reported progress of a run in progress -func runProgressTables(progress *action.RunProgress, events []*action.RunEvent) { - mt := output.NewTableWriter() - mt.SetTitle(fmt.Sprintf("Materials (reported progress) %d of %d required provided", progress.RequiredProvided, progress.RequiredTotal)) - for _, m := range progress.Materials { - requirement := "optional" - switch { - case !m.InContract: - requirement = "not in contract" - case m.Group != "": - requirement = "one of " + m.Group - case m.Required: - requirement = "required" - } - - state := text.FgHiRed.Sprint("missing") - if m.Provided { - state = text.FgHiGreen.Sprint("provided") - } - - var notes []string - if s := runPolicyCountSummary(m.Policies); s != "" { - notes = append(notes, s) - } - if m.FailedAdds > 0 { - notes = append(notes, fmt.Sprintf("(%d failed add)", m.FailedAdds)) - } - if m.Error != "" { - notes = append(notes, m.Error) - } - - mt.AppendRow(table.Row{m.Name, m.Type, requirement, state, wrap.String(strings.Join(notes, " "), 80)}) - } - mt.Render() - - if s := runPolicyCountSummary(progress.AttestationPolicies); s != "" { - pt := output.NewTableWriter() - pt.AppendRow(table.Row{"Policies (reported progress)", "attestation: " + s}) - pt.Render() - } - - runTimelineTable(events, progress.Steps) -} - -// runTimelineTable shows the events of a run in order. The duration of a step shows on its first event. -func runTimelineTable(events []*action.RunEvent, steps []*action.RunProgressStep) { - if len(events) == 0 { - return - } - - durations := make(map[string]time.Duration, len(steps)) - for _, s := range steps { - durations[s.Key] = s.Duration - } - - tt := output.NewTableWriter() - tt.SetTitle("Timeline") - seen := make(map[string]bool) - for _, e := range events { - var at, duration string - if e.CreatedAt != nil { - at = e.CreatedAt.Local().Format(time.TimeOnly) - } - if !seen[e.Key] && durations[e.Key] > 0 { - duration = durations[e.Key].Round(time.Second).String() - } - seen[e.Key] = true - - status := e.Status - if status == "failed" { - status = text.FgHiRed.Sprint(status) - } - - tt.AppendRow(table.Row{at, action.RunStepName(e.Key), status, duration, wrap.String(e.Message, 80)}) - } - tt.Render() -} - // 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 { From c5d1de367dfa2b3e406a66b36023d10b3bf562b5 Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Mon, 30 Nov 2026 23:29:55 +0100 Subject: [PATCH 12/20] feat: record the push in the closing event of the store The CLI no longer records a separate push event. When the control plane stores an attestation, it reads the attestation policy results and the gated policies with violations from the stored predicate, and puts them on the closing event of the run, in the same transaction as the status change. workflow run describe shows the timeline end as one "pushed and stored" line with the policy results, the blocking gates, and the short digest. The API drops the push event type and its attributes (numbers reserved) and adds blocking_policies to the attestation attributes. Supersedes R-001 and R-006 of spec issue-3825 with R-010 and R-011, and records the reason as D-011. Refs #3825 Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1cdb3220-119c-4a14-ac50-52d5437ee4eb --- app/cli/cmd/workflow_run_timeline.go | 178 ++++++++--- app/cli/cmd/workflow_run_timeline_test.go | 58 ++-- app/cli/pkg/action/attestation_push.go | 22 -- app/cli/pkg/action/runevents.go | 30 +- app/cli/pkg/action/runevents_test.go | 93 +----- app/cli/pkg/action/trace_attestation.go | 2 - app/cli/pkg/action/workflow_run_describe.go | 22 +- .../pkg/action/workflow_run_describe_test.go | 12 +- .../api/controlplane/v1/workflow_run.pb.go | 282 +++++++----------- .../api/controlplane/v1/workflow_run.proto | 29 +- .../api/controlplane/v1/workflow_run_test.go | 4 +- .../frontend/controlplane/v1/workflow_run.ts | 143 ++------- ...vent.AttestationAttributes.jsonschema.json | 18 +- ...RunEvent.AttestationAttributes.schema.json | 18 +- ...lowRunEvent.PushAttributes.jsonschema.json | 31 -- ...orkflowRunEvent.PushAttributes.schema.json | 31 -- ...lplane.v1.WorkflowRunEvent.jsonschema.json | 6 +- ...ntrolplane.v1.WorkflowRunEvent.schema.json | 6 +- .../internal/service/attestation.go | 9 +- .../internal/service/workflowrun.go | 16 +- .../workflowrunevent_integration_test.go | 2 +- .../pkg/biz/mocks/WorkflowRunRepo.go | 55 ++-- app/controlplane/pkg/biz/workflowrun.go | 24 +- app/controlplane/pkg/biz/workflowrun_test.go | 2 +- app/controlplane/pkg/biz/workflowrunevent.go | 102 +++++-- .../pkg/biz/workflowrunevent_test.go | 85 +++++- app/controlplane/pkg/data/workflowrun.go | 10 +- .../data/workflowrunevent_integration_test.go | 24 +- .../issue-3825-attestation-progress-events.md | 31 +- .../issue-3825-attestation-progress-events.md | 59 ++-- 30 files changed, 683 insertions(+), 721 deletions(-) delete mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PushAttributes.jsonschema.json delete mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PushAttributes.schema.json diff --git a/app/cli/cmd/workflow_run_timeline.go b/app/cli/cmd/workflow_run_timeline.go index 1acb68507..a96d0a123 100644 --- a/app/cli/cmd/workflow_run_timeline.go +++ b/app/cli/cmd/workflow_run_timeline.go @@ -28,7 +28,6 @@ import ( const ( timelineKeyAttestation = "chainloop.attestation" - timelineKeyPush = "chainloop.push" // timelineMaxDetail keeps each line of the tree readable. JSON output has the full text. timelineMaxDetail = 120 @@ -47,7 +46,8 @@ type timelineNode struct { // 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. +// that are still missing, and the push that is still to come. The closing event of the +// control plane is the last line. func renderRunTimeline(w io.Writer, events []*action.RunEvent, progress *action.RunProgress, now time.Time) { if len(events) == 0 { return @@ -75,36 +75,39 @@ func renderRunTimeline(w io.Writer, events []*action.RunEvent, progress *action. reported := make(map[string]bool) for _, key := range keys { evs := groups[key] - if key == timelineKeyAttestation { - // the start is in the header, and the closing event is the last line + switch key { + case timelineKeyAttestation: + for _, e := range evs { + if e.Status == "started" { + nodes = append(nodes, timelineInit(e)) + break + } + } + // the closing event of the control plane ends the timeline if last := evs[len(evs)-1]; last.Status != "started" { closing = last } - continue - } - - if m := evs[len(evs)-1].Material; m != nil { - reported[m.Name] = true + default: + if m := evs[len(evs)-1].Material; m != nil { + reported[m.Name] = true + } + nodes = append(nodes, timelineStep(key, evs, materials)) } - nodes = append(nodes, timelineStep(key, evs, materials)) } if progress != nil { for _, m := range progress.Materials { if m.InContract && !reported[m.Name] { nodes = append(nodes, &timelineNode{ - symbol: text.Faint.Sprint("○"), name: m.Name, - details: []string{timelineRequirement(m), text.FgHiRed.Sprint("missing")}, + symbol: text.Faint.Sprint("○"), name: "missing evidence " + timelineQuote(m.Name), + details: []string{timelineRequirement(m)}, }) } } - if _, pushed := groups[timelineKeyPush]; !pushed && closing == nil { - nodes = append(nodes, &timelineNode{symbol: text.FgYellow.Sprint("●"), name: "waiting for push"}) - } } - if closing != nil { - nodes = append(nodes, timelineClosing(closing)) + if end := timelineEnd(closing, progress != nil); end != nil { + nodes = append(nodes, end) } fmt.Fprintln(w, timelineHeader(groups[timelineKeyAttestation], events, closing, progress, now)) @@ -152,32 +155,110 @@ func timelineHeader(attestation, events []*action.RunEvent, closing *action.RunE return strings.Join(parts, " · ") } -// timelineStep is the line of one step. 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] - node := &timelineNode{at: timelineTime(evs[0].CreatedAt), symbol: timelineSymbol(last.Status), name: action.RunStepName(key)} +// 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("succeeded"), name: "initialized"} + a := e.Attestation + if a == nil { + return node + } - if m := materials[node.name]; m != nil { - node.details = append(node.details, timelineRequirement(m)) + 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 results of the stored attestation and its digest. A run that ends with no store +// (reset or expiry) shows how it ended. +func timelineEnd(closing *action.RunEvent, inProgress bool) *timelineNode { switch { - case last.Material != nil: - if s := runPolicyCountSummary(last.Material.Policies); s != "" { - node.details = append(node.details, s) + case closing == nil && inProgress: + return &timelineNode{symbol: timelineSymbol("started"), name: "waiting for push"} + case closing == nil: + return nil + } + + node := &timelineNode{at: timelineTime(closing.CreatedAt), symbol: timelineSymbol(closing.Status), name: timelineStatus(closing.Status)} + if closing.Status == "succeeded" { + node.name = "pushed and stored" + if a := closing.Attestation; a != nil { + if s := runPolicyCountSummary(a.Policies); s != "" { + node.details = append(node.details, "policies: "+s) + } + // a blocked attestation is stored too, and the push command fails after it + if len(a.BlockingPolicies) > 0 { + node.details = append(node.details, text.FgHiRed.Sprint("blocked by: "+strings.Join(a.BlockingPolicies, ", "))) + } } - case last.Push != nil: - if s := runPolicyCountSummary(last.Push.Policies); s != "" { - node.details = append(node.details, s) + } + if d := timelineDigest(closing); d != "" { + node.details = append(node.details, d) + } + if closing.Message != "" { + node.details = append(node.details, timelineMessage(closing)) + } + + return node +} + +// 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] + name := action.RunStepName(key) + node := &timelineNode{at: timelineTime(evs[0].CreatedAt), symbol: timelineSymbol(last.Status), name: timelineEvidenceAction(last, name)} + + if m := last.Material; m != nil { + if m.MaterialType != "" { + node.details = append(node.details, m.MaterialType) + } + if m.Value != "" { + node.details = append(node.details, m.Value) } - if len(last.Push.BlockingPolicies) > 0 { - node.details = append(node.details, text.FgHiRed.Sprint("blocked by: "+strings.Join(last.Push.BlockingPolicies, ", "))) + } + if m := materials[name]; m != nil { + node.details = append(node.details, timelineRequirement(m)) + } + if m := last.Material; m != nil { + if s := runPolicyCountSummary(m.Policies); s != "" { + node.details = append(node.details, "policies: "+s) } } if len(evs) == 1 { - // the blocked push already shows its gates - if last.Message != "" && last.Push == nil { + if last.Message != "" { node.details = append(node.details, timelineMessage(last)) } return node @@ -190,23 +271,34 @@ func timelineStep(key string, evs []*action.RunEvent, materials map[string]*acti } node.children = append(node.children, &timelineNode{at: timelineTime(e.CreatedAt), symbol: timelineSymbol(e.Status), name: timelineMessage(e)}) } - if failed > 0 { - node.details = append(node.details, fmt.Sprintf("%d failed", failed)) + 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 } -// timelineClosing is the last line: how the control plane closed the attestation -func timelineClosing(e *action.RunEvent) *timelineNode { - node := &timelineNode{at: timelineTime(e.CreatedAt), symbol: timelineSymbol(e.Status), name: "attestation " + timelineStatus(e.Status)} - if a := e.Attestation; a != nil && a.AttestationDigest != "" { - node.details = append(node.details, a.AttestationDigest) +// 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 } - if e.Message != "" { - node.details = append(node.details, timelineMessage(e)) +} + +func timelineQuote(name string) string { + if name == "" { + return "(no name)" } - return node + return "`" + name + "`" } func writeTimelineNodes(w io.Writer, nodes []*timelineNode, prefix string, nameWidth int) { diff --git a/app/cli/cmd/workflow_run_timeline_test.go b/app/cli/cmd/workflow_run_timeline_test.go index 8ba7bcb12..56c1cb594 100644 --- a/app/cli/cmd/workflow_run_timeline_test.go +++ b/app/cli/cmd/workflow_run_timeline_test.go @@ -34,7 +34,8 @@ func TestRenderRunTimeline(t *testing.T) { v := start.Add(d) return &v } - started := &action.RunEvent{CreatedAt: at(0), Key: timelineKeyAttestation, Status: "started", Attestation: &action.RunEventAttestation{}} + started := &action.RunEvent{CreatedAt: at(0), 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), Key: "chainloop.material." + name, Status: status, Message: msg, Material: &action.RunEventMaterial{Name: name, Policies: policies}} @@ -65,42 +66,49 @@ func TestRenderRunTimeline(t *testing.T) { {Name: "build-log", Provided: true}, }, }, - want: `Timeline (reported progress) · started 10:00:02 · running for 5m43s · 1 of 2 required provided · attestation policies: 2 passed -├─ 10:02:21 ✓ sast-report optional · 1 passed, 1 violated -├─ 10:03:10 ✓ sbom required · 2 passed · 1 failed -│ ├─ 10:03:10 ✗ invalid CycloneDX document: missing bomFormat -│ └─ 10:04:05 ✓ succeeded -├─ 10:05:30 ✓ build-log not in contract -├─ ○ image required · missing -└─ ● waiting for push -`, + 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: "finished run", + name: "stored run", events: []*action.RunEvent{ started, material(451*time.Second, "vulnerability-report", "succeeded", "", nil), - {CreatedAt: at(500 * time.Second), Key: "chainloop.push", Status: "succeeded", Push: &action.RunEventPush{Policies: &action.RunEventPolicyCount{Evaluated: 1, Passed: 1}}}, - {CreatedAt: at(501 * time.Second), Key: timelineKeyAttestation, Status: "succeeded", Attestation: &action.RunEventAttestation{AttestationDigest: "sha256:4de7"}}, + {CreatedAt: at(501 * time.Second), Key: timelineKeyAttestation, Status: "succeeded", Attestation: &action.RunEventAttestation{ + AttestationDigest: "sha256:4de7a1b2c3d4e5f60718293a4b5c6d7e8f", Policies: &action.RunEventPolicyCount{Evaluated: 1, Passed: 1}}}, }, - want: `Timeline · started 10:00:02 · finished 10:08:23 (8m21s) · stored -├─ 10:07:33 ✓ vulnerability-report -├─ 10:08:22 ✓ push 1 passed -└─ 10:08:23 ✓ attestation stored sha256:4de7 -`, + 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: 1 passed · sha256:4de7a1b2c3d4…\n", }, { - name: "blocked push, then expired", + 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", Policies: &action.RunEventPolicyCount{Evaluated: 1, Violated: 1}, BlockingPolicies: []string{"sast-no-critical"}}}, + }, + 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: 1 violated · blocked by: sast-no-critical · sha256:4de7\n", + }, + { + name: "expired run", events: []*action.RunEvent{ started, - {CreatedAt: at(60 * time.Second), Key: "chainloop.push", Status: "failed", Message: "blocked by policy gates: sast-no-critical", - Push: &action.RunEventPush{Policies: &action.RunEventPolicyCount{Evaluated: 1, Violated: 1}, BlockingPolicies: []string{"sast-no-critical"}}}, {CreatedAt: at(3600 * time.Second), Key: timelineKeyAttestation, Status: "failed", Message: "expired"}, }, - want: `Timeline · started 10:00:02 · finished 11:00:02 (1h0m0s) · failed -├─ 10:01:02 ✗ push 1 violated · blocked by: sast-no-critical -└─ 11:00:02 ✗ attestation failed 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", }, } diff --git a/app/cli/pkg/action/attestation_push.go b/app/cli/pkg/action/attestation_push.go index ef145d80f..0ef5595a8 100644 --- a/app/cli/pkg/action/attestation_push.go +++ b/app/cli/pkg/action/attestation_push.go @@ -51,9 +51,6 @@ type AttestationPushOpts struct { ConnectionInsecure bool LocalStatePath string SignServerOpts *SignServerOpts - // NoPolicyGates tells that the caller does not enforce policy gates after the push, - // so the push event never reports a blocked push - NoPolicyGates bool } // SignServerOpts holds SignServer integration options @@ -92,7 +89,6 @@ type AttestationPush struct { connectionInsecure bool localStatePath string signServerOpts *SignServerOpts - noPolicyGates bool *newCrafterOpts } @@ -108,7 +104,6 @@ func NewAttestationPush(cfg *AttestationPushOpts) (*AttestationPush, error) { casCAPath: cfg.CASCAPath, connectionInsecure: cfg.ConnectionInsecure, signServerOpts: cfg.SignServerOpts, - noPolicyGates: cfg.NoPolicyGates, localStatePath: cfg.LocalStatePath, newCrafterOpts: &newCrafterOpts{cpConnection: cfg.CPConnection, opts: opts}, }, nil @@ -291,11 +286,6 @@ func (action *AttestationPush) Run(ctx context.Context, attestationID string, ru workflow := crafter.CraftingState.Attestation.GetWorkflow() - // Progress events are best effort, they never stop the push. The push command - // enforces the same gates after the attestation is stored. - recordPushEvent(ctx, newRunEventRecorderFromState(action.CPConnection, crafter.CraftingState.CraftingState, action.Logger), - crafter.CraftingState.CraftingState, attestationStatus.PolicyEvaluations, bypassPolicyCheck || action.noPolicyGates) - attestationResult.Digest, err = pushToControlPlane(ctx, action.CPConnection, bundle, workflow.GetWorkflowRunId(), workflow.GetVersion().GetMarkAsReleased()) if err != nil { return nil, fmt.Errorf("pushing to control plane: %w", err) @@ -337,18 +327,6 @@ func (action *AttestationPush) saveBundle(bundle *protobundle.Bundle) error { return nil } -// recordPushEvent records the push event with all the attestation policies of the run. It -// fails when gates block the push and the check is not bypassed. A dry run has no run, so -// its recorder sends nothing. -func recordPushEvent(ctx context.Context, events *runEventRecorder, state *v1.CraftingState, evaluations map[string][]*PolicyEvaluation, bypassPolicyCheck bool) { - var blocking []string - if !bypassPolicyCheck { - blocking = BlockingPolicies(evaluations) - } - - _ = events.Record(ctx, pushEvent(state, blocking)) -} - // BlockingPolicies returns the sorted names of the gated policies with a violation that an // assessment does not suppress. They block the push unless the check is bypassed. func BlockingPolicies(evaluations map[string][]*PolicyEvaluation) []string { diff --git a/app/cli/pkg/action/runevents.go b/app/cli/pkg/action/runevents.go index 9cf5c8ceb..54b4b90c0 100644 --- a/app/cli/pkg/action/runevents.go +++ b/app/cli/pkg/action/runevents.go @@ -48,7 +48,7 @@ const ( // 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 and PushAttributes in workflow_run.proto + // see the max_items rules of PolicyCounts in workflow_run.proto runEventMaxPolicyNames = 100 // 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 @@ -58,7 +58,6 @@ const ( runEventKeyAttestation = runEventKeyPrefix + "attestation" runEventKeyMaterial = runEventKeyPrefix + "material" runEventKeyMaterialPrefix = runEventKeyMaterial + "." - runEventKeyPush = runEventKeyPrefix + "push" runEventStatusStarted = "started" runEventStatusFailed = "failed" @@ -111,12 +110,6 @@ func (r *runEventRecorder) Record(ctx context.Context, event *pb.WorkflowRunEven if a := event.GetAttestation(); a != nil { capPolicyNames(a.GetPolicies()) } - if p := event.GetPush(); p != nil { - capPolicyNames(p.GetPolicies()) - if len(p.BlockingPolicies) > runEventMaxPolicyNames { - p.BlockingPolicies = p.BlockingPolicies[:runEventMaxPolicyNames] - } - } ctx, cancel := context.WithTimeout(ctx, r.timeout) defer cancel() @@ -164,27 +157,6 @@ func attestationStartedEvent(state *api.CraftingState, remoteState bool, cliVers } } -// pushEvent is sent after the push-phase policies and before the attestation is stored. -// It fails when policy gates block the push, that is when blocking is not empty. -func pushEvent(state *api.CraftingState, blocking []string) *pb.WorkflowRunEvent { - ev := &pb.WorkflowRunEvent{ - Type: pb.WorkflowRunEvent_TYPE_PUSH, - Key: runEventKeyPush, - Status: pb.WorkflowRunEvent_STATUS_SUCCEEDED, - Attributes: &pb.WorkflowRunEvent_Push{Push: &pb.WorkflowRunEvent_PushAttributes{ - Policies: policyCounts(state, ""), - BlockingPolicies: blocking, - }}, - } - - if len(blocking) > 0 { - ev.Status = pb.WorkflowRunEvent_STATUS_FAILED - ev.Message = "blocked by policy gates: " + strings.Join(blocking, ", ") - } - - return ev -} - // 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 { diff --git a/app/cli/pkg/action/runevents_test.go b/app/cli/pkg/action/runevents_test.go index 4b2d7cca8..76d8da47e 100644 --- a/app/cli/pkg/action/runevents_test.go +++ b/app/cli/pkg/action/runevents_test.go @@ -339,22 +339,20 @@ func TestRunEventRecorderCapsPolicyNames(t *testing.T) { fake := &fakeEventsControlPlane{} r := newRunEventRecorder(newFakeEventsConn(t, fake), testRunID, zerolog.Nop()) require.NoError(t, r.Record(context.Background(), &pb.WorkflowRunEvent{ - Type: pb.WorkflowRunEvent_TYPE_PUSH, Key: "chainloop.push", Status: pb.WorkflowRunEvent_STATUS_FAILED, - Attributes: &pb.WorkflowRunEvent_Push{Push: &pb.WorkflowRunEvent_PushAttributes{ - Policies: &pb.WorkflowRunEvent_PolicyCounts{Violated: 150, ViolatedPolicies: names}, - BlockingPolicies: names, + 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) - push := got[0].GetEvent().GetPush() - assert.Len(t, push.GetBlockingPolicies(), 100) - assert.Len(t, push.GetPolicies().GetViolatedPolicies(), 100) - assert.Equal(t, int32(150), push.GetPolicies().GetViolated(), "the counts stay complete") + att := got[0].GetEvent().GetAttestation() + assert.Len(t, att.GetPolicies().GetViolatedPolicies(), 100) + assert.Equal(t, int32(150), att.GetPolicies().GetViolated(), "the counts stay complete") } -// The gate rule of the push: a gated policy with a violation that is not suppressed +// The gate rule of the push command: a gated policy with a violation that is not suppressed func TestBlockingPolicies(t *testing.T) { violation := []*PolicyViolation{{Message: testBad}} suppressed := []*PolicyViolation{{Message: "not affected", Suppress: true}} @@ -391,82 +389,6 @@ func TestBlockingPolicies(t *testing.T) { } } -// The push records its event before the store: failed when a gate blocks it, succeeded -// when the gate is bypassed, and nothing in a dry run -func TestRecordPushEvent(t *testing.T) { - gated := map[string][]*PolicyEvaluation{testAtt: {{Name: testAttGate, Gate: true, Violations: []*PolicyViolation{{Message: testBad}}}}} - runState := &api.CraftingState{Attestation: &api.Attestation{Workflow: &api.WorkflowMetadata{WorkflowRunId: testRunID}}} - dryRunState := &api.CraftingState{DryRun: true, Attestation: runState.GetAttestation()} - - testCases := []struct { - name string - state *api.CraftingState - bypass bool - wantSent bool - wantStatus pb.WorkflowRunEvent_Status - wantBlocking []string - }{ - {name: "blocked push", state: runState, wantSent: true, wantStatus: pb.WorkflowRunEvent_STATUS_FAILED, wantBlocking: []string{testAttGate}}, - {name: "bypassed gate", state: runState, bypass: true, wantSent: true, wantStatus: pb.WorkflowRunEvent_STATUS_SUCCEEDED}, - {name: "dry run", state: dryRunState}, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - fake := &fakeEventsControlPlane{} - events := newRunEventRecorderFromState(newFakeEventsConn(t, fake), tc.state, zerolog.Nop()) - - recordPushEvent(context.Background(), events, tc.state, gated, tc.bypass) - - got := fake.received() - if !tc.wantSent { - assert.Empty(t, got) - return - } - - require.Len(t, got, 1) - ev := got[0].GetEvent() - assert.Equal(t, "chainloop.push", ev.GetKey()) - assert.Equal(t, tc.wantStatus, ev.GetStatus()) - assert.Equal(t, tc.wantBlocking, ev.GetPush().GetBlockingPolicies()) - }) - } -} - -func TestPushEvent(t *testing.T) { - state := &api.CraftingState{Attestation: &api.Attestation{PolicyEvaluations: []*api.PolicyEvaluation{ - {Name: testAttGate, Gate: true, Violations: []*api.PolicyEvaluation_Violation{{Message: testBad}}}, - {Name: "sbom-policy", MaterialName: testSBOM}, - }}} - - testCases := []struct { - name string - blocking []string - wantStatus pb.WorkflowRunEvent_Status - }{ - {name: "not blocked, or bypassed", wantStatus: pb.WorkflowRunEvent_STATUS_SUCCEEDED}, - {name: "blocked by a gate", blocking: []string{testAttGate}, wantStatus: pb.WorkflowRunEvent_STATUS_FAILED}, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - ev := pushEvent(state, tc.blocking) - - assert.Equal(t, "chainloop.push", ev.GetKey()) - assert.Equal(t, pb.WorkflowRunEvent_TYPE_PUSH, ev.GetType()) - assert.Equal(t, tc.wantStatus, ev.GetStatus()) - assert.Equal(t, tc.blocking, ev.GetPush().GetBlockingPolicies()) - if tc.blocking != nil { - assert.Contains(t, ev.GetMessage(), testAttGate) - } else { - assert.Empty(t, ev.GetMessage()) - } - // the counts cover the attestation policies only, material policies are in material events - assert.Equal(t, int32(1), ev.GetPush().GetPolicies().GetEvaluated()) - }) - } -} - func TestPolicyCounts(t *testing.T) { violation := []*api.PolicyEvaluation_Violation{{Message: testBad}} suppressed := []*api.PolicyEvaluation_Violation{{Message: "not affected", Suppress: true}} @@ -546,7 +468,6 @@ func TestMaterialEventHoldsOnlySafeData(t *testing.T) { events := []*pb.WorkflowRunEvent{ materialAddedEvent(c, res, false), attestationStartedEvent(c.CraftingState.CraftingState, true, "v1.2.3"), - pushEvent(c.CraftingState.CraftingState, nil), } for _, ev := range events { diff --git a/app/cli/pkg/action/trace_attestation.go b/app/cli/pkg/action/trace_attestation.go index 0b25d5f68..dbc3d754a 100644 --- a/app/cli/pkg/action/trace_attestation.go +++ b/app/cli/pkg/action/trace_attestation.go @@ -275,8 +275,6 @@ func (e *AttestationExecutor) Push(ctx context.Context) (*AttestationResult, err ConnectionInsecure: casInsecure(), CLIVersion: cliVersion, CLIDigest: cliDigest, - // Trace pushes do not enforce policy gates - NoPolicyGates: true, }) if err != nil { return nil, fmt.Errorf("create attestation push action: %w", err) diff --git a/app/cli/pkg/action/workflow_run_describe.go b/app/cli/pkg/action/workflow_run_describe.go index 663a65a66..79fcb8920 100644 --- a/app/cli/pkg/action/workflow_run_describe.go +++ b/app/cli/pkg/action/workflow_run_describe.go @@ -540,7 +540,6 @@ type RunEvent struct { Message string `json:"message,omitempty"` Attestation *RunEventAttestation `json:"attestation,omitempty"` Material *RunEventMaterial `json:"material,omitempty"` - Push *RunEventPush `json:"push,omitempty"` } type RunEventAttestation struct { @@ -550,8 +549,11 @@ type RunEventAttestation struct { 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 + // results of the attestation policies: evaluated at init on the start event, + // of the stored attestation on the closing event Policies *RunEventPolicyCount `json:"policies,omitempty"` + // gated policies with violations in the stored attestation, on the closing event + BlockingPolicies []string `json:"blocking_policies,omitempty"` } type RunEventMaterial struct { @@ -564,12 +566,6 @@ type RunEventMaterial struct { Policies *RunEventPolicyCount `json:"policies,omitempty"` } -type RunEventPush struct { - // results of the attestation policies evaluated at push - Policies *RunEventPolicyCount `json:"policies,omitempty"` - BlockingPolicies []string `json:"blocking_policies,omitempty"` -} - type RunEventPolicyCount struct { Evaluated int32 `json:"evaluated"` Passed int32 `json:"passed"` @@ -653,7 +649,7 @@ func pbRunEventToAction(in *pb.WorkflowRunEvent) *RunEvent { 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()), + Policies: pbRunEventPolicyCountToAction(a.GetPolicies()), BlockingPolicies: a.GetBlockingPolicies(), } } @@ -664,10 +660,6 @@ func pbRunEventToAction(in *pb.WorkflowRunEvent) *RunEvent { } } - if p := in.GetPush(); p != nil { - out.Push = &RunEventPush{Policies: pbRunEventPolicyCountToAction(p.GetPolicies()), BlockingPolicies: p.GetBlockingPolicies()} - } - return out } @@ -712,11 +704,9 @@ func buildRunProgress(contractMaterials []*schemaapi.CraftingSchema_Material, ev if e.Status == runEventStatusFailed { failed[name]++ } - // the latest attestation policy results: init, then push + // the latest attestation policy results: init, then the stored attestation case e.Attestation != nil && e.Attestation.Policies != nil: progress.AttestationPolicies = e.Attestation.Policies - case e.Push != nil && e.Push.Policies != nil: - progress.AttestationPolicies = e.Push.Policies } } diff --git a/app/cli/pkg/action/workflow_run_describe_test.go b/app/cli/pkg/action/workflow_run_describe_test.go index 1ca94ae2b..469b9e396 100644 --- a/app/cli/pkg/action/workflow_run_describe_test.go +++ b/app/cli/pkg/action/workflow_run_describe_test.go @@ -298,16 +298,20 @@ func TestBuildRunProgressGroups(t *testing.T) { } } -// The attestation policy results come from the started event, then from the push event +// The attestation policy results come from the started event, then from the closing event +// of the stored attestation func TestBuildRunProgressAttestationPolicies(t *testing.T) { now := time.Now() initCounts := &RunEventPolicyCount{Evaluated: 2, Passed: 2} - pushCounts := &RunEventPolicyCount{Evaluated: 3, Passed: 2, Violated: 1} + storedCounts := &RunEventPolicyCount{Evaluated: 3, Passed: 2, Violated: 1} started := &RunEvent{CreatedAt: &now, Key: testAttKey, Status: "started", Attestation: &RunEventAttestation{Policies: initCounts}} - push := &RunEvent{CreatedAt: &now, Key: "chainloop.push", Status: "failed", Push: &RunEventPush{Policies: pushCounts, BlockingPolicies: []string{"gate"}}} + stored := &RunEvent{CreatedAt: &now, Key: testAttKey, Status: "succeeded", + Attestation: &RunEventAttestation{Policies: storedCounts, BlockingPolicies: []string{"gate"}}} + expired := &RunEvent{CreatedAt: &now, Key: testAttKey, Status: "failed", Message: "expired"} assert.Equal(t, initCounts, buildRunProgress(nil, []*RunEvent{started}, now).AttestationPolicies) - assert.Equal(t, pushCounts, buildRunProgress(nil, []*RunEvent{started, push}, now).AttestationPolicies) + assert.Equal(t, storedCounts, buildRunProgress(nil, []*RunEvent{started, stored}, now).AttestationPolicies) + assert.Equal(t, initCounts, buildRunProgress(nil, []*RunEvent{started, expired}, now).AttestationPolicies) } // fakeRunViewServer serves View for one run, and ListEvents with a configured answer diff --git a/app/controlplane/api/controlplane/v1/workflow_run.pb.go b/app/controlplane/api/controlplane/v1/workflow_run.pb.go index dae0659bd..8348f3928 100644 --- a/app/controlplane/api/controlplane/v1/workflow_run.pb.go +++ b/app/controlplane/api/controlplane/v1/workflow_run.pb.go @@ -143,7 +143,6 @@ const ( WorkflowRunEvent_TYPE_UNSPECIFIED WorkflowRunEvent_Type = 0 WorkflowRunEvent_TYPE_ATTESTATION WorkflowRunEvent_Type = 1 WorkflowRunEvent_TYPE_MATERIAL WorkflowRunEvent_Type = 2 - WorkflowRunEvent_TYPE_PUSH WorkflowRunEvent_Type = 3 ) // Enum value maps for WorkflowRunEvent_Type. @@ -152,13 +151,11 @@ var ( 0: "TYPE_UNSPECIFIED", 1: "TYPE_ATTESTATION", 2: "TYPE_MATERIAL", - 3: "TYPE_PUSH", } WorkflowRunEvent_Type_value = map[string]int32{ "TYPE_UNSPECIFIED": 0, "TYPE_ATTESTATION": 1, "TYPE_MATERIAL": 2, - "TYPE_PUSH": 3, } ) @@ -1312,7 +1309,6 @@ type WorkflowRunEvent struct { // // *WorkflowRunEvent_Attestation // *WorkflowRunEvent_Material - // *WorkflowRunEvent_Push Attributes isWorkflowRunEvent_Attributes `protobuf_oneof:"attributes"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache @@ -1422,15 +1418,6 @@ func (x *WorkflowRunEvent) GetMaterial() *WorkflowRunEvent_MaterialAttributes { return nil } -func (x *WorkflowRunEvent) GetPush() *WorkflowRunEvent_PushAttributes { - if x != nil { - if x, ok := x.Attributes.(*WorkflowRunEvent_Push); ok { - return x.Push - } - } - return nil -} - type isWorkflowRunEvent_Attributes interface { isWorkflowRunEvent_Attributes() } @@ -1443,16 +1430,10 @@ type WorkflowRunEvent_Material struct { Material *WorkflowRunEvent_MaterialAttributes `protobuf:"bytes,11,opt,name=material,proto3,oneof"` } -type WorkflowRunEvent_Push struct { - Push *WorkflowRunEvent_PushAttributes `protobuf:"bytes,12,opt,name=push,proto3,oneof"` -} - func (*WorkflowRunEvent_Attestation) isWorkflowRunEvent_Attributes() {} func (*WorkflowRunEvent_Material) isWorkflowRunEvent_Attributes() {} -func (*WorkflowRunEvent_Push) isWorkflowRunEvent_Attributes() {} - type WorkflowRunServiceListRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // Filters @@ -2137,10 +2118,14 @@ type WorkflowRunEvent_AttestationAttributes struct { 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"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // results of the attestation policies: the ones evaluated at init on the start event, + // the ones of the stored attestation on the closing event + Policies *WorkflowRunEvent_PolicyCounts `protobuf:"bytes,7,opt,name=policies,proto3" json:"policies,omitempty"` + // gated policies with violations in the stored attestation, empty when the check + // was bypassed. Set on the closing event only. + BlockingPolicies []string `protobuf:"bytes,8,rep,name=blocking_policies,json=blockingPolicies,proto3" json:"blocking_policies,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *WorkflowRunEvent_AttestationAttributes) Reset() { @@ -2222,6 +2207,13 @@ func (x *WorkflowRunEvent_AttestationAttributes) GetPolicies() *WorkflowRunEvent return nil } +func (x *WorkflowRunEvent_AttestationAttributes) GetBlockingPolicies() []string { + if x != nil { + return x.BlockingPolicies + } + return nil +} + type WorkflowRunEvent_MaterialAttributes struct { state protoimpl.MessageState `protogen:"open.v1"` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` @@ -2315,60 +2307,6 @@ func (x *WorkflowRunEvent_MaterialAttributes) GetPolicies() *WorkflowRunEvent_Po return nil } -type WorkflowRunEvent_PushAttributes struct { - state protoimpl.MessageState `protogen:"open.v1"` - // results of the attestation policies evaluated at push - Policies *WorkflowRunEvent_PolicyCounts `protobuf:"bytes,1,opt,name=policies,proto3" json:"policies,omitempty"` - // gated policies with violations that block the push - BlockingPolicies []string `protobuf:"bytes,2,rep,name=blocking_policies,json=blockingPolicies,proto3" json:"blocking_policies,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *WorkflowRunEvent_PushAttributes) Reset() { - *x = WorkflowRunEvent_PushAttributes{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[32] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *WorkflowRunEvent_PushAttributes) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*WorkflowRunEvent_PushAttributes) ProtoMessage() {} - -func (x *WorkflowRunEvent_PushAttributes) 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 { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use WorkflowRunEvent_PushAttributes.ProtoReflect.Descriptor instead. -func (*WorkflowRunEvent_PushAttributes) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{19, 2} -} - -func (x *WorkflowRunEvent_PushAttributes) GetPolicies() *WorkflowRunEvent_PolicyCounts { - if x != nil { - return x.Policies - } - return nil -} - -func (x *WorkflowRunEvent_PushAttributes) GetBlockingPolicies() []string { - if x != nil { - return x.BlockingPolicies - } - return nil -} - type WorkflowRunEvent_PolicyCounts struct { state protoimpl.MessageState `protogen:"open.v1"` Evaluated int32 `protobuf:"varint,1,opt,name=evaluated,proto3" json:"evaluated,omitempty"` @@ -2382,7 +2320,7 @@ type WorkflowRunEvent_PolicyCounts struct { func (x *WorkflowRunEvent_PolicyCounts) Reset() { *x = WorkflowRunEvent_PolicyCounts{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[33] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[32] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2394,7 +2332,7 @@ func (x *WorkflowRunEvent_PolicyCounts) String() string { func (*WorkflowRunEvent_PolicyCounts) ProtoMessage() {} func (x *WorkflowRunEvent_PolicyCounts) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[33] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[32] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2407,7 +2345,7 @@ func (x *WorkflowRunEvent_PolicyCounts) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkflowRunEvent_PolicyCounts.ProtoReflect.Descriptor instead. func (*WorkflowRunEvent_PolicyCounts) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{19, 3} + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{19, 2} } func (x *WorkflowRunEvent_PolicyCounts) GetEvaluated() int32 { @@ -2458,7 +2396,7 @@ type WorkflowRunServiceViewResponse_Result struct { func (x *WorkflowRunServiceViewResponse_Result) Reset() { *x = WorkflowRunServiceViewResponse_Result{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[34] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[33] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2470,7 +2408,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[34] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[33] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2526,7 +2464,7 @@ type WorkflowRunServiceViewResponse_VerificationResult struct { func (x *WorkflowRunServiceViewResponse_VerificationResult) Reset() { *x = WorkflowRunServiceViewResponse_VerificationResult{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[35] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[34] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2538,7 +2476,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[35] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[34] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2578,7 +2516,7 @@ type AttestationServiceGetUploadCredsResponse_Result struct { func (x *AttestationServiceGetUploadCredsResponse_Result) Reset() { *x = AttestationServiceGetUploadCredsResponse_Result{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[36] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[35] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2590,7 +2528,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[36] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[35] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2714,7 +2652,7 @@ const file_controlplane_v1_workflow_run_proto_rawDesc = "" + "\x0fworkflow_run_id\x18\x01 \x01(\tB\b\xbaH\x05r\x03\xb0\x01\x01R\rworkflowRunId\x121\n" + "\x0eafter_event_id\x18\x02 \x01(\tB\v\xbaH\b\xd8\x01\x01r\x03\xb0\x01\x01R\fafterEventId\"a\n" + "$WorkflowRunServiceListEventsResponse\x129\n" + - "\x06events\x18\x01 \x03(\v2!.controlplane.v1.WorkflowRunEventR\x06events\"\xa1\x0f\n" + + "\x06events\x18\x01 \x03(\v2!.controlplane.v1.WorkflowRunEventR\x06events\"\x88\x0e\n" + "\x10WorkflowRunEvent\x12\x0e\n" + "\x02id\x18\x01 \x01(\tR\x02id\x129\n" + "\n" + @@ -2729,8 +2667,7 @@ const file_controlplane_v1_workflow_run_proto_rawDesc = "" + "\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\x12F\n" + - "\x04push\x18\f \x01(\v20.controlplane.v1.WorkflowRunEvent.PushAttributesH\x00R\x04push\x1a\xf1\x02\n" + + "\bmaterial\x18\v \x01(\v24.controlplane.v1.WorkflowRunEvent.MaterialAttributesH\x00R\bmaterial\x1a\xaf\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" + @@ -2740,7 +2677,8 @@ const file_controlplane_v1_workflow_run_proto_rawDesc = "" + "\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\x1a\xbe\x02\n" + + "\bpolicies\x18\a \x01(\v2..controlplane.v1.WorkflowRunEvent.PolicyCountsR\bpolicies\x12<\n" + + "\x11blocking_policies\x18\b \x03(\tB\x0f\xbaH\f\x92\x01\t\x10d\"\x05r\x03\x18\x80\x02R\x10blockingPolicies\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" + @@ -2749,10 +2687,7 @@ const file_controlplane_v1_workflow_run_proto_rawDesc = "" + "\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\x9a\x01\n" + - "\x0ePushAttributes\x12J\n" + - "\bpolicies\x18\x01 \x01(\v2..controlplane.v1.WorkflowRunEvent.PolicyCountsR\bpolicies\x12<\n" + - "\x11blocking_policies\x18\x02 \x03(\tB\x0f\xbaH\f\x92\x01\t\x10d\"\x05r\x03\x18\x80\x02R\x10blockingPolicies\x1a\xb8\x01\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" + @@ -2763,12 +2698,11 @@ const file_controlplane_v1_workflow_run_proto_rawDesc = "" + "\x12SOURCE_UNSPECIFIED\x10\x00\x12\x0e\n" + "\n" + "SOURCE_CLI\x10\x01\x12\x18\n" + - "\x14SOURCE_CONTROL_PLANE\x10\x02\"T\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\x12\r\n" + - "\tTYPE_PUSH\x10\x03\"r\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" + @@ -2776,7 +2710,7 @@ const file_controlplane_v1_workflow_run_proto_rawDesc = "" + "\rSTATUS_FAILED\x10\x03\x12\x13\n" + "\x0fSTATUS_CANCELED\x10\x04B\f\n" + "\n" + - "attributes\"\x83\b\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" + @@ -2848,7 +2782,7 @@ func file_controlplane_v1_workflow_run_proto_rawDescGZIP() []byte { } var file_controlplane_v1_workflow_run_proto_enumTypes = make([]protoimpl.EnumInfo, 4) -var file_controlplane_v1_workflow_run_proto_msgTypes = make([]protoimpl.MessageInfo, 37) +var file_controlplane_v1_workflow_run_proto_msgTypes = make([]protoimpl.MessageInfo, 36) var file_controlplane_v1_workflow_run_proto_goTypes = []any{ (AttestationServiceCancelRequest_TriggerType)(0), // 0: controlplane.v1.AttestationServiceCancelRequest.TriggerType (WorkflowRunEvent_Source)(0), // 1: controlplane.v1.WorkflowRunEvent.Source @@ -2886,96 +2820,93 @@ var file_controlplane_v1_workflow_run_proto_goTypes = []any{ (*AttestationServiceStoreResponse_Result)(nil), // 33: controlplane.v1.AttestationServiceStoreResponse.Result (*WorkflowRunEvent_AttestationAttributes)(nil), // 34: controlplane.v1.WorkflowRunEvent.AttestationAttributes (*WorkflowRunEvent_MaterialAttributes)(nil), // 35: controlplane.v1.WorkflowRunEvent.MaterialAttributes - (*WorkflowRunEvent_PushAttributes)(nil), // 36: controlplane.v1.WorkflowRunEvent.PushAttributes - (*WorkflowRunEvent_PolicyCounts)(nil), // 37: controlplane.v1.WorkflowRunEvent.PolicyCounts - (*WorkflowRunServiceViewResponse_Result)(nil), // 38: controlplane.v1.WorkflowRunServiceViewResponse.Result - (*WorkflowRunServiceViewResponse_VerificationResult)(nil), // 39: controlplane.v1.WorkflowRunServiceViewResponse.VerificationResult - (*AttestationServiceGetUploadCredsResponse_Result)(nil), // 40: controlplane.v1.AttestationServiceGetUploadCredsResponse.Result - (*WorkflowItem)(nil), // 41: controlplane.v1.WorkflowItem - (*v1.Policy)(nil), // 42: workflowcontract.v1.Policy - (*v1.PolicyGroup)(nil), // 43: workflowcontract.v1.PolicyGroup - (v1.CraftingSchema_Runner_RunnerType)(0), // 44: workflowcontract.v1.CraftingSchema.Runner.RunnerType - (*timestamppb.Timestamp)(nil), // 45: google.protobuf.Timestamp - (RunStatus)(0), // 46: controlplane.v1.RunStatus - (PolicyViolationsFilter)(0), // 47: controlplane.v1.PolicyViolationsFilter - (PolicyStatusFilter)(0), // 48: controlplane.v1.PolicyStatusFilter - (PolicyGatesFilter)(0), // 49: controlplane.v1.PolicyGatesFilter - (*CursorPaginationRequest)(nil), // 50: controlplane.v1.CursorPaginationRequest - (*WorkflowRunItem)(nil), // 51: controlplane.v1.WorkflowRunItem - (*CursorPaginationResponse)(nil), // 52: controlplane.v1.CursorPaginationResponse - (*WorkflowContractVersionItem)(nil), // 53: controlplane.v1.WorkflowContractVersionItem - (*AttestationItem)(nil), // 54: controlplane.v1.AttestationItem - (*CASBackendItem)(nil), // 55: controlplane.v1.CASBackendItem + (*WorkflowRunEvent_PolicyCounts)(nil), // 36: controlplane.v1.WorkflowRunEvent.PolicyCounts + (*WorkflowRunServiceViewResponse_Result)(nil), // 37: controlplane.v1.WorkflowRunServiceViewResponse.Result + (*WorkflowRunServiceViewResponse_VerificationResult)(nil), // 38: controlplane.v1.WorkflowRunServiceViewResponse.VerificationResult + (*AttestationServiceGetUploadCredsResponse_Result)(nil), // 39: controlplane.v1.AttestationServiceGetUploadCredsResponse.Result + (*WorkflowItem)(nil), // 40: controlplane.v1.WorkflowItem + (*v1.Policy)(nil), // 41: workflowcontract.v1.Policy + (*v1.PolicyGroup)(nil), // 42: workflowcontract.v1.PolicyGroup + (v1.CraftingSchema_Runner_RunnerType)(0), // 43: workflowcontract.v1.CraftingSchema.Runner.RunnerType + (*timestamppb.Timestamp)(nil), // 44: google.protobuf.Timestamp + (RunStatus)(0), // 45: controlplane.v1.RunStatus + (PolicyViolationsFilter)(0), // 46: controlplane.v1.PolicyViolationsFilter + (PolicyStatusFilter)(0), // 47: controlplane.v1.PolicyStatusFilter + (PolicyGatesFilter)(0), // 48: controlplane.v1.PolicyGatesFilter + (*CursorPaginationRequest)(nil), // 49: controlplane.v1.CursorPaginationRequest + (*WorkflowRunItem)(nil), // 50: controlplane.v1.WorkflowRunItem + (*CursorPaginationResponse)(nil), // 51: controlplane.v1.CursorPaginationResponse + (*WorkflowContractVersionItem)(nil), // 52: controlplane.v1.WorkflowContractVersionItem + (*AttestationItem)(nil), // 53: controlplane.v1.AttestationItem + (*CASBackendItem)(nil), // 54: controlplane.v1.CASBackendItem } var file_controlplane_v1_workflow_run_proto_depIdxs = []int32{ - 41, // 0: controlplane.v1.FindOrCreateWorkflowResponse.result:type_name -> controlplane.v1.WorkflowItem - 42, // 1: controlplane.v1.AttestationServiceGetPolicyResponse.policy:type_name -> workflowcontract.v1.Policy + 40, // 0: controlplane.v1.FindOrCreateWorkflowResponse.result:type_name -> controlplane.v1.WorkflowItem + 41, // 1: controlplane.v1.AttestationServiceGetPolicyResponse.policy:type_name -> workflowcontract.v1.Policy 8, // 2: controlplane.v1.AttestationServiceGetPolicyResponse.reference:type_name -> controlplane.v1.RemotePolicyReference - 43, // 3: controlplane.v1.AttestationServiceGetPolicyGroupResponse.group:type_name -> workflowcontract.v1.PolicyGroup + 42, // 3: controlplane.v1.AttestationServiceGetPolicyGroupResponse.group:type_name -> workflowcontract.v1.PolicyGroup 8, // 4: controlplane.v1.AttestationServiceGetPolicyGroupResponse.reference:type_name -> controlplane.v1.RemotePolicyReference 30, // 5: controlplane.v1.AttestationServiceGetContractResponse.result:type_name -> controlplane.v1.AttestationServiceGetContractResponse.Result - 44, // 6: controlplane.v1.AttestationServiceInitRequest.runner:type_name -> workflowcontract.v1.CraftingSchema.Runner.RunnerType + 43, // 6: controlplane.v1.AttestationServiceInitRequest.runner:type_name -> workflowcontract.v1.CraftingSchema.Runner.RunnerType 31, // 7: controlplane.v1.AttestationServiceInitResponse.result:type_name -> controlplane.v1.AttestationServiceInitResponse.Result 33, // 8: controlplane.v1.AttestationServiceStoreResponse.result:type_name -> controlplane.v1.AttestationServiceStoreResponse.Result 0, // 9: controlplane.v1.AttestationServiceCancelRequest.trigger:type_name -> controlplane.v1.AttestationServiceCancelRequest.TriggerType 23, // 10: controlplane.v1.AttestationServiceRecordEventRequest.event:type_name -> controlplane.v1.WorkflowRunEvent 23, // 11: controlplane.v1.WorkflowRunServiceListEventsResponse.events:type_name -> controlplane.v1.WorkflowRunEvent - 45, // 12: controlplane.v1.WorkflowRunEvent.created_at:type_name -> google.protobuf.Timestamp + 44, // 12: controlplane.v1.WorkflowRunEvent.created_at:type_name -> google.protobuf.Timestamp 1, // 13: controlplane.v1.WorkflowRunEvent.source:type_name -> controlplane.v1.WorkflowRunEvent.Source 2, // 14: controlplane.v1.WorkflowRunEvent.type:type_name -> controlplane.v1.WorkflowRunEvent.Type 3, // 15: controlplane.v1.WorkflowRunEvent.status:type_name -> controlplane.v1.WorkflowRunEvent.Status 34, // 16: controlplane.v1.WorkflowRunEvent.attestation:type_name -> controlplane.v1.WorkflowRunEvent.AttestationAttributes 35, // 17: controlplane.v1.WorkflowRunEvent.material:type_name -> controlplane.v1.WorkflowRunEvent.MaterialAttributes - 36, // 18: controlplane.v1.WorkflowRunEvent.push:type_name -> controlplane.v1.WorkflowRunEvent.PushAttributes - 46, // 19: controlplane.v1.WorkflowRunServiceListRequest.status:type_name -> controlplane.v1.RunStatus - 47, // 20: controlplane.v1.WorkflowRunServiceListRequest.policy_violations:type_name -> controlplane.v1.PolicyViolationsFilter - 48, // 21: controlplane.v1.WorkflowRunServiceListRequest.policy_status:type_name -> controlplane.v1.PolicyStatusFilter - 49, // 22: controlplane.v1.WorkflowRunServiceListRequest.policy_gates:type_name -> controlplane.v1.PolicyGatesFilter - 50, // 23: controlplane.v1.WorkflowRunServiceListRequest.pagination:type_name -> controlplane.v1.CursorPaginationRequest - 51, // 24: controlplane.v1.WorkflowRunServiceListResponse.result:type_name -> controlplane.v1.WorkflowRunItem - 52, // 25: controlplane.v1.WorkflowRunServiceListResponse.pagination:type_name -> controlplane.v1.CursorPaginationResponse - 38, // 26: controlplane.v1.WorkflowRunServiceViewResponse.result:type_name -> controlplane.v1.WorkflowRunServiceViewResponse.Result - 40, // 27: controlplane.v1.AttestationServiceGetUploadCredsResponse.result:type_name -> controlplane.v1.AttestationServiceGetUploadCredsResponse.Result - 41, // 28: controlplane.v1.AttestationServiceGetContractResponse.Result.workflow:type_name -> controlplane.v1.WorkflowItem - 53, // 29: controlplane.v1.AttestationServiceGetContractResponse.Result.contract:type_name -> controlplane.v1.WorkflowContractVersionItem - 51, // 30: controlplane.v1.AttestationServiceInitResponse.Result.workflow_run:type_name -> controlplane.v1.WorkflowRunItem - 32, // 31: controlplane.v1.AttestationServiceInitResponse.Result.signing_options:type_name -> controlplane.v1.AttestationServiceInitResponse.SigningOptions - 37, // 32: controlplane.v1.WorkflowRunEvent.AttestationAttributes.policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts - 37, // 33: controlplane.v1.WorkflowRunEvent.MaterialAttributes.policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts - 37, // 34: controlplane.v1.WorkflowRunEvent.PushAttributes.policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts - 51, // 35: controlplane.v1.WorkflowRunServiceViewResponse.Result.workflow_run:type_name -> controlplane.v1.WorkflowRunItem - 54, // 36: controlplane.v1.WorkflowRunServiceViewResponse.Result.attestation:type_name -> controlplane.v1.AttestationItem - 39, // 37: controlplane.v1.WorkflowRunServiceViewResponse.Result.verification:type_name -> controlplane.v1.WorkflowRunServiceViewResponse.VerificationResult - 55, // 38: controlplane.v1.AttestationServiceGetUploadCredsResponse.Result.backend:type_name -> controlplane.v1.CASBackendItem - 4, // 39: controlplane.v1.AttestationService.FindOrCreateWorkflow:input_type -> controlplane.v1.FindOrCreateWorkflowRequest - 11, // 40: controlplane.v1.AttestationService.GetContract:input_type -> controlplane.v1.AttestationServiceGetContractRequest - 13, // 41: controlplane.v1.AttestationService.Init:input_type -> controlplane.v1.AttestationServiceInitRequest - 15, // 42: controlplane.v1.AttestationService.Store:input_type -> controlplane.v1.AttestationServiceStoreRequest - 28, // 43: controlplane.v1.AttestationService.GetUploadCreds:input_type -> controlplane.v1.AttestationServiceGetUploadCredsRequest - 17, // 44: controlplane.v1.AttestationService.Cancel:input_type -> controlplane.v1.AttestationServiceCancelRequest - 19, // 45: controlplane.v1.AttestationService.RecordEvent:input_type -> controlplane.v1.AttestationServiceRecordEventRequest - 6, // 46: controlplane.v1.AttestationService.GetPolicy:input_type -> controlplane.v1.AttestationServiceGetPolicyRequest - 9, // 47: controlplane.v1.AttestationService.GetPolicyGroup:input_type -> controlplane.v1.AttestationServiceGetPolicyGroupRequest - 24, // 48: controlplane.v1.WorkflowRunService.List:input_type -> controlplane.v1.WorkflowRunServiceListRequest - 26, // 49: controlplane.v1.WorkflowRunService.View:input_type -> controlplane.v1.WorkflowRunServiceViewRequest - 21, // 50: controlplane.v1.WorkflowRunService.ListEvents:input_type -> controlplane.v1.WorkflowRunServiceListEventsRequest - 5, // 51: controlplane.v1.AttestationService.FindOrCreateWorkflow:output_type -> controlplane.v1.FindOrCreateWorkflowResponse - 12, // 52: controlplane.v1.AttestationService.GetContract:output_type -> controlplane.v1.AttestationServiceGetContractResponse - 14, // 53: controlplane.v1.AttestationService.Init:output_type -> controlplane.v1.AttestationServiceInitResponse - 16, // 54: controlplane.v1.AttestationService.Store:output_type -> controlplane.v1.AttestationServiceStoreResponse - 29, // 55: controlplane.v1.AttestationService.GetUploadCreds:output_type -> controlplane.v1.AttestationServiceGetUploadCredsResponse - 18, // 56: controlplane.v1.AttestationService.Cancel:output_type -> controlplane.v1.AttestationServiceCancelResponse - 20, // 57: controlplane.v1.AttestationService.RecordEvent:output_type -> controlplane.v1.AttestationServiceRecordEventResponse - 7, // 58: controlplane.v1.AttestationService.GetPolicy:output_type -> controlplane.v1.AttestationServiceGetPolicyResponse - 10, // 59: controlplane.v1.AttestationService.GetPolicyGroup:output_type -> controlplane.v1.AttestationServiceGetPolicyGroupResponse - 25, // 60: controlplane.v1.WorkflowRunService.List:output_type -> controlplane.v1.WorkflowRunServiceListResponse - 27, // 61: controlplane.v1.WorkflowRunService.View:output_type -> controlplane.v1.WorkflowRunServiceViewResponse - 22, // 62: controlplane.v1.WorkflowRunService.ListEvents:output_type -> controlplane.v1.WorkflowRunServiceListEventsResponse - 51, // [51:63] is the sub-list for method output_type - 39, // [39:51] is the sub-list for method input_type - 39, // [39:39] is the sub-list for extension type_name - 39, // [39:39] is the sub-list for extension extendee - 0, // [0:39] is the sub-list for field type_name + 45, // 18: controlplane.v1.WorkflowRunServiceListRequest.status:type_name -> controlplane.v1.RunStatus + 46, // 19: controlplane.v1.WorkflowRunServiceListRequest.policy_violations:type_name -> controlplane.v1.PolicyViolationsFilter + 47, // 20: controlplane.v1.WorkflowRunServiceListRequest.policy_status:type_name -> controlplane.v1.PolicyStatusFilter + 48, // 21: controlplane.v1.WorkflowRunServiceListRequest.policy_gates:type_name -> controlplane.v1.PolicyGatesFilter + 49, // 22: controlplane.v1.WorkflowRunServiceListRequest.pagination:type_name -> controlplane.v1.CursorPaginationRequest + 50, // 23: controlplane.v1.WorkflowRunServiceListResponse.result:type_name -> controlplane.v1.WorkflowRunItem + 51, // 24: controlplane.v1.WorkflowRunServiceListResponse.pagination:type_name -> controlplane.v1.CursorPaginationResponse + 37, // 25: controlplane.v1.WorkflowRunServiceViewResponse.result:type_name -> controlplane.v1.WorkflowRunServiceViewResponse.Result + 39, // 26: controlplane.v1.AttestationServiceGetUploadCredsResponse.result:type_name -> controlplane.v1.AttestationServiceGetUploadCredsResponse.Result + 40, // 27: controlplane.v1.AttestationServiceGetContractResponse.Result.workflow:type_name -> controlplane.v1.WorkflowItem + 52, // 28: controlplane.v1.AttestationServiceGetContractResponse.Result.contract:type_name -> controlplane.v1.WorkflowContractVersionItem + 50, // 29: controlplane.v1.AttestationServiceInitResponse.Result.workflow_run:type_name -> controlplane.v1.WorkflowRunItem + 32, // 30: controlplane.v1.AttestationServiceInitResponse.Result.signing_options:type_name -> controlplane.v1.AttestationServiceInitResponse.SigningOptions + 36, // 31: controlplane.v1.WorkflowRunEvent.AttestationAttributes.policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts + 36, // 32: controlplane.v1.WorkflowRunEvent.MaterialAttributes.policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts + 50, // 33: controlplane.v1.WorkflowRunServiceViewResponse.Result.workflow_run:type_name -> controlplane.v1.WorkflowRunItem + 53, // 34: controlplane.v1.WorkflowRunServiceViewResponse.Result.attestation:type_name -> controlplane.v1.AttestationItem + 38, // 35: controlplane.v1.WorkflowRunServiceViewResponse.Result.verification:type_name -> controlplane.v1.WorkflowRunServiceViewResponse.VerificationResult + 54, // 36: controlplane.v1.AttestationServiceGetUploadCredsResponse.Result.backend:type_name -> controlplane.v1.CASBackendItem + 4, // 37: controlplane.v1.AttestationService.FindOrCreateWorkflow:input_type -> controlplane.v1.FindOrCreateWorkflowRequest + 11, // 38: controlplane.v1.AttestationService.GetContract:input_type -> controlplane.v1.AttestationServiceGetContractRequest + 13, // 39: controlplane.v1.AttestationService.Init:input_type -> controlplane.v1.AttestationServiceInitRequest + 15, // 40: controlplane.v1.AttestationService.Store:input_type -> controlplane.v1.AttestationServiceStoreRequest + 28, // 41: controlplane.v1.AttestationService.GetUploadCreds:input_type -> controlplane.v1.AttestationServiceGetUploadCredsRequest + 17, // 42: controlplane.v1.AttestationService.Cancel:input_type -> controlplane.v1.AttestationServiceCancelRequest + 19, // 43: controlplane.v1.AttestationService.RecordEvent:input_type -> controlplane.v1.AttestationServiceRecordEventRequest + 6, // 44: controlplane.v1.AttestationService.GetPolicy:input_type -> controlplane.v1.AttestationServiceGetPolicyRequest + 9, // 45: controlplane.v1.AttestationService.GetPolicyGroup:input_type -> controlplane.v1.AttestationServiceGetPolicyGroupRequest + 24, // 46: controlplane.v1.WorkflowRunService.List:input_type -> controlplane.v1.WorkflowRunServiceListRequest + 26, // 47: controlplane.v1.WorkflowRunService.View:input_type -> controlplane.v1.WorkflowRunServiceViewRequest + 21, // 48: controlplane.v1.WorkflowRunService.ListEvents:input_type -> controlplane.v1.WorkflowRunServiceListEventsRequest + 5, // 49: controlplane.v1.AttestationService.FindOrCreateWorkflow:output_type -> controlplane.v1.FindOrCreateWorkflowResponse + 12, // 50: controlplane.v1.AttestationService.GetContract:output_type -> controlplane.v1.AttestationServiceGetContractResponse + 14, // 51: controlplane.v1.AttestationService.Init:output_type -> controlplane.v1.AttestationServiceInitResponse + 16, // 52: controlplane.v1.AttestationService.Store:output_type -> controlplane.v1.AttestationServiceStoreResponse + 29, // 53: controlplane.v1.AttestationService.GetUploadCreds:output_type -> controlplane.v1.AttestationServiceGetUploadCredsResponse + 18, // 54: controlplane.v1.AttestationService.Cancel:output_type -> controlplane.v1.AttestationServiceCancelResponse + 20, // 55: controlplane.v1.AttestationService.RecordEvent:output_type -> controlplane.v1.AttestationServiceRecordEventResponse + 7, // 56: controlplane.v1.AttestationService.GetPolicy:output_type -> controlplane.v1.AttestationServiceGetPolicyResponse + 10, // 57: controlplane.v1.AttestationService.GetPolicyGroup:output_type -> controlplane.v1.AttestationServiceGetPolicyGroupResponse + 25, // 58: controlplane.v1.WorkflowRunService.List:output_type -> controlplane.v1.WorkflowRunServiceListResponse + 27, // 59: controlplane.v1.WorkflowRunService.View:output_type -> controlplane.v1.WorkflowRunServiceViewResponse + 22, // 60: controlplane.v1.WorkflowRunService.ListEvents:output_type -> controlplane.v1.WorkflowRunServiceListEventsResponse + 49, // [49:61] is the sub-list for method output_type + 37, // [37:49] is the sub-list for method input_type + 37, // [37:37] is the sub-list for extension type_name + 37, // [37:37] is the sub-list for extension extendee + 0, // [0:37] is the sub-list for field type_name } func init() { file_controlplane_v1_workflow_run_proto_init() } @@ -2990,7 +2921,6 @@ func file_controlplane_v1_workflow_run_proto_init() { file_controlplane_v1_workflow_run_proto_msgTypes[19].OneofWrappers = []any{ (*WorkflowRunEvent_Attestation)(nil), (*WorkflowRunEvent_Material)(nil), - (*WorkflowRunEvent_Push)(nil), } file_controlplane_v1_workflow_run_proto_msgTypes[22].OneofWrappers = []any{ (*WorkflowRunServiceViewRequest_Id)(nil), @@ -3002,7 +2932,7 @@ func file_controlplane_v1_workflow_run_proto_init() { 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: 4, - NumMessages: 37, + NumMessages: 36, 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 626eba36d..fd2b41583 100644 --- a/app/controlplane/api/controlplane/v1/workflow_run.proto +++ b/app/controlplane/api/controlplane/v1/workflow_run.proto @@ -255,8 +255,9 @@ message WorkflowRunEvent { oneof attributes { AttestationAttributes attestation = 10; MaterialAttributes material = 11; - PushAttributes push = 12; } + reserved 12; + reserved "push"; enum Source { SOURCE_UNSPECIFIED = 0; @@ -268,7 +269,8 @@ message WorkflowRunEvent { TYPE_UNSPECIFIED = 0; TYPE_ATTESTATION = 1; TYPE_MATERIAL = 2; - TYPE_PUSH = 3; + reserved 3; + reserved "TYPE_PUSH"; } enum Status { @@ -286,8 +288,17 @@ message WorkflowRunEvent { 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 + // results of the attestation policies: the ones evaluated at init on the start event, + // the ones of the stored attestation on the closing event PolicyCounts policies = 7; + // gated policies with violations in the stored attestation, empty when the check + // was bypassed. Set on the closing event only. + repeated string blocking_policies = 8 [(buf.validate.field).repeated = { + max_items: 100 + items: { + string: {max_len: 256} + } + }]; } message MaterialAttributes { @@ -301,18 +312,6 @@ message WorkflowRunEvent { PolicyCounts policies = 7; } - message PushAttributes { - // results of the attestation policies evaluated at push - PolicyCounts policies = 1; - // gated policies with violations that block the push - repeated string blocking_policies = 2 [(buf.validate.field).repeated = { - max_items: 100 - items: { - string: {max_len: 256} - } - }]; - } - message PolicyCounts { int32 evaluated = 1; int32 passed = 2; diff --git a/app/controlplane/api/controlplane/v1/workflow_run_test.go b/app/controlplane/api/controlplane/v1/workflow_run_test.go index 177d41cd4..9a0ff16d5 100644 --- a/app/controlplane/api/controlplane/v1/workflow_run_test.go +++ b/app/controlplane/api/controlplane/v1/workflow_run_test.go @@ -67,8 +67,8 @@ func TestAttestationServiceRecordEventRequestLimits(t *testing.T) { { desc: "over 100 blocking policies", mutate: func(ev *v1.WorkflowRunEvent) { - ev.Type = v1.WorkflowRunEvent_TYPE_PUSH - ev.Attributes = &v1.WorkflowRunEvent_Push{Push: &v1.WorkflowRunEvent_PushAttributes{BlockingPolicies: names(101)}} + ev.Type = v1.WorkflowRunEvent_TYPE_ATTESTATION + ev.Attributes = &v1.WorkflowRunEvent_Attestation{Attestation: &v1.WorkflowRunEvent_AttestationAttributes{BlockingPolicies: names(101)}} }, wantErr: true, }, 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 b6549f464..59e6a1ddf 100644 --- a/app/controlplane/api/gen/frontend/controlplane/v1/workflow_run.ts +++ b/app/controlplane/api/gen/frontend/controlplane/v1/workflow_run.ts @@ -259,7 +259,6 @@ export interface WorkflowRunEvent { message: string; attestation?: WorkflowRunEvent_AttestationAttributes | undefined; material?: WorkflowRunEvent_MaterialAttributes | undefined; - push?: WorkflowRunEvent_PushAttributes | undefined; } export enum WorkflowRunEvent_Source { @@ -305,7 +304,6 @@ export enum WorkflowRunEvent_Type { TYPE_UNSPECIFIED = 0, TYPE_ATTESTATION = 1, TYPE_MATERIAL = 2, - TYPE_PUSH = 3, UNRECOGNIZED = -1, } @@ -320,9 +318,6 @@ export function workflowRunEvent_TypeFromJSON(object: any): WorkflowRunEvent_Typ case 2: case "TYPE_MATERIAL": return WorkflowRunEvent_Type.TYPE_MATERIAL; - case 3: - case "TYPE_PUSH": - return WorkflowRunEvent_Type.TYPE_PUSH; case -1: case "UNRECOGNIZED": default: @@ -338,8 +333,6 @@ export function workflowRunEvent_TypeToJSON(object: WorkflowRunEvent_Type): stri return "TYPE_ATTESTATION"; case WorkflowRunEvent_Type.TYPE_MATERIAL: return "TYPE_MATERIAL"; - case WorkflowRunEvent_Type.TYPE_PUSH: - return "TYPE_PUSH"; case WorkflowRunEvent_Type.UNRECOGNIZED: default: return "UNRECOGNIZED"; @@ -404,8 +397,16 @@ export interface WorkflowRunEvent_AttestationAttributes { remoteState: boolean; cliVersion: string; attestationDigest: string; - /** results of the attestation policies evaluated at init */ + /** + * results of the attestation policies: the ones evaluated at init on the start event, + * the ones of the stored attestation on the closing event + */ policies?: WorkflowRunEvent_PolicyCounts; + /** + * gated policies with violations in the stored attestation, empty when the check + * was bypassed. Set on the closing event only. + */ + blockingPolicies: string[]; } export interface WorkflowRunEvent_MaterialAttributes { @@ -419,13 +420,6 @@ export interface WorkflowRunEvent_MaterialAttributes { policies?: WorkflowRunEvent_PolicyCounts; } -export interface WorkflowRunEvent_PushAttributes { - /** results of the attestation policies evaluated at push */ - policies?: WorkflowRunEvent_PolicyCounts; - /** gated policies with violations that block the push */ - blockingPolicies: string[]; -} - export interface WorkflowRunEvent_PolicyCounts { evaluated: number; passed: number; @@ -2450,7 +2444,6 @@ function createBaseWorkflowRunEvent(): WorkflowRunEvent { message: "", attestation: undefined, material: undefined, - push: undefined, }; } @@ -2483,9 +2476,6 @@ export const WorkflowRunEvent = { if (message.material !== undefined) { WorkflowRunEvent_MaterialAttributes.encode(message.material, writer.uint32(90).fork()).ldelim(); } - if (message.push !== undefined) { - WorkflowRunEvent_PushAttributes.encode(message.push, writer.uint32(98).fork()).ldelim(); - } return writer; }, @@ -2559,13 +2549,6 @@ export const WorkflowRunEvent = { message.material = WorkflowRunEvent_MaterialAttributes.decode(reader, reader.uint32()); continue; - case 12: - if (tag !== 98) { - break; - } - - message.push = WorkflowRunEvent_PushAttributes.decode(reader, reader.uint32()); - continue; } if ((tag & 7) === 4 || tag === 0) { break; @@ -2588,7 +2571,6 @@ export const WorkflowRunEvent = { ? WorkflowRunEvent_AttestationAttributes.fromJSON(object.attestation) : undefined, material: isSet(object.material) ? WorkflowRunEvent_MaterialAttributes.fromJSON(object.material) : undefined, - push: isSet(object.push) ? WorkflowRunEvent_PushAttributes.fromJSON(object.push) : undefined, }; }, @@ -2606,8 +2588,6 @@ export const WorkflowRunEvent = { : undefined); message.material !== undefined && (obj.material = message.material ? WorkflowRunEvent_MaterialAttributes.toJSON(message.material) : undefined); - message.push !== undefined && - (obj.push = message.push ? WorkflowRunEvent_PushAttributes.toJSON(message.push) : undefined); return obj; }, @@ -2630,9 +2610,6 @@ export const WorkflowRunEvent = { message.material = (object.material !== undefined && object.material !== null) ? WorkflowRunEvent_MaterialAttributes.fromPartial(object.material) : undefined; - message.push = (object.push !== undefined && object.push !== null) - ? WorkflowRunEvent_PushAttributes.fromPartial(object.push) - : undefined; return message; }, }; @@ -2646,6 +2623,7 @@ function createBaseWorkflowRunEvent_AttestationAttributes(): WorkflowRunEvent_At cliVersion: "", attestationDigest: "", policies: undefined, + blockingPolicies: [], }; } @@ -2672,6 +2650,9 @@ export const WorkflowRunEvent_AttestationAttributes = { if (message.policies !== undefined) { WorkflowRunEvent_PolicyCounts.encode(message.policies, writer.uint32(58).fork()).ldelim(); } + for (const v of message.blockingPolicies) { + writer.uint32(66).string(v!); + } return writer; }, @@ -2731,6 +2712,13 @@ export const WorkflowRunEvent_AttestationAttributes = { message.policies = WorkflowRunEvent_PolicyCounts.decode(reader, reader.uint32()); continue; + case 8: + if (tag !== 66) { + break; + } + + message.blockingPolicies.push(reader.string()); + continue; } if ((tag & 7) === 4 || tag === 0) { break; @@ -2749,6 +2737,9 @@ export const WorkflowRunEvent_AttestationAttributes = { cliVersion: isSet(object.cliVersion) ? String(object.cliVersion) : "", attestationDigest: isSet(object.attestationDigest) ? String(object.attestationDigest) : "", policies: isSet(object.policies) ? WorkflowRunEvent_PolicyCounts.fromJSON(object.policies) : undefined, + blockingPolicies: Array.isArray(object?.blockingPolicies) + ? object.blockingPolicies.map((e: any) => String(e)) + : [], }; }, @@ -2762,6 +2753,11 @@ export const WorkflowRunEvent_AttestationAttributes = { message.attestationDigest !== undefined && (obj.attestationDigest = message.attestationDigest); message.policies !== undefined && (obj.policies = message.policies ? WorkflowRunEvent_PolicyCounts.toJSON(message.policies) : undefined); + if (message.blockingPolicies) { + obj.blockingPolicies = message.blockingPolicies.map((e) => e); + } else { + obj.blockingPolicies = []; + } return obj; }, @@ -2784,6 +2780,7 @@ export const WorkflowRunEvent_AttestationAttributes = { message.policies = (object.policies !== undefined && object.policies !== null) ? WorkflowRunEvent_PolicyCounts.fromPartial(object.policies) : undefined; + message.blockingPolicies = object.blockingPolicies?.map((e) => e) || []; return message; }, }; @@ -2939,88 +2936,6 @@ export const WorkflowRunEvent_MaterialAttributes = { }, }; -function createBaseWorkflowRunEvent_PushAttributes(): WorkflowRunEvent_PushAttributes { - return { policies: undefined, blockingPolicies: [] }; -} - -export const WorkflowRunEvent_PushAttributes = { - encode(message: WorkflowRunEvent_PushAttributes, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { - if (message.policies !== undefined) { - WorkflowRunEvent_PolicyCounts.encode(message.policies, writer.uint32(10).fork()).ldelim(); - } - for (const v of message.blockingPolicies) { - writer.uint32(18).string(v!); - } - return writer; - }, - - decode(input: _m0.Reader | Uint8Array, length?: number): WorkflowRunEvent_PushAttributes { - const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input); - let end = length === undefined ? reader.len : reader.pos + length; - const message = createBaseWorkflowRunEvent_PushAttributes(); - while (reader.pos < end) { - const tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - if (tag !== 10) { - break; - } - - message.policies = WorkflowRunEvent_PolicyCounts.decode(reader, reader.uint32()); - continue; - case 2: - if (tag !== 18) { - break; - } - - message.blockingPolicies.push(reader.string()); - continue; - } - if ((tag & 7) === 4 || tag === 0) { - break; - } - reader.skipType(tag & 7); - } - return message; - }, - - fromJSON(object: any): WorkflowRunEvent_PushAttributes { - return { - policies: isSet(object.policies) ? WorkflowRunEvent_PolicyCounts.fromJSON(object.policies) : undefined, - blockingPolicies: Array.isArray(object?.blockingPolicies) - ? object.blockingPolicies.map((e: any) => String(e)) - : [], - }; - }, - - toJSON(message: WorkflowRunEvent_PushAttributes): unknown { - const obj: any = {}; - message.policies !== undefined && - (obj.policies = message.policies ? WorkflowRunEvent_PolicyCounts.toJSON(message.policies) : undefined); - if (message.blockingPolicies) { - obj.blockingPolicies = message.blockingPolicies.map((e) => e); - } else { - obj.blockingPolicies = []; - } - return obj; - }, - - create, I>>(base?: I): WorkflowRunEvent_PushAttributes { - return WorkflowRunEvent_PushAttributes.fromPartial(base ?? {}); - }, - - fromPartial, I>>( - object: I, - ): WorkflowRunEvent_PushAttributes { - const message = createBaseWorkflowRunEvent_PushAttributes(); - message.policies = (object.policies !== undefined && object.policies !== null) - ? WorkflowRunEvent_PolicyCounts.fromPartial(object.policies) - : undefined; - message.blockingPolicies = object.blockingPolicies?.map((e) => e) || []; - return message; - }, -}; - function createBaseWorkflowRunEvent_PolicyCounts(): WorkflowRunEvent_PolicyCounts { return { evaluated: 0, passed: 0, violated: 0, skipped: 0, violatedPolicies: [] }; } 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 index 3e3126a61..2678fdfc1 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.AttestationAttributes.jsonschema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.AttestationAttributes.jsonschema.json @@ -7,6 +7,14 @@ "maxLength": 256, "type": "string" }, + "^(blocking_policies)$": { + "description": "gated policies with violations in the stored attestation, empty when the check\n was bypassed. Set on the closing event only.", + "items": { + "maxLength": 256, + "type": "string" + }, + "type": "array" + }, "^(cli_version)$": { "maxLength": 256, "type": "string" @@ -33,6 +41,14 @@ "maxLength": 256, "type": "string" }, + "blockingPolicies": { + "description": "gated policies with violations in the stored attestation, empty when the check\n was bypassed. Set on the closing event only.", + "items": { + "maxLength": 256, + "type": "string" + }, + "type": "array" + }, "cliVersion": { "maxLength": 256, "type": "string" @@ -48,7 +64,7 @@ }, "policies": { "$ref": "controlplane.v1.WorkflowRunEvent.PolicyCounts.jsonschema.json", - "description": "results of the attestation policies evaluated at init" + "description": "results of the attestation policies: the ones evaluated at init on the start event,\n the ones of the stored attestation on the closing event" }, "remoteState": { "type": "boolean" 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 index a18146e3b..81580f614 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.AttestationAttributes.schema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.AttestationAttributes.schema.json @@ -7,6 +7,14 @@ "maxLength": 256, "type": "string" }, + "^(blockingPolicies)$": { + "description": "gated policies with violations in the stored attestation, empty when the check\n was bypassed. Set on the closing event only.", + "items": { + "maxLength": 256, + "type": "string" + }, + "type": "array" + }, "^(cliVersion)$": { "maxLength": 256, "type": "string" @@ -33,6 +41,14 @@ "maxLength": 256, "type": "string" }, + "blocking_policies": { + "description": "gated policies with violations in the stored attestation, empty when the check\n was bypassed. Set on the closing event only.", + "items": { + "maxLength": 256, + "type": "string" + }, + "type": "array" + }, "cli_version": { "maxLength": 256, "type": "string" @@ -48,7 +64,7 @@ }, "policies": { "$ref": "controlplane.v1.WorkflowRunEvent.PolicyCounts.schema.json", - "description": "results of the attestation policies evaluated at init" + "description": "results of the attestation policies: the ones evaluated at init on the start event,\n the ones of the stored attestation on the closing event" }, "remote_state": { "type": "boolean" diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PushAttributes.jsonschema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PushAttributes.jsonschema.json deleted file mode 100644 index 99a74d48d..000000000 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PushAttributes.jsonschema.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "$id": "controlplane.v1.WorkflowRunEvent.PushAttributes.jsonschema.json", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "additionalProperties": false, - "patternProperties": { - "^(blocking_policies)$": { - "description": "gated policies with violations that block the push", - "items": { - "maxLength": 256, - "type": "string" - }, - "type": "array" - } - }, - "properties": { - "blockingPolicies": { - "description": "gated policies with violations that block the push", - "items": { - "maxLength": 256, - "type": "string" - }, - "type": "array" - }, - "policies": { - "$ref": "controlplane.v1.WorkflowRunEvent.PolicyCounts.jsonschema.json", - "description": "results of the attestation policies evaluated at push" - } - }, - "title": "Push Attributes", - "type": "object" -} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PushAttributes.schema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PushAttributes.schema.json deleted file mode 100644 index 68a5edbd7..000000000 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.PushAttributes.schema.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "$id": "controlplane.v1.WorkflowRunEvent.PushAttributes.schema.json", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "additionalProperties": false, - "patternProperties": { - "^(blockingPolicies)$": { - "description": "gated policies with violations that block the push", - "items": { - "maxLength": 256, - "type": "string" - }, - "type": "array" - } - }, - "properties": { - "blocking_policies": { - "description": "gated policies with violations that block the push", - "items": { - "maxLength": 256, - "type": "string" - }, - "type": "array" - }, - "policies": { - "$ref": "controlplane.v1.WorkflowRunEvent.PolicyCounts.schema.json", - "description": "results of the attestation policies evaluated at push" - } - }, - "title": "Push Attributes", - "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 index d43b80e84..0a9901f11 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.jsonschema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.jsonschema.json @@ -33,9 +33,6 @@ "maxLength": 1024, "type": "string" }, - "push": { - "$ref": "controlplane.v1.WorkflowRunEvent.PushAttributes.jsonschema.json" - }, "source": { "anyOf": [ { @@ -80,8 +77,7 @@ "enum": [ "TYPE_UNSPECIFIED", "TYPE_ATTESTATION", - "TYPE_MATERIAL", - "TYPE_PUSH" + "TYPE_MATERIAL" ], "title": "Type", "type": "string" diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.schema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.schema.json index 5187d53f1..0f335e9c3 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.schema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.schema.json @@ -33,9 +33,6 @@ "maxLength": 1024, "type": "string" }, - "push": { - "$ref": "controlplane.v1.WorkflowRunEvent.PushAttributes.schema.json" - }, "source": { "anyOf": [ { @@ -80,8 +77,7 @@ "enum": [ "TYPE_UNSPECIFIED", "TYPE_ATTESTATION", - "TYPE_MATERIAL", - "TYPE_PUSH" + "TYPE_MATERIAL" ], "title": "Type", "type": "string" diff --git a/app/controlplane/internal/service/attestation.go b/app/controlplane/internal/service/attestation.go index c1030f1a9..5438974c7 100644 --- a/app/controlplane/internal/service/attestation.go +++ b/app/controlplane/internal/service/attestation.go @@ -423,7 +423,14 @@ func (s *AttestationService) storeAttestation(ctx context.Context, bundle []byte } } - if err := s.wrUseCase.MarkAsFinished(ctx, workflowRunID, biz.WorkflowRunSuccess, ""); err != nil { + // The closing event of the run shows the policy results of the stored attestation. + // They are informational, so a predicate that can't be read does not fail the store. + var policyResults *biz.WorkflowRunPolicyResults + if predicate, err := chainloop.ExtractPredicate(dsseEnv); err == nil { + policyResults = biz.PolicyResultsFromPredicate(predicate) + } + + if err := s.wrUseCase.MarkAsFinished(ctx, workflowRunID, biz.WorkflowRunSuccess, "", biz.WithPolicyResults(policyResults)); err != nil { return nil, handleUseCaseErr(ctx, err, s.log) } diff --git a/app/controlplane/internal/service/workflowrun.go b/app/controlplane/internal/service/workflowrun.go index 08ace5fec..4921a175a 100644 --- a/app/controlplane/internal/service/workflowrun.go +++ b/app/controlplane/internal/service/workflowrun.go @@ -638,12 +638,10 @@ var ( pbToBizRunEventType = map[pb.WorkflowRunEvent_Type]biz.WorkflowRunEventType{ pb.WorkflowRunEvent_TYPE_ATTESTATION: biz.WorkflowRunEventTypeAttestation, pb.WorkflowRunEvent_TYPE_MATERIAL: biz.WorkflowRunEventTypeMaterial, - pb.WorkflowRunEvent_TYPE_PUSH: biz.WorkflowRunEventTypePush, } bizToPbRunEventType = map[biz.WorkflowRunEventType]pb.WorkflowRunEvent_Type{ biz.WorkflowRunEventTypeAttestation: pb.WorkflowRunEvent_TYPE_ATTESTATION, biz.WorkflowRunEventTypeMaterial: pb.WorkflowRunEvent_TYPE_MATERIAL, - biz.WorkflowRunEventTypePush: pb.WorkflowRunEvent_TYPE_PUSH, } pbToBizRunEventStatus = map[pb.WorkflowRunEvent_Status]biz.WorkflowRunEventStatus{ pb.WorkflowRunEvent_STATUS_STARTED: biz.WorkflowRunEventStatusStarted, @@ -695,6 +693,7 @@ func pbWorkflowRunEventToBiz(in *pb.WorkflowRunEvent) (*biz.WorkflowRunEvent, er CLIVersion: a.GetCliVersion(), AttestationDigest: a.GetAttestationDigest(), Policies: pbPolicyCountsToBiz(a.GetPolicies()), + BlockingPolicies: a.GetBlockingPolicies(), }} case *pb.WorkflowRunEvent_Material: m := attrs.Material @@ -707,12 +706,6 @@ func pbWorkflowRunEventToBiz(in *pb.WorkflowRunEvent) (*biz.WorkflowRunEvent, er AddedByCollector: m.GetAddedByCollector(), Policies: pbPolicyCountsToBiz(m.GetPolicies()), }} - case *pb.WorkflowRunEvent_Push: - p := attrs.Push - out.Attributes = &biz.WorkflowRunEventAttributes{Push: &biz.WorkflowRunEventPushAttributes{ - Policies: pbPolicyCountsToBiz(p.GetPolicies()), - BlockingPolicies: p.GetBlockingPolicies(), - }} } return out, nil @@ -773,6 +766,7 @@ func bizWorkflowRunEventToPb(in *biz.WorkflowRunEvent) *pb.WorkflowRunEvent { CliVersion: a.CLIVersion, AttestationDigest: a.AttestationDigest, Policies: bizPolicyCountsToPb(a.Policies), + BlockingPolicies: a.BlockingPolicies, }} case attrs.Material != nil: m := attrs.Material @@ -785,12 +779,6 @@ func bizWorkflowRunEventToPb(in *biz.WorkflowRunEvent) *pb.WorkflowRunEvent { AddedByCollector: m.AddedByCollector, Policies: bizPolicyCountsToPb(m.Policies), }} - case attrs.Push != nil: - p := attrs.Push - out.Attributes = &pb.WorkflowRunEvent_Push{Push: &pb.WorkflowRunEvent_PushAttributes{ - Policies: bizPolicyCountsToPb(p.Policies), - BlockingPolicies: p.BlockingPolicies, - }} } return out diff --git a/app/controlplane/internal/service/workflowrunevent_integration_test.go b/app/controlplane/internal/service/workflowrunevent_integration_test.go index ae7f5a0d8..c0d6fc2e2 100644 --- a/app/controlplane/internal/service/workflowrunevent_integration_test.go +++ b/app/controlplane/internal/service/workflowrunevent_integration_test.go @@ -326,7 +326,7 @@ func (s *workflowRunEventRBACIntegrationSuite) TestRecordEventValidation() { { name: "attributes that do not match the type", event: &pb.WorkflowRunEvent{ - Type: pb.WorkflowRunEvent_TYPE_PUSH, Key: "chainloop.push", Status: pb.WorkflowRunEvent_STATUS_SUCCEEDED, + Type: pb.WorkflowRunEvent_TYPE_ATTESTATION, Key: "chainloop.attestation", Status: pb.WorkflowRunEvent_STATUS_SUCCEEDED, Attributes: &pb.WorkflowRunEvent_Material{Material: &pb.WorkflowRunEvent_MaterialAttributes{Name: sbomMaterial}}, }, }, diff --git a/app/controlplane/pkg/biz/mocks/WorkflowRunRepo.go b/app/controlplane/pkg/biz/mocks/WorkflowRunRepo.go index c7b4a51cb..f617c1864 100644 --- a/app/controlplane/pkg/biz/mocks/WorkflowRunRepo.go +++ b/app/controlplane/pkg/biz/mocks/WorkflowRunRepo.go @@ -21,10 +21,19 @@ func NewWorkflowRunRepo(t interface { mock.TestingT Cleanup(func()) }) *WorkflowRunRepo { + if helper, ok := t.(interface{ Helper() }); ok { + helper.Helper() + } + mock := &WorkflowRunRepo{} mock.Mock.Test(t) - t.Cleanup(func() { mock.AssertExpectations(t) }) + t.Cleanup(func() { + if helper, ok := t.(interface{ Helper() }); ok { + helper.Helper() + } + mock.AssertExpectations(t) + }) return mock } @@ -78,7 +87,7 @@ type WorkflowRunRepo_Create_Call struct { // Create is a helper method to define mock.On call // - ctx context.Context // - opts *biz.WorkflowRunRepoCreateOpts -func (_e *WorkflowRunRepo_Expecter) Create(ctx interface{}, opts interface{}) *WorkflowRunRepo_Create_Call { +func (_e *WorkflowRunRepo_Expecter) Create(ctx any, opts any) *WorkflowRunRepo_Create_Call { return &WorkflowRunRepo_Create_Call{Call: _e.mock.On("Create", ctx, opts)} } @@ -135,7 +144,7 @@ type WorkflowRunRepo_Expire_Call struct { // Expire is a helper method to define mock.On call // - ctx context.Context // - id uuid.UUID -func (_e *WorkflowRunRepo_Expecter) Expire(ctx interface{}, id interface{}) *WorkflowRunRepo_Expire_Call { +func (_e *WorkflowRunRepo_Expecter) Expire(ctx any, id any) *WorkflowRunRepo_Expire_Call { return &WorkflowRunRepo_Expire_Call{Call: _e.mock.On("Expire", ctx, id)} } @@ -203,7 +212,7 @@ type WorkflowRunRepo_FindByAttestationDigest_Call struct { // FindByAttestationDigest is a helper method to define mock.On call // - ctx context.Context // - digest string -func (_e *WorkflowRunRepo_Expecter) FindByAttestationDigest(ctx interface{}, digest interface{}) *WorkflowRunRepo_FindByAttestationDigest_Call { +func (_e *WorkflowRunRepo_Expecter) FindByAttestationDigest(ctx any, digest any) *WorkflowRunRepo_FindByAttestationDigest_Call { return &WorkflowRunRepo_FindByAttestationDigest_Call{Call: _e.mock.On("FindByAttestationDigest", ctx, digest)} } @@ -271,7 +280,7 @@ type WorkflowRunRepo_FindByID_Call struct { // FindByID is a helper method to define mock.On call // - ctx context.Context // - ID uuid.UUID -func (_e *WorkflowRunRepo_Expecter) FindByID(ctx interface{}, ID interface{}) *WorkflowRunRepo_FindByID_Call { +func (_e *WorkflowRunRepo_Expecter) FindByID(ctx any, ID any) *WorkflowRunRepo_FindByID_Call { return &WorkflowRunRepo_FindByID_Call{Call: _e.mock.On("FindByID", ctx, ID)} } @@ -340,7 +349,7 @@ type WorkflowRunRepo_FindByIDInOrg_Call struct { // - ctx context.Context // - orgID uuid.UUID // - ID uuid.UUID -func (_e *WorkflowRunRepo_Expecter) FindByIDInOrg(ctx interface{}, orgID interface{}, ID interface{}) *WorkflowRunRepo_FindByIDInOrg_Call { +func (_e *WorkflowRunRepo_Expecter) FindByIDInOrg(ctx any, orgID any, ID any) *WorkflowRunRepo_FindByIDInOrg_Call { return &WorkflowRunRepo_FindByIDInOrg_Call{Call: _e.mock.On("FindByIDInOrg", ctx, orgID, ID)} } @@ -413,7 +422,7 @@ type WorkflowRunRepo_GetBundle_Call struct { // GetBundle is a helper method to define mock.On call // - ctx context.Context // - wrID uuid.UUID -func (_e *WorkflowRunRepo_Expecter) GetBundle(ctx interface{}, wrID interface{}) *WorkflowRunRepo_GetBundle_Call { +func (_e *WorkflowRunRepo_Expecter) GetBundle(ctx any, wrID any) *WorkflowRunRepo_GetBundle_Call { return &WorkflowRunRepo_GetBundle_Call{Call: _e.mock.On("GetBundle", ctx, wrID)} } @@ -489,7 +498,7 @@ type WorkflowRunRepo_List_Call struct { // - orgID uuid.UUID // - f *biz.RunListFilters // - p *pagination.CursorOptions -func (_e *WorkflowRunRepo_Expecter) List(ctx interface{}, orgID interface{}, f interface{}, p interface{}) *WorkflowRunRepo_List_Call { +func (_e *WorkflowRunRepo_Expecter) List(ctx any, orgID any, f any, p any) *WorkflowRunRepo_List_Call { return &WorkflowRunRepo_List_Call{Call: _e.mock.On("List", ctx, orgID, f, p)} } @@ -568,7 +577,7 @@ type WorkflowRunRepo_ListNotFinishedOlderThan_Call struct { // - ctx context.Context // - olderThan time.Time // - limit int -func (_e *WorkflowRunRepo_Expecter) ListNotFinishedOlderThan(ctx interface{}, olderThan interface{}, limit interface{}) *WorkflowRunRepo_ListNotFinishedOlderThan_Call { +func (_e *WorkflowRunRepo_Expecter) ListNotFinishedOlderThan(ctx any, olderThan any, limit any) *WorkflowRunRepo_ListNotFinishedOlderThan_Call { return &WorkflowRunRepo_ListNotFinishedOlderThan_Call{Call: _e.mock.On("ListNotFinishedOlderThan", ctx, olderThan, limit)} } @@ -606,16 +615,16 @@ func (_c *WorkflowRunRepo_ListNotFinishedOlderThan_Call) RunAndReturn(run func(c } // MarkAsFinished provides a mock function for the type WorkflowRunRepo -func (_mock *WorkflowRunRepo) MarkAsFinished(ctx context.Context, ID uuid.UUID, status biz.WorkflowRunStatus, reason string) error { - ret := _mock.Called(ctx, ID, status, reason) +func (_mock *WorkflowRunRepo) MarkAsFinished(ctx context.Context, ID uuid.UUID, status biz.WorkflowRunStatus, reason string, policies *biz.WorkflowRunPolicyResults) error { + ret := _mock.Called(ctx, ID, status, reason, policies) if len(ret) == 0 { panic("no return value specified for MarkAsFinished") } var r0 error - if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, biz.WorkflowRunStatus, string) error); ok { - r0 = returnFunc(ctx, ID, status, reason) + if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, biz.WorkflowRunStatus, string, *biz.WorkflowRunPolicyResults) error); ok { + r0 = returnFunc(ctx, ID, status, reason, policies) } else { r0 = ret.Error(0) } @@ -632,11 +641,12 @@ type WorkflowRunRepo_MarkAsFinished_Call struct { // - ID uuid.UUID // - status biz.WorkflowRunStatus // - reason string -func (_e *WorkflowRunRepo_Expecter) MarkAsFinished(ctx interface{}, ID interface{}, status interface{}, reason interface{}) *WorkflowRunRepo_MarkAsFinished_Call { - return &WorkflowRunRepo_MarkAsFinished_Call{Call: _e.mock.On("MarkAsFinished", ctx, ID, status, reason)} +// - policies *biz.WorkflowRunPolicyResults +func (_e *WorkflowRunRepo_Expecter) MarkAsFinished(ctx any, ID any, status any, reason any, policies any) *WorkflowRunRepo_MarkAsFinished_Call { + return &WorkflowRunRepo_MarkAsFinished_Call{Call: _e.mock.On("MarkAsFinished", ctx, ID, status, reason, policies)} } -func (_c *WorkflowRunRepo_MarkAsFinished_Call) Run(run func(ctx context.Context, ID uuid.UUID, status biz.WorkflowRunStatus, reason string)) *WorkflowRunRepo_MarkAsFinished_Call { +func (_c *WorkflowRunRepo_MarkAsFinished_Call) Run(run func(ctx context.Context, ID uuid.UUID, status biz.WorkflowRunStatus, reason string, policies *biz.WorkflowRunPolicyResults)) *WorkflowRunRepo_MarkAsFinished_Call { _c.Call.Run(func(args mock.Arguments) { var arg0 context.Context if args[0] != nil { @@ -654,11 +664,16 @@ func (_c *WorkflowRunRepo_MarkAsFinished_Call) Run(run func(ctx context.Context, if args[3] != nil { arg3 = args[3].(string) } + var arg4 *biz.WorkflowRunPolicyResults + if args[4] != nil { + arg4 = args[4].(*biz.WorkflowRunPolicyResults) + } run( arg0, arg1, arg2, arg3, + arg4, ) }) return _c @@ -669,7 +684,7 @@ func (_c *WorkflowRunRepo_MarkAsFinished_Call) Return(err error) *WorkflowRunRep return _c } -func (_c *WorkflowRunRepo_MarkAsFinished_Call) RunAndReturn(run func(ctx context.Context, ID uuid.UUID, status biz.WorkflowRunStatus, reason string) error) *WorkflowRunRepo_MarkAsFinished_Call { +func (_c *WorkflowRunRepo_MarkAsFinished_Call) RunAndReturn(run func(ctx context.Context, ID uuid.UUID, status biz.WorkflowRunStatus, reason string, policies *biz.WorkflowRunPolicyResults) error) *WorkflowRunRepo_MarkAsFinished_Call { _c.Call.Return(run) return _c } @@ -702,7 +717,7 @@ type WorkflowRunRepo_SaveAttestationBundle_Call struct { // - digest string // - bundle []byte // - blockReleasedVersions bool -func (_e *WorkflowRunRepo_Expecter) SaveAttestationBundle(ctx interface{}, ID interface{}, digest interface{}, bundle interface{}, blockReleasedVersions interface{}) *WorkflowRunRepo_SaveAttestationBundle_Call { +func (_e *WorkflowRunRepo_Expecter) SaveAttestationBundle(ctx any, ID any, digest any, bundle any, blockReleasedVersions any) *WorkflowRunRepo_SaveAttestationBundle_Call { return &WorkflowRunRepo_SaveAttestationBundle_Call{Call: _e.mock.On("SaveAttestationBundle", ctx, ID, digest, bundle, blockReleasedVersions)} } @@ -776,7 +791,7 @@ type WorkflowRunRepo_SaveAttestationDigest_Call struct { // - ID uuid.UUID // - digest string // - blockReleasedVersions bool -func (_e *WorkflowRunRepo_Expecter) SaveAttestationDigest(ctx interface{}, ID interface{}, digest interface{}, blockReleasedVersions interface{}) *WorkflowRunRepo_SaveAttestationDigest_Call { +func (_e *WorkflowRunRepo_Expecter) SaveAttestationDigest(ctx any, ID any, digest any, blockReleasedVersions any) *WorkflowRunRepo_SaveAttestationDigest_Call { return &WorkflowRunRepo_SaveAttestationDigest_Call{Call: _e.mock.On("SaveAttestationDigest", ctx, ID, digest, blockReleasedVersions)} } @@ -844,7 +859,7 @@ type WorkflowRunRepo_UpdatePolicyStatus_Call struct { // - ctx context.Context // - ID uuid.UUID // - summary *chainloop.PolicyStatusSummary -func (_e *WorkflowRunRepo_Expecter) UpdatePolicyStatus(ctx interface{}, ID interface{}, summary interface{}) *WorkflowRunRepo_UpdatePolicyStatus_Call { +func (_e *WorkflowRunRepo_Expecter) UpdatePolicyStatus(ctx any, ID any, summary any) *WorkflowRunRepo_UpdatePolicyStatus_Call { return &WorkflowRunRepo_UpdatePolicyStatus_Call{Call: _e.mock.On("UpdatePolicyStatus", ctx, ID, summary)} } diff --git a/app/controlplane/pkg/biz/workflowrun.go b/app/controlplane/pkg/biz/workflowrun.go index 53c163cbb..d423fbc02 100644 --- a/app/controlplane/pkg/biz/workflowrun.go +++ b/app/controlplane/pkg/biz/workflowrun.go @@ -104,7 +104,9 @@ type WorkflowRunRepo interface { FindByID(ctx context.Context, ID uuid.UUID) (*WorkflowRun, error) FindByAttestationDigest(ctx context.Context, digest string) (*WorkflowRun, error) FindByIDInOrg(ctx context.Context, orgID, ID uuid.UUID) (*WorkflowRun, error) - MarkAsFinished(ctx context.Context, ID uuid.UUID, status WorkflowRunStatus, reason string) error + // MarkAsFinished sets the final status of the run and closes its timeline. The policy + // results, when set, go on the closing event of a stored attestation. + MarkAsFinished(ctx context.Context, ID uuid.UUID, status WorkflowRunStatus, reason string, policies *WorkflowRunPolicyResults) error // SaveAttestationBundle persists the digest and bundle. When // blockReleasedVersions is set it transactionally rejects the write if the // run's project version is already released (prerelease == false), locking @@ -433,7 +435,18 @@ func (uc *WorkflowRunUseCase) ExistsInWorkflow(ctx context.Context, workflowID, return res != nil && res.Workflow.ID.String() == workflowID, nil } -func (uc *WorkflowRunUseCase) MarkAsFinished(ctx context.Context, id string, status WorkflowRunStatus, reason string) error { +type MarkAsFinishedOpt func(*markAsFinishedOpts) + +type markAsFinishedOpts struct { + policies *WorkflowRunPolicyResults +} + +// WithPolicyResults sets the policy results of the stored attestation on the closing event +func WithPolicyResults(p *WorkflowRunPolicyResults) MarkAsFinishedOpt { + return func(o *markAsFinishedOpts) { o.policies = p } +} + +func (uc *WorkflowRunUseCase) MarkAsFinished(ctx context.Context, id string, status WorkflowRunStatus, reason string, opts ...MarkAsFinishedOpt) error { ctx, span := otelx.Start(ctx, workflowRunTracer, "WorkflowRunUseCase.MarkAsFinished") defer span.End() @@ -442,7 +455,12 @@ func (uc *WorkflowRunUseCase) MarkAsFinished(ctx context.Context, id string, sta return NewErrInvalidUUID(err) } - return uc.wfRunRepo.MarkAsFinished(ctx, runID, status, reason) + o := &markAsFinishedOpts{} + for _, opt := range opts { + opt(o) + } + + return uc.wfRunRepo.MarkAsFinished(ctx, runID, status, reason, o.policies) } // SaveAttestationOption customises how SaveAttestation persists the bundle. diff --git a/app/controlplane/pkg/biz/workflowrun_test.go b/app/controlplane/pkg/biz/workflowrun_test.go index d38f8fc9b..d75e24b72 100644 --- a/app/controlplane/pkg/biz/workflowrun_test.go +++ b/app/controlplane/pkg/biz/workflowrun_test.go @@ -175,7 +175,7 @@ func (s *workflowrunTestSuite) TestMarkAsFinished() { uuid, err := uuid.Parse(tc.id) require.NoError(t, err) - s.repo.On("MarkAsFinished", mock.Anything, uuid, tc.status, tc.reason).Return(nil) + s.repo.On("MarkAsFinished", mock.Anything, uuid, tc.status, tc.reason, (*biz.WorkflowRunPolicyResults)(nil)).Return(nil) } // s.repo.On("MarkAsFinished", s.ctx, id, tc.wantStatus, tc.reason).Return(tc.err) diff --git a/app/controlplane/pkg/biz/workflowrunevent.go b/app/controlplane/pkg/biz/workflowrunevent.go index 1efa58100..81eb7072d 100644 --- a/app/controlplane/pkg/biz/workflowrunevent.go +++ b/app/controlplane/pkg/biz/workflowrunevent.go @@ -23,6 +23,7 @@ import ( "time" "unicode/utf8" + "github.com/chainloop-dev/chainloop/pkg/attestation/renderer/chainloop" "github.com/chainloop-dev/chainloop/pkg/otelx" "github.com/go-kratos/kratos/v2/log" "github.com/google/uuid" @@ -41,6 +42,10 @@ const ( workflowRunEventKeyPrefix = "chainloop." // workflowRunEventExpiredMessage is the message of the closing event of an expired run workflowRunEventExpiredMessage = "expired" + // maxWorkflowRunEventStringBytes and maxWorkflowRunEventPolicyNames are the API bounds of + // an attribute string and of a list of policy names + maxWorkflowRunEventStringBytes = 256 + maxWorkflowRunEventPolicyNames = 100 ) type WorkflowRunEventSource string @@ -60,12 +65,11 @@ type WorkflowRunEventType string const ( WorkflowRunEventTypeAttestation WorkflowRunEventType = "attestation" WorkflowRunEventTypeMaterial WorkflowRunEventType = "material" - WorkflowRunEventTypePush WorkflowRunEventType = "push" ) // Values implements the ent enum interface func (WorkflowRunEventType) Values() []string { - return []string{string(WorkflowRunEventTypeAttestation), string(WorkflowRunEventTypeMaterial), string(WorkflowRunEventTypePush)} + return []string{string(WorkflowRunEventTypeAttestation), string(WorkflowRunEventTypeMaterial)} } type WorkflowRunEventStatus string @@ -106,7 +110,6 @@ type WorkflowRunEvent struct { type WorkflowRunEventAttributes struct { Attestation *WorkflowRunEventAttestationAttributes `json:"attestation,omitempty"` Material *WorkflowRunEventMaterialAttributes `json:"material,omitempty"` - Push *WorkflowRunEventPushAttributes `json:"push,omitempty"` } type WorkflowRunEventAttestationAttributes struct { @@ -116,8 +119,12 @@ type WorkflowRunEventAttestationAttributes struct { 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 + // Results of the attestation policies: the ones evaluated at init on the start event, + // the ones of the stored attestation on the closing event Policies *WorkflowRunEventPolicyCounts `json:"policies,omitempty"` + // Gated policies with violations in the stored attestation, empty when the check was + // bypassed. Set on the closing event only. + BlockingPolicies []string `json:"blocking_policies,omitempty"` } type WorkflowRunEventMaterialAttributes struct { @@ -130,13 +137,6 @@ type WorkflowRunEventMaterialAttributes struct { Policies *WorkflowRunEventPolicyCounts `json:"policies,omitempty"` } -type WorkflowRunEventPushAttributes struct { - // Results of the attestation policies evaluated at push - Policies *WorkflowRunEventPolicyCounts `json:"policies,omitempty"` - // Gated policies with violations that block the push - BlockingPolicies []string `json:"blocking_policies,omitempty"` -} - type WorkflowRunEventPolicyCounts struct { Evaluated int32 `json:"evaluated,omitempty"` Passed int32 `json:"passed,omitempty"` @@ -208,9 +208,6 @@ func validateWorkflowRunEvent(ev *WorkflowRunEvent) error { if attrs.Material != nil { set = append(set, WorkflowRunEventTypeMaterial) } - if attrs.Push != nil { - set = append(set, WorkflowRunEventTypePush) - } } if !slices.Contains(ev.Type.Values(), string(ev.Type)) { @@ -266,9 +263,73 @@ func (uc *WorkflowRunEventUseCase) DeleteOlderThan(ctx context.Context, t time.T } } +// WorkflowRunPolicyResults are the policy results of a stored attestation. The closing +// event of its run carries them. +type WorkflowRunPolicyResults struct { + // Results of the attestation policies + Policies *WorkflowRunEventPolicyCounts + // Gated policies with violations, empty when the check was bypassed + BlockingPolicies []string +} + +// PolicyResultsFromPredicate returns the policy results of a stored attestation. It returns +// nil when the predicate does not hold its evaluations, for example when they are in the CAS. +func PolicyResultsFromPredicate(p chainloop.NormalizablePredicate) *WorkflowRunPolicyResults { + if p == nil || len(p.GetPolicyEvaluations()) == 0 { + return nil + } + + res := &WorkflowRunPolicyResults{Policies: &WorkflowRunEventPolicyCounts{}} + for key, evs := range p.GetPolicyEvaluations() { + for _, ev := range evs { + violated := slices.ContainsFunc(ev.Violations, func(v *chainloop.PolicyViolation) bool { return !v.Suppress }) + if violated && ev.Gate { + res.BlockingPolicies = append(res.BlockingPolicies, truncateBytes(ev.Name, maxWorkflowRunEventStringBytes)) + } + + // The materials have their own events + if key != chainloop.AttPolicyEvaluation { + continue + } + + counts := res.Policies + counts.Evaluated++ + switch { + case ev.Skipped: + counts.Skipped++ + case violated: + counts.Violated++ + if len(counts.ViolatedPolicies) < maxWorkflowRunEventPolicyNames { + counts.ViolatedPolicies = append(counts.ViolatedPolicies, truncateBytes(ev.Name, maxWorkflowRunEventStringBytes)) + } + default: + counts.Passed++ + } + } + } + + if status := p.GetPolicyEvaluationStatus(); status != nil && status.Bypassed { + res.BlockingPolicies = nil + } + + // A policy attached to several materials is one blocking policy + slices.Sort(res.BlockingPolicies) + res.BlockingPolicies = slices.Compact(res.BlockingPolicies) + if len(res.BlockingPolicies) > maxWorkflowRunEventPolicyNames { + res.BlockingPolicies = res.BlockingPolicies[:maxWorkflowRunEventPolicyNames] + } + + if res.Policies.Evaluated == 0 { + res.Policies = nil + } + + return res +} + // 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 { +// The policy results are set only on the event of a stored attestation. +func ClosingWorkflowRunEvent(runID uuid.UUID, runStatus WorkflowRunStatus, reason, attestationDigest string, policies *WorkflowRunPolicyResults) *WorkflowRunEvent { ev := &WorkflowRunEvent{ WorkflowRunID: runID, Source: WorkflowRunEventSourceControlPlane, @@ -280,10 +341,13 @@ func ClosingWorkflowRunEvent(runID uuid.UUID, runStatus WorkflowRunStatus, reaso case WorkflowRunSuccess: // Automatic events that succeed have no message ev.Status = WorkflowRunEventStatusSucceeded - if attestationDigest != "" { - ev.Attributes = &WorkflowRunEventAttributes{ - Attestation: &WorkflowRunEventAttestationAttributes{AttestationDigest: attestationDigest}, - } + attrs := &WorkflowRunEventAttestationAttributes{AttestationDigest: attestationDigest} + if policies != nil { + attrs.Policies = policies.Policies + attrs.BlockingPolicies = policies.BlockingPolicies + } + if attrs.AttestationDigest != "" || attrs.Policies != nil || len(attrs.BlockingPolicies) > 0 { + ev.Attributes = &WorkflowRunEventAttributes{Attestation: attrs} } case WorkflowRunCancelled: ev.Status = WorkflowRunEventStatusCanceled diff --git a/app/controlplane/pkg/biz/workflowrunevent_test.go b/app/controlplane/pkg/biz/workflowrunevent_test.go index 5a5237103..fec4af294 100644 --- a/app/controlplane/pkg/biz/workflowrunevent_test.go +++ b/app/controlplane/pkg/biz/workflowrunevent_test.go @@ -20,11 +20,70 @@ import ( "testing" "unicode/utf8" + "github.com/chainloop-dev/chainloop/pkg/attestation/renderer/chainloop" "github.com/google/uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) +func TestPolicyResultsFromPredicate(t *testing.T) { + violation := []*chainloop.PolicyViolation{{Message: "bad"}} + suppressed := []*chainloop.PolicyViolation{{Message: "accepted", Suppress: true}} + evaluations := map[string][]*chainloop.PolicyEvaluation{ + chainloop.AttPolicyEvaluation: { + {Name: "att-passed"}, + {Name: "att-skipped", Skipped: true}, + {Name: "att-violated", Violations: violation}, + {Name: "att-suppressed", Violations: suppressed}, + {Name: "att-gate", Gate: true, Violations: violation}, + }, + "sbom": {{Name: "sbom-gate", Gate: true, Violations: violation}, {Name: "sbom-advisory", Violations: violation}}, + "image": {{Name: "sbom-gate", Gate: true, Violations: violation}, {Name: "suppressed-gate", Gate: true, Violations: suppressed}}, + } + + testCases := []struct { + name string + predicate chainloop.NormalizablePredicate + want *WorkflowRunPolicyResults + }{ + { + name: "attestation policy counts and the gates of all the policies", + predicate: &chainloop.ProvenancePredicateV02{PolicyEvaluations: evaluations}, + want: &WorkflowRunPolicyResults{ + Policies: &WorkflowRunEventPolicyCounts{Evaluated: 5, Passed: 2, Violated: 2, Skipped: 1, ViolatedPolicies: []string{"att-violated", "att-gate"}}, + BlockingPolicies: []string{"att-gate", "sbom-gate"}, + }, + }, + { + name: "bypassed check has no blocking policies", + predicate: &chainloop.ProvenancePredicateV02{PolicyEvaluations: evaluations, PolicyBlockBypassEnabled: true}, + want: &WorkflowRunPolicyResults{ + Policies: &WorkflowRunEventPolicyCounts{Evaluated: 5, Passed: 2, Violated: 2, Skipped: 1, ViolatedPolicies: []string{"att-violated", "att-gate"}}, + }, + }, + { + name: "material policies only", + predicate: &chainloop.ProvenancePredicateV02{PolicyEvaluations: map[string][]*chainloop.PolicyEvaluation{ + "sbom": {{Name: "sbom-advisory"}}, + }}, + want: &WorkflowRunPolicyResults{}, + }, + { + name: "evaluations not in the predicate", + predicate: &chainloop.ProvenancePredicateV02{}, + }, + { + name: "no predicate", + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, PolicyResultsFromPredicate(tc.predicate)) + }) + } +} + const ( sbomKey = "chainloop.material.sbom" shortText = "abc" @@ -32,7 +91,7 @@ const ( func TestValidateWorkflowRunEvent(t *testing.T) { material := &WorkflowRunEventAttributes{Material: &WorkflowRunEventMaterialAttributes{Name: "sbom"}} - push := &WorkflowRunEventAttributes{Push: &WorkflowRunEventPushAttributes{BlockingPolicies: []string{"gate"}}} + attestation := &WorkflowRunEventAttributes{Attestation: &WorkflowRunEventAttestationAttributes{BlockingPolicies: []string{"gate"}}} testCases := []struct { name string @@ -45,7 +104,7 @@ func TestValidateWorkflowRunEvent(t *testing.T) { }, { name: "event with no attributes", - event: &WorkflowRunEvent{Type: WorkflowRunEventTypeAttestation, Key: "chainloop.push"}, + event: &WorkflowRunEvent{Type: WorkflowRunEventTypeAttestation, Key: WorkflowRunEventKeyAttestation}, }, { name: "key that is not automatic", @@ -54,7 +113,7 @@ func TestValidateWorkflowRunEvent(t *testing.T) { }, { name: "attributes of another type", - event: &WorkflowRunEvent{Type: WorkflowRunEventTypeMaterial, Key: sbomKey, Attributes: push}, + event: &WorkflowRunEvent{Type: WorkflowRunEventTypeMaterial, Key: sbomKey, Attributes: attestation}, wantErr: "do not match", }, { @@ -92,12 +151,22 @@ func TestClosingWorkflowRunEvent(t *testing.T) { status WorkflowRunStatus reason string digest string + policies *WorkflowRunPolicyResults wantNil bool wantStatus WorkflowRunEventStatus wantMessage string - wantDigest string + wantAttrs *WorkflowRunEventAttestationAttributes }{ - {name: "store", status: WorkflowRunSuccess, reason: "ignored", digest: "sha256:abc", wantStatus: WorkflowRunEventStatusSucceeded, wantDigest: "sha256:abc"}, + {name: "store", status: WorkflowRunSuccess, reason: "ignored", digest: "sha256:abc", wantStatus: WorkflowRunEventStatusSucceeded, + wantAttrs: &WorkflowRunEventAttestationAttributes{AttestationDigest: "sha256:abc"}}, + {name: "store with policy results", status: WorkflowRunSuccess, digest: "sha256:abc", + policies: &WorkflowRunPolicyResults{Policies: &WorkflowRunEventPolicyCounts{Evaluated: 1, Violated: 1}, BlockingPolicies: []string{"gate"}}, + wantStatus: WorkflowRunEventStatusSucceeded, + wantAttrs: &WorkflowRunEventAttestationAttributes{AttestationDigest: "sha256:abc", + Policies: &WorkflowRunEventPolicyCounts{Evaluated: 1, Violated: 1}, BlockingPolicies: []string{"gate"}}}, + {name: "policy results only on a stored attestation", status: WorkflowRunError, reason: "build failed", + policies: &WorkflowRunPolicyResults{BlockingPolicies: []string{"gate"}}, + wantStatus: WorkflowRunEventStatusFailed, wantMessage: "build failed"}, {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"}, @@ -106,7 +175,7 @@ func TestClosingWorkflowRunEvent(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - got := ClosingWorkflowRunEvent(runID, tc.status, tc.reason, tc.digest) + got := ClosingWorkflowRunEvent(runID, tc.status, tc.reason, tc.digest, tc.policies) if tc.wantNil { assert.Nil(t, got) return @@ -118,8 +187,8 @@ func TestClosingWorkflowRunEvent(t *testing.T) { 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) + if tc.wantAttrs != nil { + assert.Equal(t, tc.wantAttrs, got.Attributes.Attestation) } else { assert.Nil(t, got.Attributes) } diff --git a/app/controlplane/pkg/data/workflowrun.go b/app/controlplane/pkg/data/workflowrun.go index e00b5d7bc..041524428 100644 --- a/app/controlplane/pkg/data/workflowrun.go +++ b/app/controlplane/pkg/data/workflowrun.go @@ -416,7 +416,7 @@ func (r *WorkflowRunRepo) GetBundle(ctx context.Context, wrID uuid.UUID) ([]byte return att.Bundle, nil } -func (r *WorkflowRunRepo) MarkAsFinished(ctx context.Context, id uuid.UUID, status biz.WorkflowRunStatus, reason string) error { +func (r *WorkflowRunRepo) MarkAsFinished(ctx context.Context, id uuid.UUID, status biz.WorkflowRunStatus, reason string, policies *biz.WorkflowRunPolicyResults) error { ctx, span := otelx.Start(ctx, workflowRunRepoTracer, "WorkflowRunRepo.MarkAsFinished") defer span.End() @@ -432,13 +432,13 @@ func (r *WorkflowRunRepo) MarkAsFinished(ctx context.Context, id uuid.UUID, stat } // The store path saves the attestation digest before it finishes the run - return closeWorkflowRunTimeline(ctx, tx.Client(), id, status, reason, run.AttestationDigest) + return closeWorkflowRunTimeline(ctx, tx.Client(), id, status, reason, run.AttestationDigest, policies) }) } // 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) +func closeWorkflowRunTimeline(ctx context.Context, client *ent.Client, runID uuid.UUID, status biz.WorkflowRunStatus, reason, digest string, policies *biz.WorkflowRunPolicyResults) error { + ev := biz.ClosingWorkflowRunEvent(runID, status, reason, digest, policies) if ev == nil { return nil } @@ -593,7 +593,7 @@ func (r *WorkflowRunRepo) Expire(ctx context.Context, id uuid.UUID) error { return fmt.Errorf("failed to expire workflow run: %w", err) } - return closeWorkflowRunTimeline(ctx, tx.Client(), id, biz.WorkflowRunExpired, "", "") + return closeWorkflowRunTimeline(ctx, tx.Client(), id, biz.WorkflowRunExpired, "", "", nil) }) } diff --git a/app/controlplane/pkg/data/workflowrunevent_integration_test.go b/app/controlplane/pkg/data/workflowrunevent_integration_test.go index ea5bf5f48..d2e2a3038 100644 --- a/app/controlplane/pkg/data/workflowrunevent_integration_test.go +++ b/app/controlplane/pkg/data/workflowrunevent_integration_test.go @@ -93,7 +93,7 @@ func (s *workflowRunEventIntegrationTestSuite) TestCreate() { name: "finished run is rejected", setup: func() uuid.UUID { id := s.newRun() - s.Require().NoError(s.Repos.WorkflowRunRepo.MarkAsFinished(ctx, id, biz.WorkflowRunSuccess, "")) + s.Require().NoError(s.Repos.WorkflowRunRepo.MarkAsFinished(ctx, id, biz.WorkflowRunSuccess, "", nil)) return id }, maxEvents: 10, @@ -256,13 +256,17 @@ func (s *workflowRunEventIntegrationTestSuite) TestClosingEvent() { ctx := context.Background() runRepo := s.Repos.WorkflowRunRepo const digest = "sha256:deadbeef" + policies := &biz.WorkflowRunPolicyResults{ + Policies: &biz.WorkflowRunEventPolicyCounts{Evaluated: 2, Passed: 1, Violated: 1, ViolatedPolicies: []string{"gate"}}, + BlockingPolicies: []string{"gate"}, + } testCases := []struct { name string finish func(id uuid.UUID) error wantStatus biz.WorkflowRunEventStatus wantMessage string - wantDigest string + wantAttrs *biz.WorkflowRunEventAttestationAttributes }{ { name: "store", @@ -270,15 +274,17 @@ func (s *workflowRunEventIntegrationTestSuite) TestClosingEvent() { if err := runRepo.SaveAttestationDigest(ctx, id, digest, false); err != nil { return err } - return runRepo.MarkAsFinished(ctx, id, biz.WorkflowRunSuccess, "") + return runRepo.MarkAsFinished(ctx, id, biz.WorkflowRunSuccess, "", policies) }, wantStatus: biz.WorkflowRunEventStatusSucceeded, - wantDigest: digest, + wantAttrs: &biz.WorkflowRunEventAttestationAttributes{ + AttestationDigest: digest, Policies: policies.Policies, BlockingPolicies: policies.BlockingPolicies, + }, }, { name: "reset with cancellation", finish: func(id uuid.UUID) error { - return runRepo.MarkAsFinished(ctx, id, biz.WorkflowRunCancelled, "user canceled") + return runRepo.MarkAsFinished(ctx, id, biz.WorkflowRunCancelled, "user canceled", nil) }, wantStatus: biz.WorkflowRunEventStatusCanceled, wantMessage: "user canceled", @@ -286,7 +292,7 @@ func (s *workflowRunEventIntegrationTestSuite) TestClosingEvent() { { name: "reset with failure", finish: func(id uuid.UUID) error { - return runRepo.MarkAsFinished(ctx, id, biz.WorkflowRunError, "build failed") + return runRepo.MarkAsFinished(ctx, id, biz.WorkflowRunError, "build failed", nil) }, wantStatus: biz.WorkflowRunEventStatusFailed, wantMessage: "build failed", @@ -317,9 +323,9 @@ func (s *workflowRunEventIntegrationTestSuite) TestClosingEvent() { s.Equal(biz.WorkflowRunEventKeyAttestation, last.Key) s.Equal(tc.wantStatus, last.Status) s.Equal(tc.wantMessage, last.Message) - if tc.wantDigest != "" { + if tc.wantAttrs != nil { s.Require().NotNil(last.Attributes) - s.Equal(tc.wantDigest, last.Attributes.Attestation.AttestationDigest) + s.Equal(tc.wantAttrs, last.Attributes.Attestation) } else { s.Nil(last.Attributes) } @@ -331,7 +337,7 @@ func (s *workflowRunEventIntegrationTestSuite) TestClosingEvent() { func (s *workflowRunEventIntegrationTestSuite) TestExpireSkipsFinishedRun() { ctx := context.Background() runID := s.newRun() - s.Require().NoError(s.Repos.WorkflowRunRepo.MarkAsFinished(ctx, runID, biz.WorkflowRunSuccess, "")) + s.Require().NoError(s.Repos.WorkflowRunRepo.MarkAsFinished(ctx, runID, biz.WorkflowRunSuccess, "", nil)) 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) diff --git a/docs/plans/issue-3825-attestation-progress-events.md b/docs/plans/issue-3825-attestation-progress-events.md index 96f07d9be..3be0331f9 100644 --- a/docs/plans/issue-3825-attestation-progress-events.md +++ b/docs/plans/issue-3825-attestation-progress-events.md @@ -144,16 +144,16 @@ 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 string blocking_policies = 8; } + 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; } +} ``` @@ -211,12 +211,12 @@ 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-001 to R-008, R-010, R-011 | 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 and read calls, the closing events, and the deletion of old events. The CLI records events from `init` and `add`, the store closes the timeline, 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. **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. @@ -260,13 +260,13 @@ Add the `WorkflowRunEvent` Ent schema with an edge to the run and cascade delete
-03 / 07 · Close the timeline when the run is stored, canceled, or expired (R-006) +03 / 07 · Close the timeline when the run is stored, canceled, or expired (R-011) -Wrap the status update and the insert of the closing `chainloop.attestation` event in one transaction, with source CONTROL_PLANE. `Expire` locks the run row and skips the update and the insert when the run is no longer initialized. So a run that a store finishes during the sweep gets one closing event. On store, read the attestation digest from the run row, because the store path saves it before it finishes the run. Do not change the signature. +Wrap the status update and the insert of the closing `chainloop.attestation` event in one transaction, with source CONTROL_PLANE. `Expire` locks the run row and skips the update and the insert when the run is no longer initialized. So a run that a store finishes during the sweep gets one closing event. On store, read the attestation digest from the run row, because the store path saves it before it finishes the run. The store path also reads the predicate of the attestation that it stores. It passes the attestation policy counts and the gated policies with violations to `MarkAsFinished` (spec R-011). The use case takes them as an option, and the repository as a new parameter. The list of gated policies is empty when the predicate shows a bypass of the check. When the policy evaluations are in the CAS and not in the predicate, the closing event has no policy results. | Run change | Closing status | Code | |------------|----------------|------| -| Store | succeeded, with the digest | `MarkAsFinished` | +| Store | succeeded, with the digest, the attestation policy counts, and the gated policies | `MarkAsFinished` | | Reset, trigger CANCELLATION | canceled | `MarkAsFinished` | | Reset, trigger FAILURE | failed | `MarkAsFinished` | | Expiry | failed, message "expired" | `Expire` | @@ -274,6 +274,7 @@ Wrap the status update and the insert of the closing `chainloop.attestation` eve | File | Change | |------|--------| | `app/controlplane/pkg/data/workflowrun.go` | Use a transaction in `MarkAsFinished` and `Expire`, and insert the event. | +| `app/controlplane/pkg/biz/workflowrunevent.go`, `app/controlplane/internal/service/attestation.go` | Read the policy results from the stored predicate, and pass them to `MarkAsFinished`. | | `app/controlplane/pkg/data/workflowrunevent_integration_test.go` | Add a table test for the four rows, and a test that expiry skips a stored run. | | `app/controlplane/pkg/biz/attestationstate_integration_test.go` | Change the existing test that expires a finished run to use a run in progress, because expiry now skips a finished run. | @@ -282,7 +283,7 @@ 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) -`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. `ListEvents` copies the checks of `View`. | Caller | `RecordEvent` | `ListEvents` | |--------|---------------|--------------| @@ -320,9 +321,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. 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). Move the gate check from the push command into the push action, as a function that returns the blocking policies. The policy counts come from the evaluations in the crafting state. | Answer of the control plane | Recorder | |-----------------------------|----------| @@ -333,16 +334,16 @@ 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/pkg/action/attestation_init.go`, `attestation_add.go`, `attestation_push.go` | Record after each action of `init` and `add`. 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/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 the gate function. Test an archive above and at 20 materials, each with the event of the archive file. |
07 / 07 · Show the progress in workflow run describe (R-004) -`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 `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 closing event of the store, or else from the start event. It shows the timeline as a tree: one line for each step, with the events of a repeated step below it. The last line is "pushed and stored" from the closing event, with the policy counts, the gated policies, 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. Any error from `ListEvents` keeps the current output, and `describe` does not fail. `Unimplemented` gives a debug log, and other errors give a warning. | File | Change | |------|--------| diff --git a/docs/specs/issue-3825-attestation-progress-events.md b/docs/specs/issue-3825-attestation-progress-events.md index 8ca4c9278..9d43ed1c6 100644 --- a/docs/specs/issue-3825-attestation-progress-events.md +++ b/docs/specs/issue-3825-attestation-progress-events.md @@ -54,13 +54,15 @@ 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. @@ -83,9 +85,11 @@ It labels the material and policy data as reported progress. For a finished run, ### R-005: Only safe data in automatic events An automatic event MUST contain only names, types, statuses, counts, digests, timestamps, and the error text of a failed action. It also holds the material value that `attestation status` shows, cut to 256 characters. That is the text of a string material, and the reference or file name of other materials. It MUST NOT contain environment variables, annotations, commit data, file content, policy arguments, or raw policy input and output. -### R-006: The run closes its timeline -The control plane MUST record the closing event of the attestation when it stores, cancels, or expires the run. The status is succeeded on store, with the attestation digest and no message. On `attestation reset`, it is canceled for a cancellation and failed for a failure, with the reset reason as the message, cut to 1 KB. It is failed on expiry, with the message "expired". The CLI never records it. It writes the event in the same place as the change of run status. It MUST accept new events for a run only while the run is in progress. -- Done when: the last event of each finished run agrees with the status of the run, also for an expired run. +### ~~R-006: The run closes its timeline~~ +Superseded by R-011. + +~~The control plane MUST record the closing event of the attestation when it stores, cancels, or expires the run. The status is succeeded on store, with the attestation digest and no message. On `attestation reset`, it is canceled for a cancellation and failed for a failure, with the reset reason as the message, cut to 1 KB. It is failed on expiry, with the message "expired". The CLI never records it. It writes the event in the same place as the change of run status. It MUST accept new events for a run only while the run is in progress.~~ +- ~~Done when: the last event of each finished run agrees with the status of the run, also for an expired run.~~ ### R-007: Retention The control plane MUST delete run events that are older than a retention period. The default is 90 days. An operator can change it in the control plane configuration. The age comes from the time of each event. The run and its attestation stay. A periodic job deletes the events, with the same pattern as the run expiry job. @@ -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 (R-011, 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: The run closes its timeline +Supersedes R-006. The control plane MUST record the closing event of the attestation when it stores, cancels, or expires the run. The status is succeeded on store. The event then has no message. It has the attestation digest and the results of the attestation policies of the stored attestation. It also has the names of the gated policies with violations. The list of gated policies is empty when the user bypassed the policy check. A blocked push is stored as today, so its closing event is succeeded, with the gated policies. On `attestation reset`, the status is canceled for a cancellation and failed for a failure, with the reset reason as the message, cut to 1 KB. It is failed on expiry, with the message "expired". The CLI never records it. It writes the event in the same place as the change of run status. It MUST accept new events for a run only while the run is in progress. +- Done when: the last event of each finished run agrees with the status of the run, also for an expired run. The closing event of a stored attestation has the same policy results as the attestation. + ## 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,13 +124,14 @@ 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 shows the push, with the gated policies of a blocked push (R-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 closing event of the store holds the attestation policies of the stored attestation. 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. @@ -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. The closing event of the store has the policy results of the attestation. ## Decision Record @@ -218,13 +234,20 @@ 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: The closing event of the store replaces the push event +The CLI records no `chainloop.push` event. The control plane reads the policy results and the gated policies from the attestation that it stores, and puts them on the closing event (R-011). The event types are attestation, material, and custom. +- Why: the push event and the closing event described one step for the user, "pushed and stored", in two events. The control plane reads the results from the signed attestation, so they agree with the evidence. A failed send of the CLI can no longer lose them (R-002). +- Alternatives considered: + - Keep the push event, and show it and the closing event as one line: two events for one step. After a retry, the push event can disagree with the stored attestation. +- Source: implementation 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 and R-011 supersede R-001 and R-006. 2. **Custom events.** `chainloop attestation event` (R-009). ## Risks @@ -237,7 +260,7 @@ None. | 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. | | 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 +273,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). The closing event of the store has the attestation digest. It also has the attestation policies of the stored attestation: 2 evaluated, 2 passed, 0 violated, 0 skipped. When a policy gate blocks the push, the control plane still stores the attestation. The closing event is then succeeded, with the names of the gated policies. Reset and expiry follow R-011. From 7b54eadb107d0c93cbfc1fdc67390427b85a8be9 Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Mon, 30 Nov 2026 23:56:10 +0100 Subject: [PATCH 13/20] refactor: take the push result from the attestation, not the closing event Most pushes move the policy evaluations to the CAS, so the control plane can't rebuild the per-policy results at store time. The closing event goes back to digest only, and workflow run describe takes the policy status of the "pushed and stored" line from the stored attestation it already loads. Also: - regenerate the ent code without the push event type - restore the inline gate check of the push command from main - simplify the timeline renderer - spec: R-010 supersedes R-001, D-011 records the decision Refs #3825 Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1cdb3220-119c-4a14-ac50-52d5437ee4eb --- app/cli/cmd/attestation_push.go | 31 ++++-- app/cli/cmd/workflow_run_timeline.go | 104 ++++++++++-------- app/cli/cmd/workflow_run_timeline_test.go | 15 ++- app/cli/cmd/workflow_workflow_run_describe.go | 8 +- app/cli/pkg/action/attestation_push.go | 25 ----- app/cli/pkg/action/runevents_test.go | 37 ------- app/cli/pkg/action/workflow_run_describe.go | 9 +- .../pkg/action/workflow_run_describe_test.go | 11 +- .../api/controlplane/v1/workflow_run.pb.go | 26 ++--- .../api/controlplane/v1/workflow_run.proto | 11 +- .../api/controlplane/v1/workflow_run_test.go | 8 -- .../frontend/controlplane/v1/workflow_run.ts | 30 +---- ...vent.AttestationAttributes.jsonschema.json | 18 +-- ...RunEvent.AttestationAttributes.schema.json | 18 +-- .../internal/service/attestation.go | 9 +- .../internal/service/workflowrun.go | 2 - .../pkg/biz/mocks/WorkflowRunRepo.go | 55 ++++----- app/controlplane/pkg/biz/workflowrun.go | 24 +--- app/controlplane/pkg/biz/workflowrun_test.go | 2 +- app/controlplane/pkg/biz/workflowrunevent.go | 88 +-------------- .../pkg/biz/workflowrunevent_test.go | 81 +------------- .../pkg/data/ent/migrate/schema.go | 2 +- .../ent/workflowrunevent/workflowrunevent.go | 2 +- app/controlplane/pkg/data/workflowrun.go | 10 +- .../data/workflowrunevent_integration_test.go | 24 ++-- .../issue-3825-attestation-progress-events.md | 20 ++-- .../issue-3825-attestation-progress-events.md | 33 +++--- 27 files changed, 185 insertions(+), 518 deletions(-) diff --git a/app/cli/cmd/attestation_push.go b/app/cli/cmd/attestation_push.go index 7594f13a0..2442fb74c 100644 --- a/app/cli/cmd/attestation_push.go +++ b/app/cli/cmd/attestation_push.go @@ -186,20 +186,35 @@ func (e *GateError) Error() string { return fmt.Sprintf("the policy %q is configured as a gate and has violations", e.PolicyName) } +// hasGatingViolation reports whether any of the supplied violations should +// count toward the policy gate. Entries flagged Suppress (typically because +// an assessment renders the finding NOT_AFFECTED) are excluded. +func hasGatingViolation(violations []*action.PolicyViolation) bool { + for _, v := range violations { + if !v.Suppress { + return true + } + } + return false +} + func validatePolicyEnforcement(status *action.AttestationStatusResult, bypassPolicyCheck bool) error { // Block if any of the policies acts as a gate. Organization and contract // enforcement are already resolved into each evaluation's gate. Entries // flagged Suppress are excluded from the gate count but remain in // eval.Violations for CAS storage and ingestion (audit trail preserved). - blocking := action.BlockingPolicies(status.PolicyEvaluations) - if len(blocking) == 0 { - return nil - } + for _, evaluations := range status.PolicyEvaluations { + for _, eval := range evaluations { + if eval.Gate && hasGatingViolation(eval.Violations) { + if bypassPolicyCheck { + logger.Warn().Msg(exceptionBypassPolicyCheck) + continue + } - if bypassPolicyCheck { - logger.Warn().Msg(exceptionBypassPolicyCheck) - return nil + return NewGateError(eval.Name) + } + } } - return NewGateError(blocking[0]) + return nil } diff --git a/app/cli/cmd/workflow_run_timeline.go b/app/cli/cmd/workflow_run_timeline.go index a96d0a123..83dcc8fbe 100644 --- a/app/cli/cmd/workflow_run_timeline.go +++ b/app/cli/cmd/workflow_run_timeline.go @@ -31,7 +31,9 @@ const ( // timelineMaxDetail keeps each line of the tree readable. JSON output has the full text. timelineMaxDetail = 120 - timelineFailed = "failed" + timelineFailed = "failed" + timelineStarted = "started" + timelineSucceeded = "succeeded" ) // timelineNode is one line of the timeline tree @@ -47,8 +49,8 @@ type timelineNode struct { // 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. -func renderRunTimeline(w io.Writer, events []*action.RunEvent, progress *action.RunProgress, now time.Time) { +// 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) { if len(events) == 0 { return } @@ -71,20 +73,21 @@ func renderRunTimeline(w io.Writer, events []*action.RunEvent, progress *action. } var nodes []*timelineNode - var closing *action.RunEvent + 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 == "started" { + 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 != "started" { + if last := evs[len(evs)-1]; last.Status != timelineStarted { closing = last } default: @@ -104,29 +107,29 @@ func renderRunTimeline(w io.Writer, events []*action.RunEvent, progress *action. }) } } + if closing == nil { + nodes = append(nodes, &timelineNode{symbol: timelineSymbol(timelineStarted), name: "waiting for push"}) + } } - if end := timelineEnd(closing, progress != nil); end != nil { - nodes = append(nodes, end) + if closing != nil { + nodes = append(nodes, timelineEnd(closing, stored)) } - fmt.Fprintln(w, timelineHeader(groups[timelineKeyAttestation], events, closing, progress, now)) + 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(attestation, events []*action.RunEvent, closing *action.RunEvent, progress *action.RunProgress, now time.Time) string { +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 - for _, e := range attestation { - if e.Status == "started" { - start = e.CreatedAt - break - } + if started != nil { + start = started.CreatedAt } parts := []string{title} @@ -157,7 +160,7 @@ func timelineHeader(attestation, events []*action.RunEvent, closing *action.RunE // 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("succeeded"), name: "initialized"} + node := &timelineNode{at: timelineTime(e.CreatedAt), symbol: timelineSymbol(timelineSucceeded), name: "initialized"} a := e.Attestation if a == nil { return node @@ -187,28 +190,13 @@ func timelineInit(e *action.RunEvent) *timelineNode { // 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 results of the stored attestation and its digest. A run that ends with no store +// 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, inProgress bool) *timelineNode { - switch { - case closing == nil && inProgress: - return &timelineNode{symbol: timelineSymbol("started"), name: "waiting for push"} - case closing == nil: - return nil - } - - node := &timelineNode{at: timelineTime(closing.CreatedAt), symbol: timelineSymbol(closing.Status), name: timelineStatus(closing.Status)} - if closing.Status == "succeeded" { +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" - if a := closing.Attestation; a != nil { - if s := runPolicyCountSummary(a.Policies); s != "" { - node.details = append(node.details, "policies: "+s) - } - // a blocked attestation is stored too, and the push command fails after it - if len(a.BlockingPolicies) > 0 { - node.details = append(node.details, text.FgHiRed.Sprint("blocked by: "+strings.Join(a.BlockingPolicies, ", "))) - } - } + node.details = append(node.details, timelinePolicyStatus(stored)...) } if d := timelineDigest(closing); d != "" { node.details = append(node.details, d) @@ -220,6 +208,26 @@ func timelineEnd(closing *action.RunEvent, inProgress bool) *timelineNode { 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 attestation table above +// the timeline has the details of the gates. +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 == "" { @@ -240,18 +248,18 @@ func timelineStep(key string, evs []*action.RunEvent, materials map[string]*acti name := action.RunStepName(key) node := &timelineNode{at: timelineTime(evs[0].CreatedAt), symbol: timelineSymbol(last.Status), name: timelineEvidenceAction(last, name)} - if m := last.Material; m != nil { - if m.MaterialType != "" { - node.details = append(node.details, m.MaterialType) - } - if m.Value != "" { - node.details = append(node.details, m.Value) - } + // details in order: type, value, requirement, policies + m := last.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 m := materials[name]; m != nil { - node.details = append(node.details, timelineRequirement(m)) + if req := materials[name]; req != nil { + node.details = append(node.details, timelineRequirement(req)) } - if m := last.Material; m != nil { + if m != nil { if s := runPolicyCountSummary(m.Policies); s != "" { node.details = append(node.details, "policies: "+s) } @@ -343,7 +351,7 @@ func timelineRequirement(m *action.RunProgressMaterial) string { func timelineSymbol(status string) string { switch status { - case "succeeded": + case timelineSucceeded: return text.FgHiGreen.Sprint("✓") case timelineFailed: return text.FgHiRed.Sprint("✗") @@ -356,7 +364,7 @@ func timelineSymbol(status string) string { // timelineStatus names how the attestation ended func timelineStatus(status string) string { - if status == "succeeded" { + if status == timelineSucceeded { return "stored" } return status diff --git a/app/cli/cmd/workflow_run_timeline_test.go b/app/cli/cmd/workflow_run_timeline_test.go index 56c1cb594..ef22da351 100644 --- a/app/cli/cmd/workflow_run_timeline_test.go +++ b/app/cli/cmd/workflow_run_timeline_test.go @@ -45,6 +45,7 @@ func TestRenderRunTimeline(t *testing.T) { name string events []*action.RunEvent progress *action.RunProgress + stored *action.PolicyEvaluationStatus want string }{ { @@ -82,23 +83,25 @@ func TestRenderRunTimeline(t *testing.T) { started, material(451*time.Second, "vulnerability-report", "succeeded", "", nil), {CreatedAt: at(501 * time.Second), Key: timelineKeyAttestation, Status: "succeeded", Attestation: &action.RunEventAttestation{ - AttestationDigest: "sha256:4de7a1b2c3d4e5f60718293a4b5c6d7e8f", Policies: &action.RunEventPolicyCount{Evaluated: 1, Passed: 1}}}, + 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: 1 passed · sha256:4de7a1b2c3d4…\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", Policies: &action.RunEventPolicyCount{Evaluated: 1, Violated: 1}, BlockingPolicies: []string{"sast-no-critical"}}}, + 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: 1 violated · blocked by: sast-no-critical · sha256:4de7\n", + "└─ 10:01:02 ✓ pushed and stored policies: 2 passed, 1 violated · blocked by policy gates · sha256:4de7\n", }, { name: "expired run", @@ -115,7 +118,7 @@ func TestRenderRunTimeline(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { var buf bytes.Buffer - renderRunTimeline(&buf, tc.events, tc.progress, start.Add(343*time.Second)) + renderRunTimeline(&buf, tc.events, tc.progress, tc.stored, start.Add(343*time.Second)) assert.Equal(t, tc.want, buf.String()) }) } @@ -123,6 +126,6 @@ func TestRenderRunTimeline(t *testing.T) { func TestRenderRunTimelineNoEvents(t *testing.T) { var buf bytes.Buffer - renderRunTimeline(&buf, nil, nil, time.Now()) + renderRunTimeline(&buf, nil, nil, nil, time.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 3b438d881..87e5fdbb2 100644 --- a/app/cli/cmd/workflow_workflow_run_describe.go +++ b/app/cli/cmd/workflow_workflow_run_describe.go @@ -136,13 +136,13 @@ func workflowRunDescribeTableOutput(run *action.WorkflowRunItemFull) error { if run.Progress != nil { gt.Render() - renderRunTimeline(os.Stdout, run.Events, run.Progress, time.Now()) + 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, time.Now()) + 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 } @@ -150,7 +150,7 @@ func workflowRunDescribeTableOutput(run *action.WorkflowRunItemFull) error { att := run.Attestation if att == nil { gt.Render() - renderRunTimeline(os.Stdout, run.Events, nil, time.Now()) + renderRunTimeline(os.Stdout, run.Events, nil, nil, time.Now()) logger.Warn().Msg("there was an issue retrieving the attestation") return nil } @@ -184,7 +184,7 @@ func workflowRunDescribeTableOutput(run *action.WorkflowRunItemFull) error { predicateV1Table(att) // The timeline is history: the signed attestation above is the source of truth - renderRunTimeline(os.Stdout, run.Events, nil, time.Now()) + 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 } diff --git a/app/cli/pkg/action/attestation_push.go b/app/cli/pkg/action/attestation_push.go index 0ef5595a8..a706856c3 100644 --- a/app/cli/pkg/action/attestation_push.go +++ b/app/cli/pkg/action/attestation_push.go @@ -23,8 +23,6 @@ import ( "encoding/json" "fmt" "os" - "slices" - "sort" "time" pb "github.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1" @@ -327,29 +325,6 @@ func (action *AttestationPush) saveBundle(bundle *protobundle.Bundle) error { return nil } -// BlockingPolicies returns the sorted names of the gated policies with a violation that an -// assessment does not suppress. They block the push unless the check is bypassed. -func BlockingPolicies(evaluations map[string][]*PolicyEvaluation) []string { - var blocking []string - for _, evs := range evaluations { - for _, ev := range evs { - if !ev.Gate { - continue - } - for _, v := range ev.Violations { - if !v.Suppress { - blocking = append(blocking, ev.Name) - break - } - } - } - } - // A policy attached to several materials is one blocking policy - sort.Strings(blocking) - - return slices.Compact(blocking) -} - func pushToControlPlane(ctx context.Context, conn *grpc.ClientConn, bundle *protobundle.Bundle, workflowRunID string, markVersionAsReleased bool) (string, error) { encodedBundle, err := encodeBundle(bundle) if err != nil { diff --git a/app/cli/pkg/action/runevents_test.go b/app/cli/pkg/action/runevents_test.go index 76d8da47e..3c8818323 100644 --- a/app/cli/pkg/action/runevents_test.go +++ b/app/cli/pkg/action/runevents_test.go @@ -352,43 +352,6 @@ func TestRunEventRecorderCapsPolicyNames(t *testing.T) { assert.Equal(t, int32(150), att.GetPolicies().GetViolated(), "the counts stay complete") } -// The gate rule of the push command: a gated policy with a violation that is not suppressed -func TestBlockingPolicies(t *testing.T) { - violation := []*PolicyViolation{{Message: testBad}} - suppressed := []*PolicyViolation{{Message: "not affected", Suppress: true}} - - testCases := []struct { - name string - evaluations map[string][]*PolicyEvaluation - want []string - }{ - {name: "no gate", evaluations: map[string][]*PolicyEvaluation{testAtt: {{Name: "advisory", Violations: violation}}}}, - { - name: "gated policies with violations, sorted", - evaluations: map[string][]*PolicyEvaluation{ - testSBOM: {{Name: testSBOMGate, Gate: true, Violations: violation}}, - testAtt: {{Name: testAttGate, Gate: true, Violations: violation}, {Name: "ok", Gate: true}}, - }, - want: []string{testAttGate, testSBOMGate}, - }, - { - name: "same policy on two materials, once", - evaluations: map[string][]*PolicyEvaluation{ - testSBOM: {{Name: testSBOMGate, Gate: true, Violations: violation}}, - testImage: {{Name: testSBOMGate, Gate: true, Violations: violation}}, - }, - want: []string{testSBOMGate}, - }, - {name: "suppressed violations only", evaluations: map[string][]*PolicyEvaluation{testAtt: {{Name: testAttGate, Gate: true, Violations: suppressed}}}}, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - assert.Equal(t, tc.want, BlockingPolicies(tc.evaluations)) - }) - } -} - func TestPolicyCounts(t *testing.T) { violation := []*api.PolicyEvaluation_Violation{{Message: testBad}} suppressed := []*api.PolicyEvaluation_Violation{{Message: "not affected", Suppress: true}} diff --git a/app/cli/pkg/action/workflow_run_describe.go b/app/cli/pkg/action/workflow_run_describe.go index 79fcb8920..e48405424 100644 --- a/app/cli/pkg/action/workflow_run_describe.go +++ b/app/cli/pkg/action/workflow_run_describe.go @@ -549,11 +549,8 @@ type RunEventAttestation struct { 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 on the start event, - // of the stored attestation on the closing event + // results of the attestation policies evaluated at init Policies *RunEventPolicyCount `json:"policies,omitempty"` - // gated policies with violations in the stored attestation, on the closing event - BlockingPolicies []string `json:"blocking_policies,omitempty"` } type RunEventMaterial struct { @@ -649,7 +646,7 @@ func pbRunEventToAction(in *pb.WorkflowRunEvent) *RunEvent { 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()), BlockingPolicies: a.GetBlockingPolicies(), + Policies: pbRunEventPolicyCountToAction(a.GetPolicies()), } } @@ -704,7 +701,7 @@ func buildRunProgress(contractMaterials []*schemaapi.CraftingSchema_Material, ev if e.Status == runEventStatusFailed { failed[name]++ } - // the latest attestation policy results: init, then the stored attestation + // the attestation policy results of init case e.Attestation != nil && e.Attestation.Policies != nil: progress.AttestationPolicies = e.Attestation.Policies } diff --git a/app/cli/pkg/action/workflow_run_describe_test.go b/app/cli/pkg/action/workflow_run_describe_test.go index 469b9e396..102b8e0ed 100644 --- a/app/cli/pkg/action/workflow_run_describe_test.go +++ b/app/cli/pkg/action/workflow_run_describe_test.go @@ -298,20 +298,15 @@ func TestBuildRunProgressGroups(t *testing.T) { } } -// The attestation policy results come from the started event, then from the closing event -// of the stored attestation +// The attestation policy results come from the started event. The closing event has none. func TestBuildRunProgressAttestationPolicies(t *testing.T) { now := time.Now() initCounts := &RunEventPolicyCount{Evaluated: 2, Passed: 2} - storedCounts := &RunEventPolicyCount{Evaluated: 3, Passed: 2, Violated: 1} started := &RunEvent{CreatedAt: &now, Key: testAttKey, Status: "started", Attestation: &RunEventAttestation{Policies: initCounts}} - stored := &RunEvent{CreatedAt: &now, Key: testAttKey, Status: "succeeded", - Attestation: &RunEventAttestation{Policies: storedCounts, BlockingPolicies: []string{"gate"}}} - expired := &RunEvent{CreatedAt: &now, Key: testAttKey, Status: "failed", Message: "expired"} + stored := &RunEvent{CreatedAt: &now, Key: testAttKey, Status: "succeeded", Attestation: &RunEventAttestation{AttestationDigest: "sha256:abc"}} assert.Equal(t, initCounts, buildRunProgress(nil, []*RunEvent{started}, now).AttestationPolicies) - assert.Equal(t, storedCounts, buildRunProgress(nil, []*RunEvent{started, stored}, now).AttestationPolicies) - assert.Equal(t, initCounts, buildRunProgress(nil, []*RunEvent{started, expired}, now).AttestationPolicies) + assert.Equal(t, initCounts, buildRunProgress(nil, []*RunEvent{started, stored}, now).AttestationPolicies) } // fakeRunViewServer serves View for one run, and ListEvents with a configured answer diff --git a/app/controlplane/api/controlplane/v1/workflow_run.pb.go b/app/controlplane/api/controlplane/v1/workflow_run.pb.go index 8348f3928..96bc30712 100644 --- a/app/controlplane/api/controlplane/v1/workflow_run.pb.go +++ b/app/controlplane/api/controlplane/v1/workflow_run.pb.go @@ -2118,14 +2118,10 @@ type WorkflowRunEvent_AttestationAttributes struct { 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: the ones evaluated at init on the start event, - // the ones of the stored attestation on the closing event - Policies *WorkflowRunEvent_PolicyCounts `protobuf:"bytes,7,opt,name=policies,proto3" json:"policies,omitempty"` - // gated policies with violations in the stored attestation, empty when the check - // was bypassed. Set on the closing event only. - BlockingPolicies []string `protobuf:"bytes,8,rep,name=blocking_policies,json=blockingPolicies,proto3" json:"blocking_policies,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // results of the attestation policies evaluated at init + Policies *WorkflowRunEvent_PolicyCounts `protobuf:"bytes,7,opt,name=policies,proto3" json:"policies,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *WorkflowRunEvent_AttestationAttributes) Reset() { @@ -2207,13 +2203,6 @@ func (x *WorkflowRunEvent_AttestationAttributes) GetPolicies() *WorkflowRunEvent return nil } -func (x *WorkflowRunEvent_AttestationAttributes) GetBlockingPolicies() []string { - if x != nil { - return x.BlockingPolicies - } - return nil -} - type WorkflowRunEvent_MaterialAttributes struct { state protoimpl.MessageState `protogen:"open.v1"` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` @@ -2652,7 +2641,7 @@ const file_controlplane_v1_workflow_run_proto_rawDesc = "" + "\x0fworkflow_run_id\x18\x01 \x01(\tB\b\xbaH\x05r\x03\xb0\x01\x01R\rworkflowRunId\x121\n" + "\x0eafter_event_id\x18\x02 \x01(\tB\v\xbaH\b\xd8\x01\x01r\x03\xb0\x01\x01R\fafterEventId\"a\n" + "$WorkflowRunServiceListEventsResponse\x129\n" + - "\x06events\x18\x01 \x03(\v2!.controlplane.v1.WorkflowRunEventR\x06events\"\x88\x0e\n" + + "\x06events\x18\x01 \x03(\v2!.controlplane.v1.WorkflowRunEventR\x06events\"\xca\r\n" + "\x10WorkflowRunEvent\x12\x0e\n" + "\x02id\x18\x01 \x01(\tR\x02id\x129\n" + "\n" + @@ -2667,7 +2656,7 @@ const file_controlplane_v1_workflow_run_proto_rawDesc = "" + "\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\xaf\x03\n" + + "\bmaterial\x18\v \x01(\v24.controlplane.v1.WorkflowRunEvent.MaterialAttributesH\x00R\bmaterial\x1a\xf1\x02\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" + @@ -2677,8 +2666,7 @@ const file_controlplane_v1_workflow_run_proto_rawDesc = "" + "\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\x12<\n" + - "\x11blocking_policies\x18\b \x03(\tB\x0f\xbaH\f\x92\x01\t\x10d\"\x05r\x03\x18\x80\x02R\x10blockingPolicies\x1a\xbe\x02\n" + + "\bpolicies\x18\a \x01(\v2..controlplane.v1.WorkflowRunEvent.PolicyCountsR\bpolicies\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" + diff --git a/app/controlplane/api/controlplane/v1/workflow_run.proto b/app/controlplane/api/controlplane/v1/workflow_run.proto index fd2b41583..7343633a0 100644 --- a/app/controlplane/api/controlplane/v1/workflow_run.proto +++ b/app/controlplane/api/controlplane/v1/workflow_run.proto @@ -288,17 +288,8 @@ message WorkflowRunEvent { 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: the ones evaluated at init on the start event, - // the ones of the stored attestation on the closing event + // results of the attestation policies evaluated at init PolicyCounts policies = 7; - // gated policies with violations in the stored attestation, empty when the check - // was bypassed. Set on the closing event only. - repeated string blocking_policies = 8 [(buf.validate.field).repeated = { - max_items: 100 - items: { - string: {max_len: 256} - } - }]; } message MaterialAttributes { diff --git a/app/controlplane/api/controlplane/v1/workflow_run_test.go b/app/controlplane/api/controlplane/v1/workflow_run_test.go index 9a0ff16d5..bbf29c860 100644 --- a/app/controlplane/api/controlplane/v1/workflow_run_test.go +++ b/app/controlplane/api/controlplane/v1/workflow_run_test.go @@ -64,14 +64,6 @@ func TestAttestationServiceRecordEventRequestLimits(t *testing.T) { }, wantErr: true, }, - { - desc: "over 100 blocking policies", - mutate: func(ev *v1.WorkflowRunEvent) { - ev.Type = v1.WorkflowRunEvent_TYPE_ATTESTATION - ev.Attributes = &v1.WorkflowRunEvent_Attestation{Attestation: &v1.WorkflowRunEvent_AttestationAttributes{BlockingPolicies: names(101)}} - }, - wantErr: true, - }, } validator, err := protovalidate.New() 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 59e6a1ddf..51b8a87a4 100644 --- a/app/controlplane/api/gen/frontend/controlplane/v1/workflow_run.ts +++ b/app/controlplane/api/gen/frontend/controlplane/v1/workflow_run.ts @@ -397,16 +397,8 @@ export interface WorkflowRunEvent_AttestationAttributes { remoteState: boolean; cliVersion: string; attestationDigest: string; - /** - * results of the attestation policies: the ones evaluated at init on the start event, - * the ones of the stored attestation on the closing event - */ + /** results of the attestation policies evaluated at init */ policies?: WorkflowRunEvent_PolicyCounts; - /** - * gated policies with violations in the stored attestation, empty when the check - * was bypassed. Set on the closing event only. - */ - blockingPolicies: string[]; } export interface WorkflowRunEvent_MaterialAttributes { @@ -2623,7 +2615,6 @@ function createBaseWorkflowRunEvent_AttestationAttributes(): WorkflowRunEvent_At cliVersion: "", attestationDigest: "", policies: undefined, - blockingPolicies: [], }; } @@ -2650,9 +2641,6 @@ export const WorkflowRunEvent_AttestationAttributes = { if (message.policies !== undefined) { WorkflowRunEvent_PolicyCounts.encode(message.policies, writer.uint32(58).fork()).ldelim(); } - for (const v of message.blockingPolicies) { - writer.uint32(66).string(v!); - } return writer; }, @@ -2712,13 +2700,6 @@ export const WorkflowRunEvent_AttestationAttributes = { message.policies = WorkflowRunEvent_PolicyCounts.decode(reader, reader.uint32()); continue; - case 8: - if (tag !== 66) { - break; - } - - message.blockingPolicies.push(reader.string()); - continue; } if ((tag & 7) === 4 || tag === 0) { break; @@ -2737,9 +2718,6 @@ export const WorkflowRunEvent_AttestationAttributes = { cliVersion: isSet(object.cliVersion) ? String(object.cliVersion) : "", attestationDigest: isSet(object.attestationDigest) ? String(object.attestationDigest) : "", policies: isSet(object.policies) ? WorkflowRunEvent_PolicyCounts.fromJSON(object.policies) : undefined, - blockingPolicies: Array.isArray(object?.blockingPolicies) - ? object.blockingPolicies.map((e: any) => String(e)) - : [], }; }, @@ -2753,11 +2731,6 @@ export const WorkflowRunEvent_AttestationAttributes = { message.attestationDigest !== undefined && (obj.attestationDigest = message.attestationDigest); message.policies !== undefined && (obj.policies = message.policies ? WorkflowRunEvent_PolicyCounts.toJSON(message.policies) : undefined); - if (message.blockingPolicies) { - obj.blockingPolicies = message.blockingPolicies.map((e) => e); - } else { - obj.blockingPolicies = []; - } return obj; }, @@ -2780,7 +2753,6 @@ export const WorkflowRunEvent_AttestationAttributes = { message.policies = (object.policies !== undefined && object.policies !== null) ? WorkflowRunEvent_PolicyCounts.fromPartial(object.policies) : undefined; - message.blockingPolicies = object.blockingPolicies?.map((e) => e) || []; return message; }, }; 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 index 2678fdfc1..3e3126a61 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.AttestationAttributes.jsonschema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.AttestationAttributes.jsonschema.json @@ -7,14 +7,6 @@ "maxLength": 256, "type": "string" }, - "^(blocking_policies)$": { - "description": "gated policies with violations in the stored attestation, empty when the check\n was bypassed. Set on the closing event only.", - "items": { - "maxLength": 256, - "type": "string" - }, - "type": "array" - }, "^(cli_version)$": { "maxLength": 256, "type": "string" @@ -41,14 +33,6 @@ "maxLength": 256, "type": "string" }, - "blockingPolicies": { - "description": "gated policies with violations in the stored attestation, empty when the check\n was bypassed. Set on the closing event only.", - "items": { - "maxLength": 256, - "type": "string" - }, - "type": "array" - }, "cliVersion": { "maxLength": 256, "type": "string" @@ -64,7 +48,7 @@ }, "policies": { "$ref": "controlplane.v1.WorkflowRunEvent.PolicyCounts.jsonschema.json", - "description": "results of the attestation policies: the ones evaluated at init on the start event,\n the ones of the stored attestation on the closing event" + "description": "results of the attestation policies evaluated at init" }, "remoteState": { "type": "boolean" 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 index 81580f614..a18146e3b 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.AttestationAttributes.schema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.AttestationAttributes.schema.json @@ -7,14 +7,6 @@ "maxLength": 256, "type": "string" }, - "^(blockingPolicies)$": { - "description": "gated policies with violations in the stored attestation, empty when the check\n was bypassed. Set on the closing event only.", - "items": { - "maxLength": 256, - "type": "string" - }, - "type": "array" - }, "^(cliVersion)$": { "maxLength": 256, "type": "string" @@ -41,14 +33,6 @@ "maxLength": 256, "type": "string" }, - "blocking_policies": { - "description": "gated policies with violations in the stored attestation, empty when the check\n was bypassed. Set on the closing event only.", - "items": { - "maxLength": 256, - "type": "string" - }, - "type": "array" - }, "cli_version": { "maxLength": 256, "type": "string" @@ -64,7 +48,7 @@ }, "policies": { "$ref": "controlplane.v1.WorkflowRunEvent.PolicyCounts.schema.json", - "description": "results of the attestation policies: the ones evaluated at init on the start event,\n the ones of the stored attestation on the closing event" + "description": "results of the attestation policies evaluated at init" }, "remote_state": { "type": "boolean" diff --git a/app/controlplane/internal/service/attestation.go b/app/controlplane/internal/service/attestation.go index 5438974c7..c1030f1a9 100644 --- a/app/controlplane/internal/service/attestation.go +++ b/app/controlplane/internal/service/attestation.go @@ -423,14 +423,7 @@ func (s *AttestationService) storeAttestation(ctx context.Context, bundle []byte } } - // The closing event of the run shows the policy results of the stored attestation. - // They are informational, so a predicate that can't be read does not fail the store. - var policyResults *biz.WorkflowRunPolicyResults - if predicate, err := chainloop.ExtractPredicate(dsseEnv); err == nil { - policyResults = biz.PolicyResultsFromPredicate(predicate) - } - - if err := s.wrUseCase.MarkAsFinished(ctx, workflowRunID, biz.WorkflowRunSuccess, "", biz.WithPolicyResults(policyResults)); err != nil { + if err := s.wrUseCase.MarkAsFinished(ctx, workflowRunID, biz.WorkflowRunSuccess, ""); err != nil { return nil, handleUseCaseErr(ctx, err, s.log) } diff --git a/app/controlplane/internal/service/workflowrun.go b/app/controlplane/internal/service/workflowrun.go index 4921a175a..837d3dd99 100644 --- a/app/controlplane/internal/service/workflowrun.go +++ b/app/controlplane/internal/service/workflowrun.go @@ -693,7 +693,6 @@ func pbWorkflowRunEventToBiz(in *pb.WorkflowRunEvent) (*biz.WorkflowRunEvent, er CLIVersion: a.GetCliVersion(), AttestationDigest: a.GetAttestationDigest(), Policies: pbPolicyCountsToBiz(a.GetPolicies()), - BlockingPolicies: a.GetBlockingPolicies(), }} case *pb.WorkflowRunEvent_Material: m := attrs.Material @@ -766,7 +765,6 @@ func bizWorkflowRunEventToPb(in *biz.WorkflowRunEvent) *pb.WorkflowRunEvent { CliVersion: a.CLIVersion, AttestationDigest: a.AttestationDigest, Policies: bizPolicyCountsToPb(a.Policies), - BlockingPolicies: a.BlockingPolicies, }} case attrs.Material != nil: m := attrs.Material diff --git a/app/controlplane/pkg/biz/mocks/WorkflowRunRepo.go b/app/controlplane/pkg/biz/mocks/WorkflowRunRepo.go index f617c1864..c7b4a51cb 100644 --- a/app/controlplane/pkg/biz/mocks/WorkflowRunRepo.go +++ b/app/controlplane/pkg/biz/mocks/WorkflowRunRepo.go @@ -21,19 +21,10 @@ func NewWorkflowRunRepo(t interface { mock.TestingT Cleanup(func()) }) *WorkflowRunRepo { - if helper, ok := t.(interface{ Helper() }); ok { - helper.Helper() - } - mock := &WorkflowRunRepo{} mock.Mock.Test(t) - t.Cleanup(func() { - if helper, ok := t.(interface{ Helper() }); ok { - helper.Helper() - } - mock.AssertExpectations(t) - }) + t.Cleanup(func() { mock.AssertExpectations(t) }) return mock } @@ -87,7 +78,7 @@ type WorkflowRunRepo_Create_Call struct { // Create is a helper method to define mock.On call // - ctx context.Context // - opts *biz.WorkflowRunRepoCreateOpts -func (_e *WorkflowRunRepo_Expecter) Create(ctx any, opts any) *WorkflowRunRepo_Create_Call { +func (_e *WorkflowRunRepo_Expecter) Create(ctx interface{}, opts interface{}) *WorkflowRunRepo_Create_Call { return &WorkflowRunRepo_Create_Call{Call: _e.mock.On("Create", ctx, opts)} } @@ -144,7 +135,7 @@ type WorkflowRunRepo_Expire_Call struct { // Expire is a helper method to define mock.On call // - ctx context.Context // - id uuid.UUID -func (_e *WorkflowRunRepo_Expecter) Expire(ctx any, id any) *WorkflowRunRepo_Expire_Call { +func (_e *WorkflowRunRepo_Expecter) Expire(ctx interface{}, id interface{}) *WorkflowRunRepo_Expire_Call { return &WorkflowRunRepo_Expire_Call{Call: _e.mock.On("Expire", ctx, id)} } @@ -212,7 +203,7 @@ type WorkflowRunRepo_FindByAttestationDigest_Call struct { // FindByAttestationDigest is a helper method to define mock.On call // - ctx context.Context // - digest string -func (_e *WorkflowRunRepo_Expecter) FindByAttestationDigest(ctx any, digest any) *WorkflowRunRepo_FindByAttestationDigest_Call { +func (_e *WorkflowRunRepo_Expecter) FindByAttestationDigest(ctx interface{}, digest interface{}) *WorkflowRunRepo_FindByAttestationDigest_Call { return &WorkflowRunRepo_FindByAttestationDigest_Call{Call: _e.mock.On("FindByAttestationDigest", ctx, digest)} } @@ -280,7 +271,7 @@ type WorkflowRunRepo_FindByID_Call struct { // FindByID is a helper method to define mock.On call // - ctx context.Context // - ID uuid.UUID -func (_e *WorkflowRunRepo_Expecter) FindByID(ctx any, ID any) *WorkflowRunRepo_FindByID_Call { +func (_e *WorkflowRunRepo_Expecter) FindByID(ctx interface{}, ID interface{}) *WorkflowRunRepo_FindByID_Call { return &WorkflowRunRepo_FindByID_Call{Call: _e.mock.On("FindByID", ctx, ID)} } @@ -349,7 +340,7 @@ type WorkflowRunRepo_FindByIDInOrg_Call struct { // - ctx context.Context // - orgID uuid.UUID // - ID uuid.UUID -func (_e *WorkflowRunRepo_Expecter) FindByIDInOrg(ctx any, orgID any, ID any) *WorkflowRunRepo_FindByIDInOrg_Call { +func (_e *WorkflowRunRepo_Expecter) FindByIDInOrg(ctx interface{}, orgID interface{}, ID interface{}) *WorkflowRunRepo_FindByIDInOrg_Call { return &WorkflowRunRepo_FindByIDInOrg_Call{Call: _e.mock.On("FindByIDInOrg", ctx, orgID, ID)} } @@ -422,7 +413,7 @@ type WorkflowRunRepo_GetBundle_Call struct { // GetBundle is a helper method to define mock.On call // - ctx context.Context // - wrID uuid.UUID -func (_e *WorkflowRunRepo_Expecter) GetBundle(ctx any, wrID any) *WorkflowRunRepo_GetBundle_Call { +func (_e *WorkflowRunRepo_Expecter) GetBundle(ctx interface{}, wrID interface{}) *WorkflowRunRepo_GetBundle_Call { return &WorkflowRunRepo_GetBundle_Call{Call: _e.mock.On("GetBundle", ctx, wrID)} } @@ -498,7 +489,7 @@ type WorkflowRunRepo_List_Call struct { // - orgID uuid.UUID // - f *biz.RunListFilters // - p *pagination.CursorOptions -func (_e *WorkflowRunRepo_Expecter) List(ctx any, orgID any, f any, p any) *WorkflowRunRepo_List_Call { +func (_e *WorkflowRunRepo_Expecter) List(ctx interface{}, orgID interface{}, f interface{}, p interface{}) *WorkflowRunRepo_List_Call { return &WorkflowRunRepo_List_Call{Call: _e.mock.On("List", ctx, orgID, f, p)} } @@ -577,7 +568,7 @@ type WorkflowRunRepo_ListNotFinishedOlderThan_Call struct { // - ctx context.Context // - olderThan time.Time // - limit int -func (_e *WorkflowRunRepo_Expecter) ListNotFinishedOlderThan(ctx any, olderThan any, limit any) *WorkflowRunRepo_ListNotFinishedOlderThan_Call { +func (_e *WorkflowRunRepo_Expecter) ListNotFinishedOlderThan(ctx interface{}, olderThan interface{}, limit interface{}) *WorkflowRunRepo_ListNotFinishedOlderThan_Call { return &WorkflowRunRepo_ListNotFinishedOlderThan_Call{Call: _e.mock.On("ListNotFinishedOlderThan", ctx, olderThan, limit)} } @@ -615,16 +606,16 @@ func (_c *WorkflowRunRepo_ListNotFinishedOlderThan_Call) RunAndReturn(run func(c } // MarkAsFinished provides a mock function for the type WorkflowRunRepo -func (_mock *WorkflowRunRepo) MarkAsFinished(ctx context.Context, ID uuid.UUID, status biz.WorkflowRunStatus, reason string, policies *biz.WorkflowRunPolicyResults) error { - ret := _mock.Called(ctx, ID, status, reason, policies) +func (_mock *WorkflowRunRepo) MarkAsFinished(ctx context.Context, ID uuid.UUID, status biz.WorkflowRunStatus, reason string) error { + ret := _mock.Called(ctx, ID, status, reason) if len(ret) == 0 { panic("no return value specified for MarkAsFinished") } var r0 error - if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, biz.WorkflowRunStatus, string, *biz.WorkflowRunPolicyResults) error); ok { - r0 = returnFunc(ctx, ID, status, reason, policies) + if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, biz.WorkflowRunStatus, string) error); ok { + r0 = returnFunc(ctx, ID, status, reason) } else { r0 = ret.Error(0) } @@ -641,12 +632,11 @@ type WorkflowRunRepo_MarkAsFinished_Call struct { // - ID uuid.UUID // - status biz.WorkflowRunStatus // - reason string -// - policies *biz.WorkflowRunPolicyResults -func (_e *WorkflowRunRepo_Expecter) MarkAsFinished(ctx any, ID any, status any, reason any, policies any) *WorkflowRunRepo_MarkAsFinished_Call { - return &WorkflowRunRepo_MarkAsFinished_Call{Call: _e.mock.On("MarkAsFinished", ctx, ID, status, reason, policies)} +func (_e *WorkflowRunRepo_Expecter) MarkAsFinished(ctx interface{}, ID interface{}, status interface{}, reason interface{}) *WorkflowRunRepo_MarkAsFinished_Call { + return &WorkflowRunRepo_MarkAsFinished_Call{Call: _e.mock.On("MarkAsFinished", ctx, ID, status, reason)} } -func (_c *WorkflowRunRepo_MarkAsFinished_Call) Run(run func(ctx context.Context, ID uuid.UUID, status biz.WorkflowRunStatus, reason string, policies *biz.WorkflowRunPolicyResults)) *WorkflowRunRepo_MarkAsFinished_Call { +func (_c *WorkflowRunRepo_MarkAsFinished_Call) Run(run func(ctx context.Context, ID uuid.UUID, status biz.WorkflowRunStatus, reason string)) *WorkflowRunRepo_MarkAsFinished_Call { _c.Call.Run(func(args mock.Arguments) { var arg0 context.Context if args[0] != nil { @@ -664,16 +654,11 @@ func (_c *WorkflowRunRepo_MarkAsFinished_Call) Run(run func(ctx context.Context, if args[3] != nil { arg3 = args[3].(string) } - var arg4 *biz.WorkflowRunPolicyResults - if args[4] != nil { - arg4 = args[4].(*biz.WorkflowRunPolicyResults) - } run( arg0, arg1, arg2, arg3, - arg4, ) }) return _c @@ -684,7 +669,7 @@ func (_c *WorkflowRunRepo_MarkAsFinished_Call) Return(err error) *WorkflowRunRep return _c } -func (_c *WorkflowRunRepo_MarkAsFinished_Call) RunAndReturn(run func(ctx context.Context, ID uuid.UUID, status biz.WorkflowRunStatus, reason string, policies *biz.WorkflowRunPolicyResults) error) *WorkflowRunRepo_MarkAsFinished_Call { +func (_c *WorkflowRunRepo_MarkAsFinished_Call) RunAndReturn(run func(ctx context.Context, ID uuid.UUID, status biz.WorkflowRunStatus, reason string) error) *WorkflowRunRepo_MarkAsFinished_Call { _c.Call.Return(run) return _c } @@ -717,7 +702,7 @@ type WorkflowRunRepo_SaveAttestationBundle_Call struct { // - digest string // - bundle []byte // - blockReleasedVersions bool -func (_e *WorkflowRunRepo_Expecter) SaveAttestationBundle(ctx any, ID any, digest any, bundle any, blockReleasedVersions any) *WorkflowRunRepo_SaveAttestationBundle_Call { +func (_e *WorkflowRunRepo_Expecter) SaveAttestationBundle(ctx interface{}, ID interface{}, digest interface{}, bundle interface{}, blockReleasedVersions interface{}) *WorkflowRunRepo_SaveAttestationBundle_Call { return &WorkflowRunRepo_SaveAttestationBundle_Call{Call: _e.mock.On("SaveAttestationBundle", ctx, ID, digest, bundle, blockReleasedVersions)} } @@ -791,7 +776,7 @@ type WorkflowRunRepo_SaveAttestationDigest_Call struct { // - ID uuid.UUID // - digest string // - blockReleasedVersions bool -func (_e *WorkflowRunRepo_Expecter) SaveAttestationDigest(ctx any, ID any, digest any, blockReleasedVersions any) *WorkflowRunRepo_SaveAttestationDigest_Call { +func (_e *WorkflowRunRepo_Expecter) SaveAttestationDigest(ctx interface{}, ID interface{}, digest interface{}, blockReleasedVersions interface{}) *WorkflowRunRepo_SaveAttestationDigest_Call { return &WorkflowRunRepo_SaveAttestationDigest_Call{Call: _e.mock.On("SaveAttestationDigest", ctx, ID, digest, blockReleasedVersions)} } @@ -859,7 +844,7 @@ type WorkflowRunRepo_UpdatePolicyStatus_Call struct { // - ctx context.Context // - ID uuid.UUID // - summary *chainloop.PolicyStatusSummary -func (_e *WorkflowRunRepo_Expecter) UpdatePolicyStatus(ctx any, ID any, summary any) *WorkflowRunRepo_UpdatePolicyStatus_Call { +func (_e *WorkflowRunRepo_Expecter) UpdatePolicyStatus(ctx interface{}, ID interface{}, summary interface{}) *WorkflowRunRepo_UpdatePolicyStatus_Call { return &WorkflowRunRepo_UpdatePolicyStatus_Call{Call: _e.mock.On("UpdatePolicyStatus", ctx, ID, summary)} } diff --git a/app/controlplane/pkg/biz/workflowrun.go b/app/controlplane/pkg/biz/workflowrun.go index d423fbc02..53c163cbb 100644 --- a/app/controlplane/pkg/biz/workflowrun.go +++ b/app/controlplane/pkg/biz/workflowrun.go @@ -104,9 +104,7 @@ type WorkflowRunRepo interface { FindByID(ctx context.Context, ID uuid.UUID) (*WorkflowRun, error) FindByAttestationDigest(ctx context.Context, digest string) (*WorkflowRun, error) FindByIDInOrg(ctx context.Context, orgID, ID uuid.UUID) (*WorkflowRun, error) - // MarkAsFinished sets the final status of the run and closes its timeline. The policy - // results, when set, go on the closing event of a stored attestation. - MarkAsFinished(ctx context.Context, ID uuid.UUID, status WorkflowRunStatus, reason string, policies *WorkflowRunPolicyResults) error + MarkAsFinished(ctx context.Context, ID uuid.UUID, status WorkflowRunStatus, reason string) error // SaveAttestationBundle persists the digest and bundle. When // blockReleasedVersions is set it transactionally rejects the write if the // run's project version is already released (prerelease == false), locking @@ -435,18 +433,7 @@ func (uc *WorkflowRunUseCase) ExistsInWorkflow(ctx context.Context, workflowID, return res != nil && res.Workflow.ID.String() == workflowID, nil } -type MarkAsFinishedOpt func(*markAsFinishedOpts) - -type markAsFinishedOpts struct { - policies *WorkflowRunPolicyResults -} - -// WithPolicyResults sets the policy results of the stored attestation on the closing event -func WithPolicyResults(p *WorkflowRunPolicyResults) MarkAsFinishedOpt { - return func(o *markAsFinishedOpts) { o.policies = p } -} - -func (uc *WorkflowRunUseCase) MarkAsFinished(ctx context.Context, id string, status WorkflowRunStatus, reason string, opts ...MarkAsFinishedOpt) error { +func (uc *WorkflowRunUseCase) MarkAsFinished(ctx context.Context, id string, status WorkflowRunStatus, reason string) error { ctx, span := otelx.Start(ctx, workflowRunTracer, "WorkflowRunUseCase.MarkAsFinished") defer span.End() @@ -455,12 +442,7 @@ func (uc *WorkflowRunUseCase) MarkAsFinished(ctx context.Context, id string, sta return NewErrInvalidUUID(err) } - o := &markAsFinishedOpts{} - for _, opt := range opts { - opt(o) - } - - return uc.wfRunRepo.MarkAsFinished(ctx, runID, status, reason, o.policies) + return uc.wfRunRepo.MarkAsFinished(ctx, runID, status, reason) } // SaveAttestationOption customises how SaveAttestation persists the bundle. diff --git a/app/controlplane/pkg/biz/workflowrun_test.go b/app/controlplane/pkg/biz/workflowrun_test.go index d75e24b72..d38f8fc9b 100644 --- a/app/controlplane/pkg/biz/workflowrun_test.go +++ b/app/controlplane/pkg/biz/workflowrun_test.go @@ -175,7 +175,7 @@ func (s *workflowrunTestSuite) TestMarkAsFinished() { uuid, err := uuid.Parse(tc.id) require.NoError(t, err) - s.repo.On("MarkAsFinished", mock.Anything, uuid, tc.status, tc.reason, (*biz.WorkflowRunPolicyResults)(nil)).Return(nil) + s.repo.On("MarkAsFinished", mock.Anything, uuid, tc.status, tc.reason).Return(nil) } // s.repo.On("MarkAsFinished", s.ctx, id, tc.wantStatus, tc.reason).Return(tc.err) diff --git a/app/controlplane/pkg/biz/workflowrunevent.go b/app/controlplane/pkg/biz/workflowrunevent.go index 81eb7072d..aeadd74d1 100644 --- a/app/controlplane/pkg/biz/workflowrunevent.go +++ b/app/controlplane/pkg/biz/workflowrunevent.go @@ -23,7 +23,6 @@ import ( "time" "unicode/utf8" - "github.com/chainloop-dev/chainloop/pkg/attestation/renderer/chainloop" "github.com/chainloop-dev/chainloop/pkg/otelx" "github.com/go-kratos/kratos/v2/log" "github.com/google/uuid" @@ -42,10 +41,6 @@ const ( workflowRunEventKeyPrefix = "chainloop." // workflowRunEventExpiredMessage is the message of the closing event of an expired run workflowRunEventExpiredMessage = "expired" - // maxWorkflowRunEventStringBytes and maxWorkflowRunEventPolicyNames are the API bounds of - // an attribute string and of a list of policy names - maxWorkflowRunEventStringBytes = 256 - maxWorkflowRunEventPolicyNames = 100 ) type WorkflowRunEventSource string @@ -119,12 +114,8 @@ type WorkflowRunEventAttestationAttributes struct { RemoteState bool `json:"remote_state,omitempty"` CLIVersion string `json:"cli_version,omitempty"` AttestationDigest string `json:"attestation_digest,omitempty"` - // Results of the attestation policies: the ones evaluated at init on the start event, - // the ones of the stored attestation on the closing event + // Results of the attestation policies evaluated at init Policies *WorkflowRunEventPolicyCounts `json:"policies,omitempty"` - // Gated policies with violations in the stored attestation, empty when the check was - // bypassed. Set on the closing event only. - BlockingPolicies []string `json:"blocking_policies,omitempty"` } type WorkflowRunEventMaterialAttributes struct { @@ -263,73 +254,9 @@ func (uc *WorkflowRunEventUseCase) DeleteOlderThan(ctx context.Context, t time.T } } -// WorkflowRunPolicyResults are the policy results of a stored attestation. The closing -// event of its run carries them. -type WorkflowRunPolicyResults struct { - // Results of the attestation policies - Policies *WorkflowRunEventPolicyCounts - // Gated policies with violations, empty when the check was bypassed - BlockingPolicies []string -} - -// PolicyResultsFromPredicate returns the policy results of a stored attestation. It returns -// nil when the predicate does not hold its evaluations, for example when they are in the CAS. -func PolicyResultsFromPredicate(p chainloop.NormalizablePredicate) *WorkflowRunPolicyResults { - if p == nil || len(p.GetPolicyEvaluations()) == 0 { - return nil - } - - res := &WorkflowRunPolicyResults{Policies: &WorkflowRunEventPolicyCounts{}} - for key, evs := range p.GetPolicyEvaluations() { - for _, ev := range evs { - violated := slices.ContainsFunc(ev.Violations, func(v *chainloop.PolicyViolation) bool { return !v.Suppress }) - if violated && ev.Gate { - res.BlockingPolicies = append(res.BlockingPolicies, truncateBytes(ev.Name, maxWorkflowRunEventStringBytes)) - } - - // The materials have their own events - if key != chainloop.AttPolicyEvaluation { - continue - } - - counts := res.Policies - counts.Evaluated++ - switch { - case ev.Skipped: - counts.Skipped++ - case violated: - counts.Violated++ - if len(counts.ViolatedPolicies) < maxWorkflowRunEventPolicyNames { - counts.ViolatedPolicies = append(counts.ViolatedPolicies, truncateBytes(ev.Name, maxWorkflowRunEventStringBytes)) - } - default: - counts.Passed++ - } - } - } - - if status := p.GetPolicyEvaluationStatus(); status != nil && status.Bypassed { - res.BlockingPolicies = nil - } - - // A policy attached to several materials is one blocking policy - slices.Sort(res.BlockingPolicies) - res.BlockingPolicies = slices.Compact(res.BlockingPolicies) - if len(res.BlockingPolicies) > maxWorkflowRunEventPolicyNames { - res.BlockingPolicies = res.BlockingPolicies[:maxWorkflowRunEventPolicyNames] - } - - if res.Policies.Evaluated == 0 { - res.Policies = nil - } - - return res -} - // 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. -// The policy results are set only on the event of a stored attestation. -func ClosingWorkflowRunEvent(runID uuid.UUID, runStatus WorkflowRunStatus, reason, attestationDigest string, policies *WorkflowRunPolicyResults) *WorkflowRunEvent { +func ClosingWorkflowRunEvent(runID uuid.UUID, runStatus WorkflowRunStatus, reason, attestationDigest string) *WorkflowRunEvent { ev := &WorkflowRunEvent{ WorkflowRunID: runID, Source: WorkflowRunEventSourceControlPlane, @@ -341,13 +268,10 @@ func ClosingWorkflowRunEvent(runID uuid.UUID, runStatus WorkflowRunStatus, reaso case WorkflowRunSuccess: // Automatic events that succeed have no message ev.Status = WorkflowRunEventStatusSucceeded - attrs := &WorkflowRunEventAttestationAttributes{AttestationDigest: attestationDigest} - if policies != nil { - attrs.Policies = policies.Policies - attrs.BlockingPolicies = policies.BlockingPolicies - } - if attrs.AttestationDigest != "" || attrs.Policies != nil || len(attrs.BlockingPolicies) > 0 { - ev.Attributes = &WorkflowRunEventAttributes{Attestation: attrs} + if attestationDigest != "" { + ev.Attributes = &WorkflowRunEventAttributes{ + Attestation: &WorkflowRunEventAttestationAttributes{AttestationDigest: attestationDigest}, + } } case WorkflowRunCancelled: ev.Status = WorkflowRunEventStatusCanceled diff --git a/app/controlplane/pkg/biz/workflowrunevent_test.go b/app/controlplane/pkg/biz/workflowrunevent_test.go index fec4af294..329916027 100644 --- a/app/controlplane/pkg/biz/workflowrunevent_test.go +++ b/app/controlplane/pkg/biz/workflowrunevent_test.go @@ -20,70 +20,11 @@ import ( "testing" "unicode/utf8" - "github.com/chainloop-dev/chainloop/pkg/attestation/renderer/chainloop" "github.com/google/uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) -func TestPolicyResultsFromPredicate(t *testing.T) { - violation := []*chainloop.PolicyViolation{{Message: "bad"}} - suppressed := []*chainloop.PolicyViolation{{Message: "accepted", Suppress: true}} - evaluations := map[string][]*chainloop.PolicyEvaluation{ - chainloop.AttPolicyEvaluation: { - {Name: "att-passed"}, - {Name: "att-skipped", Skipped: true}, - {Name: "att-violated", Violations: violation}, - {Name: "att-suppressed", Violations: suppressed}, - {Name: "att-gate", Gate: true, Violations: violation}, - }, - "sbom": {{Name: "sbom-gate", Gate: true, Violations: violation}, {Name: "sbom-advisory", Violations: violation}}, - "image": {{Name: "sbom-gate", Gate: true, Violations: violation}, {Name: "suppressed-gate", Gate: true, Violations: suppressed}}, - } - - testCases := []struct { - name string - predicate chainloop.NormalizablePredicate - want *WorkflowRunPolicyResults - }{ - { - name: "attestation policy counts and the gates of all the policies", - predicate: &chainloop.ProvenancePredicateV02{PolicyEvaluations: evaluations}, - want: &WorkflowRunPolicyResults{ - Policies: &WorkflowRunEventPolicyCounts{Evaluated: 5, Passed: 2, Violated: 2, Skipped: 1, ViolatedPolicies: []string{"att-violated", "att-gate"}}, - BlockingPolicies: []string{"att-gate", "sbom-gate"}, - }, - }, - { - name: "bypassed check has no blocking policies", - predicate: &chainloop.ProvenancePredicateV02{PolicyEvaluations: evaluations, PolicyBlockBypassEnabled: true}, - want: &WorkflowRunPolicyResults{ - Policies: &WorkflowRunEventPolicyCounts{Evaluated: 5, Passed: 2, Violated: 2, Skipped: 1, ViolatedPolicies: []string{"att-violated", "att-gate"}}, - }, - }, - { - name: "material policies only", - predicate: &chainloop.ProvenancePredicateV02{PolicyEvaluations: map[string][]*chainloop.PolicyEvaluation{ - "sbom": {{Name: "sbom-advisory"}}, - }}, - want: &WorkflowRunPolicyResults{}, - }, - { - name: "evaluations not in the predicate", - predicate: &chainloop.ProvenancePredicateV02{}, - }, - { - name: "no predicate", - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - assert.Equal(t, tc.want, PolicyResultsFromPredicate(tc.predicate)) - }) - } -} - const ( sbomKey = "chainloop.material.sbom" shortText = "abc" @@ -91,7 +32,7 @@ const ( func TestValidateWorkflowRunEvent(t *testing.T) { material := &WorkflowRunEventAttributes{Material: &WorkflowRunEventMaterialAttributes{Name: "sbom"}} - attestation := &WorkflowRunEventAttributes{Attestation: &WorkflowRunEventAttestationAttributes{BlockingPolicies: []string{"gate"}}} + attestation := &WorkflowRunEventAttributes{Attestation: &WorkflowRunEventAttestationAttributes{ContractName: "build"}} testCases := []struct { name string @@ -151,22 +92,12 @@ func TestClosingWorkflowRunEvent(t *testing.T) { status WorkflowRunStatus reason string digest string - policies *WorkflowRunPolicyResults wantNil bool wantStatus WorkflowRunEventStatus wantMessage string - wantAttrs *WorkflowRunEventAttestationAttributes + wantDigest string }{ - {name: "store", status: WorkflowRunSuccess, reason: "ignored", digest: "sha256:abc", wantStatus: WorkflowRunEventStatusSucceeded, - wantAttrs: &WorkflowRunEventAttestationAttributes{AttestationDigest: "sha256:abc"}}, - {name: "store with policy results", status: WorkflowRunSuccess, digest: "sha256:abc", - policies: &WorkflowRunPolicyResults{Policies: &WorkflowRunEventPolicyCounts{Evaluated: 1, Violated: 1}, BlockingPolicies: []string{"gate"}}, - wantStatus: WorkflowRunEventStatusSucceeded, - wantAttrs: &WorkflowRunEventAttestationAttributes{AttestationDigest: "sha256:abc", - Policies: &WorkflowRunEventPolicyCounts{Evaluated: 1, Violated: 1}, BlockingPolicies: []string{"gate"}}}, - {name: "policy results only on a stored attestation", status: WorkflowRunError, reason: "build failed", - policies: &WorkflowRunPolicyResults{BlockingPolicies: []string{"gate"}}, - wantStatus: WorkflowRunEventStatusFailed, wantMessage: "build failed"}, + {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"}, @@ -175,7 +106,7 @@ func TestClosingWorkflowRunEvent(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - got := ClosingWorkflowRunEvent(runID, tc.status, tc.reason, tc.digest, tc.policies) + got := ClosingWorkflowRunEvent(runID, tc.status, tc.reason, tc.digest) if tc.wantNil { assert.Nil(t, got) return @@ -187,8 +118,8 @@ func TestClosingWorkflowRunEvent(t *testing.T) { assert.Equal(t, WorkflowRunEventKeyAttestation, got.Key) assert.Equal(t, tc.wantStatus, got.Status) assert.Equal(t, tc.wantMessage, got.Message) - if tc.wantAttrs != nil { - assert.Equal(t, tc.wantAttrs, got.Attributes.Attestation) + if tc.wantDigest != "" { + assert.Equal(t, tc.wantDigest, got.Attributes.Attestation.AttestationDigest) } else { assert.Nil(t, got.Attributes) } diff --git a/app/controlplane/pkg/data/ent/migrate/schema.go b/app/controlplane/pkg/data/ent/migrate/schema.go index bb88a1a26..54c8eff7f 100644 --- a/app/controlplane/pkg/data/ent/migrate/schema.go +++ b/app/controlplane/pkg/data/ent/migrate/schema.go @@ -1001,7 +1001,7 @@ var ( {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", "push"}}, + {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}, diff --git a/app/controlplane/pkg/data/ent/workflowrunevent/workflowrunevent.go b/app/controlplane/pkg/data/ent/workflowrunevent/workflowrunevent.go index 88b8e109f..d6848ea54 100644 --- a/app/controlplane/pkg/data/ent/workflowrunevent/workflowrunevent.go +++ b/app/controlplane/pkg/data/ent/workflowrunevent/workflowrunevent.go @@ -89,7 +89,7 @@ func SourceValidator(s biz.WorkflowRunEventSource) error { // 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", "push": + case "attestation", "material": return nil default: return fmt.Errorf("workflowrunevent: invalid enum value for type field: %q", _type) diff --git a/app/controlplane/pkg/data/workflowrun.go b/app/controlplane/pkg/data/workflowrun.go index 041524428..e00b5d7bc 100644 --- a/app/controlplane/pkg/data/workflowrun.go +++ b/app/controlplane/pkg/data/workflowrun.go @@ -416,7 +416,7 @@ func (r *WorkflowRunRepo) GetBundle(ctx context.Context, wrID uuid.UUID) ([]byte return att.Bundle, nil } -func (r *WorkflowRunRepo) MarkAsFinished(ctx context.Context, id uuid.UUID, status biz.WorkflowRunStatus, reason string, policies *biz.WorkflowRunPolicyResults) error { +func (r *WorkflowRunRepo) MarkAsFinished(ctx context.Context, id uuid.UUID, status biz.WorkflowRunStatus, reason string) error { ctx, span := otelx.Start(ctx, workflowRunRepoTracer, "WorkflowRunRepo.MarkAsFinished") defer span.End() @@ -432,13 +432,13 @@ func (r *WorkflowRunRepo) MarkAsFinished(ctx context.Context, id uuid.UUID, stat } // The store path saves the attestation digest before it finishes the run - return closeWorkflowRunTimeline(ctx, tx.Client(), id, status, reason, run.AttestationDigest, policies) + 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, policies *biz.WorkflowRunPolicyResults) error { - ev := biz.ClosingWorkflowRunEvent(runID, status, reason, digest, policies) +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 } @@ -593,7 +593,7 @@ func (r *WorkflowRunRepo) Expire(ctx context.Context, id uuid.UUID) error { return fmt.Errorf("failed to expire workflow run: %w", err) } - return closeWorkflowRunTimeline(ctx, tx.Client(), id, biz.WorkflowRunExpired, "", "", nil) + return closeWorkflowRunTimeline(ctx, tx.Client(), id, biz.WorkflowRunExpired, "", "") }) } diff --git a/app/controlplane/pkg/data/workflowrunevent_integration_test.go b/app/controlplane/pkg/data/workflowrunevent_integration_test.go index d2e2a3038..ea5bf5f48 100644 --- a/app/controlplane/pkg/data/workflowrunevent_integration_test.go +++ b/app/controlplane/pkg/data/workflowrunevent_integration_test.go @@ -93,7 +93,7 @@ func (s *workflowRunEventIntegrationTestSuite) TestCreate() { name: "finished run is rejected", setup: func() uuid.UUID { id := s.newRun() - s.Require().NoError(s.Repos.WorkflowRunRepo.MarkAsFinished(ctx, id, biz.WorkflowRunSuccess, "", nil)) + s.Require().NoError(s.Repos.WorkflowRunRepo.MarkAsFinished(ctx, id, biz.WorkflowRunSuccess, "")) return id }, maxEvents: 10, @@ -256,17 +256,13 @@ func (s *workflowRunEventIntegrationTestSuite) TestClosingEvent() { ctx := context.Background() runRepo := s.Repos.WorkflowRunRepo const digest = "sha256:deadbeef" - policies := &biz.WorkflowRunPolicyResults{ - Policies: &biz.WorkflowRunEventPolicyCounts{Evaluated: 2, Passed: 1, Violated: 1, ViolatedPolicies: []string{"gate"}}, - BlockingPolicies: []string{"gate"}, - } testCases := []struct { name string finish func(id uuid.UUID) error wantStatus biz.WorkflowRunEventStatus wantMessage string - wantAttrs *biz.WorkflowRunEventAttestationAttributes + wantDigest string }{ { name: "store", @@ -274,17 +270,15 @@ func (s *workflowRunEventIntegrationTestSuite) TestClosingEvent() { if err := runRepo.SaveAttestationDigest(ctx, id, digest, false); err != nil { return err } - return runRepo.MarkAsFinished(ctx, id, biz.WorkflowRunSuccess, "", policies) + return runRepo.MarkAsFinished(ctx, id, biz.WorkflowRunSuccess, "") }, wantStatus: biz.WorkflowRunEventStatusSucceeded, - wantAttrs: &biz.WorkflowRunEventAttestationAttributes{ - AttestationDigest: digest, Policies: policies.Policies, BlockingPolicies: policies.BlockingPolicies, - }, + wantDigest: digest, }, { name: "reset with cancellation", finish: func(id uuid.UUID) error { - return runRepo.MarkAsFinished(ctx, id, biz.WorkflowRunCancelled, "user canceled", nil) + return runRepo.MarkAsFinished(ctx, id, biz.WorkflowRunCancelled, "user canceled") }, wantStatus: biz.WorkflowRunEventStatusCanceled, wantMessage: "user canceled", @@ -292,7 +286,7 @@ func (s *workflowRunEventIntegrationTestSuite) TestClosingEvent() { { name: "reset with failure", finish: func(id uuid.UUID) error { - return runRepo.MarkAsFinished(ctx, id, biz.WorkflowRunError, "build failed", nil) + return runRepo.MarkAsFinished(ctx, id, biz.WorkflowRunError, "build failed") }, wantStatus: biz.WorkflowRunEventStatusFailed, wantMessage: "build failed", @@ -323,9 +317,9 @@ func (s *workflowRunEventIntegrationTestSuite) TestClosingEvent() { s.Equal(biz.WorkflowRunEventKeyAttestation, last.Key) s.Equal(tc.wantStatus, last.Status) s.Equal(tc.wantMessage, last.Message) - if tc.wantAttrs != nil { + if tc.wantDigest != "" { s.Require().NotNil(last.Attributes) - s.Equal(tc.wantAttrs, last.Attributes.Attestation) + s.Equal(tc.wantDigest, last.Attributes.Attestation.AttestationDigest) } else { s.Nil(last.Attributes) } @@ -337,7 +331,7 @@ func (s *workflowRunEventIntegrationTestSuite) TestClosingEvent() { func (s *workflowRunEventIntegrationTestSuite) TestExpireSkipsFinishedRun() { ctx := context.Background() runID := s.newRun() - s.Require().NoError(s.Repos.WorkflowRunRepo.MarkAsFinished(ctx, runID, biz.WorkflowRunSuccess, "", nil)) + 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) diff --git a/docs/plans/issue-3825-attestation-progress-events.md b/docs/plans/issue-3825-attestation-progress-events.md index 3be0331f9..03ac3b038 100644 --- a/docs/plans/issue-3825-attestation-progress-events.md +++ b/docs/plans/issue-3825-attestation-progress-events.md @@ -152,7 +152,7 @@ R-003, R-005, R-008 (M1) and R-009 (M2). `app/controlplane/api/controlplane/v1/w + 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; repeated string blocking_policies = 8; } ++ 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 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 PolicyCounts { int32 evaluated = 1; int32 passed = 2; int32 violated = 3; int32 skipped = 4; repeated string violated_policies = 5; } +} @@ -211,7 +211,7 @@ 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, R-010, R-011 | none | +| 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, R-010 | none | | M2 | Custom events | A pipeline adds its own steps to the timeline with `chainloop attestation event` | R-009 | M1 | ### M1: Automatic progress @@ -260,13 +260,13 @@ Add the `WorkflowRunEvent` Ent schema with an edge to the run and cascade delete
-03 / 07 · Close the timeline when the run is stored, canceled, or expired (R-011) +03 / 07 · Close the timeline when the run is stored, canceled, or expired (R-006) -Wrap the status update and the insert of the closing `chainloop.attestation` event in one transaction, with source CONTROL_PLANE. `Expire` locks the run row and skips the update and the insert when the run is no longer initialized. So a run that a store finishes during the sweep gets one closing event. On store, read the attestation digest from the run row, because the store path saves it before it finishes the run. The store path also reads the predicate of the attestation that it stores. It passes the attestation policy counts and the gated policies with violations to `MarkAsFinished` (spec R-011). The use case takes them as an option, and the repository as a new parameter. The list of gated policies is empty when the predicate shows a bypass of the check. When the policy evaluations are in the CAS and not in the predicate, the closing event has no policy results. +Wrap the status update and the insert of the closing `chainloop.attestation` event in one transaction, with source CONTROL_PLANE. `Expire` locks the run row and skips the update and the insert when the run is no longer initialized. So a run that a store finishes during the sweep gets one closing event. On store, read the attestation digest from the run row, because the store path saves it before it finishes the run. Do not change the signature. | Run change | Closing status | Code | |------------|----------------|------| -| Store | succeeded, with the digest, the attestation policy counts, and the gated policies | `MarkAsFinished` | +| Store | succeeded, with the digest | `MarkAsFinished` | | Reset, trigger CANCELLATION | canceled | `MarkAsFinished` | | Reset, trigger FAILURE | failed | `MarkAsFinished` | | Expiry | failed, message "expired" | `Expire` | @@ -274,7 +274,6 @@ Wrap the status update and the insert of the closing `chainloop.attestation` eve | File | Change | |------|--------| | `app/controlplane/pkg/data/workflowrun.go` | Use a transaction in `MarkAsFinished` and `Expire`, and insert the event. | -| `app/controlplane/pkg/biz/workflowrunevent.go`, `app/controlplane/internal/service/attestation.go` | Read the policy results from the stored predicate, and pass them to `MarkAsFinished`. | | `app/controlplane/pkg/data/workflowrunevent_integration_test.go` | Add a table test for the four rows, and a test that expiry skips a stored run. | | `app/controlplane/pkg/biz/attestationstate_integration_test.go` | Change the existing test that expires a finished run to use a run in progress, because expiry now skips a finished run. | @@ -323,7 +322,7 @@ Add a retention duration to the attestations section of the config, with a defau
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`). `push` records no event: the closing event of the store shows it (spec D-011). Move the gate check from the push command into the push action, as a function that returns the blocking policies. 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. 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 | |-----------------------------|----------| @@ -334,16 +333,15 @@ 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 of `init` and `add`. 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 the gate function. 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. |
07 / 07 · Show the progress in workflow run describe (R-004) -`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 closing event of the store, or else from the start event. It shows the timeline as a tree: one line for each step, with the events of a repeated step below it. The last line is "pushed and stored" from the closing event, with the policy counts, the gated policies, 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. 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 `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 of a run in progress from the start event. It shows the timeline as a tree: one line for each step, with the events of a repeated step below it. 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. Any error from `ListEvents` keeps the current output, and `describe` does not fail. `Unimplemented` gives a debug log, and other errors give a warning. | File | Change | |------|--------| diff --git a/docs/specs/issue-3825-attestation-progress-events.md b/docs/specs/issue-3825-attestation-progress-events.md index 9d43ed1c6..1c082408a 100644 --- a/docs/specs/issue-3825-attestation-progress-events.md +++ b/docs/specs/issue-3825-attestation-progress-events.md @@ -85,11 +85,9 @@ It labels the material and policy data as reported progress. For a finished run, ### R-005: Only safe data in automatic events An automatic event MUST contain only names, types, statuses, counts, digests, timestamps, and the error text of a failed action. It also holds the material value that `attestation status` shows, cut to 256 characters. That is the text of a string material, and the reference or file name of other materials. It MUST NOT contain environment variables, annotations, commit data, file content, policy arguments, or raw policy input and output. -### ~~R-006: The run closes its timeline~~ -Superseded by R-011. - -~~The control plane MUST record the closing event of the attestation when it stores, cancels, or expires the run. The status is succeeded on store, with the attestation digest and no message. On `attestation reset`, it is canceled for a cancellation and failed for a failure, with the reset reason as the message, cut to 1 KB. It is failed on expiry, with the message "expired". The CLI never records it. It writes the event in the same place as the change of run status. It MUST accept new events for a run only while the run is in progress.~~ -- ~~Done when: the last event of each finished run agrees with the status of the run, also for an expired run.~~ +### R-006: The run closes its timeline +The control plane MUST record the closing event of the attestation when it stores, cancels, or expires the run. The status is succeeded on store, with the attestation digest and no message. On `attestation reset`, it is canceled for a cancellation and failed for a failure, with the reset reason as the message, cut to 1 KB. It is failed on expiry, with the message "expired". The CLI never records it. It writes the event in the same place as the change of run status. It MUST accept new events for a run only while the run is in progress. +- Done when: the last event of each finished run agrees with the status of the run, also for an expired run. ### R-007: Retention The control plane MUST delete run events that are older than a retention period. The default is 90 days. An operator can change it in the control plane configuration. The age comes from the time of each event. The run and its attestation stay. A periodic job deletes the events, with the same pattern as the run expiry job. @@ -101,16 +99,12 @@ The control plane MUST reject an event that goes past a limit. The limits are 1, `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 (R-011, D-011). The actions are: +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: The run closes its timeline -Supersedes R-006. The control plane MUST record the closing event of the attestation when it stores, cancels, or expires the run. The status is succeeded on store. The event then has no message. It has the attestation digest and the results of the attestation policies of the stored attestation. It also has the names of the gated policies with violations. The list of gated policies is empty when the user bypassed the policy check. A blocked push is stored as today, so its closing event is succeeded, with the gated policies. On `attestation reset`, the status is canceled for a cancellation and failed for a failure, with the reset reason as the message, cut to 1 KB. It is failed on expiry, with the message "expired". The CLI never records it. It writes the event in the same place as the change of run status. It MUST accept new events for a run only while the run is in progress. -- Done when: the last event of each finished run agrees with the status of the run, also for an expired run. The closing event of a stored attestation has the same policy results as the attestation. - ## 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. @@ -131,7 +125,7 @@ Supersedes R-006. The control plane MUST record the closing event of the attesta - 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 closing event of the store shows the push, with the gated policies of a blocked push (R-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 closing event of the store holds the attestation policies of the stored attestation. 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. @@ -157,7 +151,7 @@ sequenceDiagram CP-->>U: signed attestation + timeline as history ``` -Dashed arrows are best effort. A failed event does not stop the attestation. Since D-011, the CLI sends no push event. The closing event of the store has the policy results of the attestation. +Dashed arrows are best effort. A failed event does not stop the attestation. Since D-011, the CLI sends no push event. ## Decision Record @@ -234,11 +228,12 @@ 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: The closing event of the store replaces the push event -The CLI records no `chainloop.push` event. The control plane reads the policy results and the gated policies from the attestation that it stores, and puts them on the closing event (R-011). The event types are attestation, material, and custom. -- Why: the push event and the closing event described one step for the user, "pushed and stored", in two events. The control plane reads the results from the signed attestation, so they agree with the evidence. A failed send of the CLI can no longer lose them (R-002). +### 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. After a retry, the push event can disagree with the stored attestation. + - 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 ## Open Questions @@ -247,7 +242,7 @@ 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). R-010 and R-011 supersede R-001 and R-006. +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. 2. **Custom events.** `chainloop attestation event` (R-009). ## Risks @@ -258,7 +253,7 @@ 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. | | 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).~~ | @@ -278,4 +273,4 @@ Contract: `image` (container image, required), `sbom` (CycloneDX, required), and ~~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). The closing event of the store has the attestation digest. It also has the attestation policies of the stored attestation: 2 evaluated, 2 passed, 0 violated, 0 skipped. When a policy gate blocks the push, the control plane still stores the attestation. The closing event is then succeeded, with the names of the gated policies. Reset and expiry follow R-011. +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. From 785d267b4c820b110c7f1f0b56250d20bb948434 Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Tue, 1 Dec 2026 00:01:36 +0100 Subject: [PATCH 14/20] docs(cli): correct the comment on the policy status of the timeline Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1cdb3220-119c-4a14-ac50-52d5437ee4eb --- app/cli/cmd/workflow_run_timeline.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/app/cli/cmd/workflow_run_timeline.go b/app/cli/cmd/workflow_run_timeline.go index 83dcc8fbe..ac513ec2a 100644 --- a/app/cli/cmd/workflow_run_timeline.go +++ b/app/cli/cmd/workflow_run_timeline.go @@ -209,8 +209,9 @@ func timelineEnd(closing *action.RunEvent, stored *action.PolicyEvaluationStatus } // timelinePolicyStatus is the policy result of the stored attestation. A blocked attestation -// is stored too, and the push command fails after the store. The attestation table above -// the timeline has the details of the gates. +// 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 From dba4b39d240ac651b88f83d460f4bd21a071f394 Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Tue, 1 Dec 2026 11:58:02 +0100 Subject: [PATCH 15/20] feat: return the run progress and events in the workflow run view The control plane now builds the progress of a run in progress and returns it, with the events of the run, in WorkflowRunService.View, so the CLI, the UI and other tools render it with no logic of their own. ListEvents and its after_event_id option are removed. The start event lists the materials that init resolves, from the contract and its policy groups, so the progress also counts the materials that policy groups require. A failed add after a successful one keeps the material as provided, with the error. Spec: R-011 supersedes R-003, D-012 supersedes D-007. Refs #3825 Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1cdb3220-119c-4a14-ac50-52d5437ee4eb --- app/cli/cmd/workflow_run_timeline.go | 27 +- app/cli/cmd/workflow_run_timeline_test.go | 28 +- app/cli/pkg/action/runevents.go | 38 +- app/cli/pkg/action/runevents_compat_test.go | 4 +- app/cli/pkg/action/runevents_test.go | 22 + app/cli/pkg/action/workflow_run_describe.go | 252 ++--- .../pkg/action/workflow_run_describe_test.go | 220 +---- .../api/controlplane/v1/workflow_run.pb.go | 888 ++++++++++++------ .../api/controlplane/v1/workflow_run.proto | 77 +- .../controlplane/v1/workflow_run_grpc.pb.go | 47 +- .../frontend/controlplane/v1/workflow_run.ts | 788 ++++++++++++---- ...vent.AttestationAttributes.jsonschema.json | 14 + ...RunEvent.AttestationAttributes.schema.json | 14 + ...wRunEvent.ExpectedMaterial.jsonschema.json | 31 + ...kflowRunEvent.ExpectedMaterial.schema.json | 31 + ...rkflowRunProgress.Material.jsonschema.json | 88 ++ ...1.WorkflowRunProgress.Material.schema.json | 88 ++ ...ane.v1.WorkflowRunProgress.jsonschema.json | 49 + ...olplane.v1.WorkflowRunProgress.schema.json | 49 + ...unServiceListEventsRequest.jsonschema.json | 29 - ...lowRunServiceListEventsRequest.schema.json | 29 - ...nServiceListEventsResponse.jsonschema.json | 15 - ...owRunServiceListEventsResponse.schema.json | 15 - ...ServiceViewResponse.Result.jsonschema.json | 11 + ...wRunServiceViewResponse.Result.schema.json | 11 + .../internal/service/workflowrun.go | 115 ++- .../workflowrunevent_integration_test.go | 66 +- app/controlplane/pkg/authz/authz.go | 5 +- .../pkg/biz/mocks/WorkflowRunEventRepo.go | 30 +- app/controlplane/pkg/biz/workflowrunevent.go | 29 +- .../pkg/biz/workflowrunprogress.go | 205 ++++ .../pkg/biz/workflowrunprogress_test.go | 190 ++++ app/controlplane/pkg/data/workflowrunevent.go | 26 +- .../data/workflowrunevent_integration_test.go | 24 +- .../issue-3825-attestation-progress-events.md | 71 +- .../issue-3825-attestation-progress-events.md | 42 +- 36 files changed, 2483 insertions(+), 1185 deletions(-) create mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.ExpectedMaterial.jsonschema.json create mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.ExpectedMaterial.schema.json create mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunProgress.Material.jsonschema.json create mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunProgress.Material.schema.json create mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunProgress.jsonschema.json create mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunProgress.schema.json delete mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceListEventsRequest.jsonschema.json delete mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceListEventsRequest.schema.json delete mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceListEventsResponse.jsonschema.json delete mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceListEventsResponse.schema.json create mode 100644 app/controlplane/pkg/biz/workflowrunprogress.go create mode 100644 app/controlplane/pkg/biz/workflowrunprogress_test.go diff --git a/app/cli/cmd/workflow_run_timeline.go b/app/cli/cmd/workflow_run_timeline.go index ac513ec2a..01c7ae9bb 100644 --- a/app/cli/cmd/workflow_run_timeline.go +++ b/app/cli/cmd/workflow_run_timeline.go @@ -18,6 +18,7 @@ package cmd import ( "fmt" "io" + "slices" "strings" "time" "unicode/utf8" @@ -100,7 +101,7 @@ func renderRunTimeline(w io.Writer, events []*action.RunEvent, progress *action. if progress != nil { for _, m := range progress.Materials { - if m.InContract && !reported[m.Name] { + 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)}, @@ -246,11 +247,23 @@ func timelineDigest(e *action.RunEvent) string { // 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(last.Status), name: timelineEvidenceAction(last, name)} + node := &timelineNode{at: timelineTime(evs[0].CreatedAt), symbol: timelineSymbol(shown.Status), name: timelineEvidenceAction(shown, name)} // details in order: type, value, requirement, policies - m := last.Material + m := shown.Material if m != nil && m.MaterialType != "" { node.details = append(node.details, m.MaterialType) } @@ -338,12 +351,12 @@ func timelineNameWidth(nodes []*timelineNode) int { // timelineRequirement shows how the contract asks for a material func timelineRequirement(m *action.RunProgressMaterial) string { - switch { - case !m.InContract: + switch m.Requirement { + case action.RunMaterialNotInContract: return "not in contract" - case m.Group != "": + case action.RunMaterialOneOfGroup: return "one of " + m.Group - case m.Required: + case action.RunMaterialRequired: return "required" default: return "optional" diff --git a/app/cli/cmd/workflow_run_timeline_test.go b/app/cli/cmd/workflow_run_timeline_test.go index ef22da351..53a6ed35a 100644 --- a/app/cli/cmd/workflow_run_timeline_test.go +++ b/app/cli/cmd/workflow_run_timeline_test.go @@ -61,10 +61,10 @@ func TestRenderRunTimeline(t *testing.T) { RequiredTotal: 2, RequiredProvided: 1, AttestationPolicies: &action.RunEventPolicyCount{Evaluated: 2, Passed: 2}, Materials: []*action.RunProgressMaterial{ - {Name: "sbom", InContract: true, Required: true, Provided: true}, - {Name: "image", InContract: true, Required: true}, - {Name: "sast-report", InContract: true, Provided: true}, - {Name: "build-log", Provided: true}, + {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" + @@ -77,6 +77,26 @@ func TestRenderRunTimeline(t *testing.T) { "├─ ○ 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{ diff --git a/app/cli/pkg/action/runevents.go b/app/cli/pkg/action/runevents.go index 54b4b90c0..3649bc986 100644 --- a/app/cli/pkg/action/runevents.go +++ b/app/cli/pkg/action/runevents.go @@ -50,6 +50,9 @@ const ( // 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 @@ -58,9 +61,6 @@ const ( runEventKeyAttestation = runEventKeyPrefix + "attestation" runEventKeyMaterial = runEventKeyPrefix + "material" runEventKeyMaterialPrefix = runEventKeyMaterial + "." - - runEventStatusStarted = "started" - runEventStatusFailed = "failed" ) // runEventRecorder sends progress events of an attestation to the control plane. @@ -147,16 +147,36 @@ func attestationStartedEvent(state *api.CraftingState, remoteState bool, cliVers 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, ""), + 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 { diff --git a/app/cli/pkg/action/runevents_compat_test.go b/app/cli/pkg/action/runevents_compat_test.go index a3b7b837c..fa1696db1 100644 --- a/app/cli/pkg/action/runevents_compat_test.go +++ b/app/cli/pkg/action/runevents_compat_test.go @@ -56,8 +56,8 @@ func TestRunEventsAgainstOlderControlPlane(t *testing.T) { conn := newBufConn(t, func(s *grpc.Server) { attDesc := withoutMethods(pb.AttestationService_ServiceDesc, "RecordEvent") s.RegisterService(&attDesc, attSvc) - runDesc := withoutMethods(pb.WorkflowRunService_ServiceDesc, "ListEvents") - s.RegisterService(&runDesc, runSvc) + // an older View returns no events and no progress + pb.RegisterWorkflowRunServiceServer(s, runSvc) }) t.Run("the recorder gets Unimplemented and turns off", func(t *testing.T) { diff --git a/app/cli/pkg/action/runevents_test.go b/app/cli/pkg/action/runevents_test.go index 3c8818323..fcbb5b411 100644 --- a/app/cli/pkg/action/runevents_test.go +++ b/app/cli/pkg/action/runevents_test.go @@ -510,3 +510,25 @@ func TestAttestationAddRecordsEvents(t *testing.T) { }) } } + +// 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: "cdx", Type: schemaapi.CraftingSchema_Material_SBOM_CYCLONEDX_JSON, Group: "sboms"}, + }}}, + 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, "sboms", got[2].GetGroup()) +} diff --git a/app/cli/pkg/action/workflow_run_describe.go b/app/cli/pkg/action/workflow_run_describe.go index e48405424..4ad136b2b 100644 --- a/app/cli/pkg/action/workflow_run_describe.go +++ b/app/cli/pkg/action/workflow_run_describe.go @@ -27,7 +27,6 @@ import ( "unicode/utf8" pb "github.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1" - schemaapi "github.com/chainloop-dev/chainloop/app/controlplane/api/workflowcontract/v1" attv1 "github.com/chainloop-dev/chainloop/pkg/attestation/crafter/api/attestation/v1" "github.com/chainloop-dev/chainloop/pkg/attestation/renderer/chainloop" "github.com/chainloop-dev/chainloop/pkg/attestation/verifier" @@ -39,8 +38,6 @@ 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 { @@ -54,7 +51,7 @@ type WorkflowRunItemFull struct { 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 from the contract and the events + // Progress of a run in progress, built by the control plane Progress *RunProgress `json:"progress,omitempty"` } @@ -217,11 +214,11 @@ func (action *WorkflowRunDescribe) Run(ctx context.Context, opts *WorkflowRunDes item.WorkflowRun.FinishedAt = toTimePtr(wr.FinishedAt.AsTime()) } - // Progress events are optional: with no events, describe shows the run as before - item.Events = action.listRunEvents(ctx, wr.GetId()) - if wr.GetStatus() == pb.RunStatus_RUN_STATUS_INITIALIZED && len(item.Events) > 0 { - item.Progress = buildRunProgress(runContractMaterials(wr.GetContractVersion()), item.Events, time.Now()) + // An older control plane returns no events and no progress: describe shows the run as before + for _, e := range resp.GetResult().GetEvents() { + item.Events = append(item.Events, pbRunEventToAction(e)) } + item.Progress = pbRunProgressToAction(resp.GetResult().GetProgress()) att := resp.GetResult().GetAttestation() // The item does not have associated attestation @@ -571,62 +568,46 @@ type RunEventPolicyCount struct { ViolatedPolicies []string `json:"violated_policies,omitempty"` } -// RunProgress is the progress of a run in progress, built from the contract and the reported events +// 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"` - // Results of the attestation policies of the latest evaluation phase + // 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"` - RequiredTotal int `json:"required_total"` - RequiredProvided int `json:"required_provided"` - Steps []*RunProgressStep `json:"steps"` } type RunProgressMaterial struct { - Name string `json:"name"` - Type string `json:"type"` - InContract bool `json:"in_contract"` - Required bool `json:"required"` - // a group of the contract needs at least one of its materials - Group string `json:"group,omitempty"` - Provided bool `json:"provided"` - Value string `json:"value,omitempty"` - Policies *RunEventPolicyCount `json:"policies,omitempty"` - FailedAdds int `json:"failed_adds,omitempty"` - // error of the latest add, when it failed - Error string `json:"error,omitempty"` -} - -// RunProgressStep groups the events with the same key -type RunProgressStep struct { - Key string `json:"key"` - Name string `json:"name"` - StartedAt *time.Time `json:"started_at,omitempty"` - Duration time.Duration `json:"duration"` - Status string `json:"status"` - Events int `json:"events"` + 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"` } -// listRunEvents returns the events of the run. It returns nil when the control plane cannot -// return them, for example an older one, so that describe shows the run as before. -func (action *WorkflowRunDescribe) listRunEvents(ctx context.Context, runID string) []*RunEvent { - client := pb.NewWorkflowRunServiceClient(action.cfg.CPConnection) - resp, err := client.ListEvents(ctx, &pb.WorkflowRunServiceListEventsRequest{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 events") - } else { - action.cfg.Logger.Warn().Err(err).Msg("failed to retrieve the progress events of the run") - } - return nil - } - - events := make([]*RunEvent, 0, len(resp.GetEvents())) - for _, e := range resp.GetEvents() { - events = append(events, pbRunEventToAction(e)) - } - - return events -} +// 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{ @@ -671,142 +652,49 @@ func pbRunEventPolicyCountToAction(in *pb.WorkflowRunEvent_PolicyCounts) *RunEve } } -// runContractMaterials returns the materials of the contract of the run, from the V2 schema when present -func runContractMaterials(cv *pb.WorkflowContractVersionItem) []*schemaapi.CraftingSchema_Material { - if v2 := parseContractV2(cv.GetRawContract()); v2 != nil && v2.GetSpec() != nil { - return v2.GetSpec().GetMaterials() +// 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 } - //nolint:staticcheck // the V1 schema is the fallback for contracts with no V2 body - return cv.GetV1().GetMaterials() + return strings.TrimPrefix(key, runEventKeyPrefix) } -// buildRunProgress joins the contract materials with the latest event of each material, and -// groups the events by key into steps. now is the time used for the duration of open steps. -func buildRunProgress(contractMaterials []*schemaapi.CraftingSchema_Material, events []*RunEvent, now time.Time) *RunProgress { - progress := &RunProgress{Materials: make([]*RunProgressMaterial, 0)} - - // latest event and failed adds of each material, in the order they were first reported - latest := make(map[string]*RunEvent) - failed := make(map[string]int) - var order []string - for _, e := range events { - switch { - case e.Material != nil && e.Material.Name != "": - name := e.Material.Name - if _, ok := latest[name]; !ok { - order = append(order, name) - } - latest[name] = e - if e.Status == runEventStatusFailed { - failed[name]++ - } - // the attestation policy results of init - case e.Attestation != nil && e.Attestation.Policies != nil: - progress.AttestationPolicies = e.Attestation.Policies - } +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, } - - fill := func(m *RunProgressMaterial) { - e, ok := latest[m.Name] - if !ok { - return - } - - m.FailedAdds = failed[m.Name] - if e.Status == runEventStatusFailed { - m.Error = e.Message - return - } - - m.Provided = true - m.Value = e.Material.Value - m.Policies = e.Material.Policies - if m.Type == "" { - m.Type = e.Material.MaterialType - } + pbToActionRunMaterialStatus = map[pb.WorkflowRunProgress_Status]string{ + pb.WorkflowRunProgress_STATUS_MISSING: RunMaterialMissing, + pb.WorkflowRunProgress_STATUS_PROVIDED: RunMaterialProvided, + pb.WorkflowRunProgress_STATUS_FAILED: RunMaterialFailed, } +) - inContract := make(map[string]struct{}, len(contractMaterials)) - // Grouped materials are required at the group level, "at least one of", as attestation - // status shows them. So each group counts once, provided when any member is. - groupProvided := make(map[string]bool) - for _, cm := range contractMaterials { - inContract[cm.GetName()] = struct{}{} - m := &RunProgressMaterial{ - Name: cm.GetName(), Type: cm.GetType().String(), InContract: true, - Required: !cm.GetOptional() && cm.GetGroup() == "", Group: cm.GetGroup(), - } - fill(m) - switch { - case m.Group != "": - groupProvided[m.Group] = groupProvided[m.Group] || m.Provided - case m.Required: - progress.RequiredTotal++ - if m.Provided { - progress.RequiredProvided++ - } - } - progress.Materials = append(progress.Materials, m) - } - - for _, provided := range groupProvided { - progress.RequiredTotal++ - if provided { - progress.RequiredProvided++ - } - } - - for _, name := range order { - if _, ok := inContract[name]; ok { - continue - } - m := &RunProgressMaterial{Name: name} - fill(m) - progress.Materials = append(progress.Materials, m) - } - - progress.Steps = buildRunSteps(events, now) - - return progress -} - -// buildRunSteps groups the events by key, in the order of their first event -func buildRunSteps(events []*RunEvent, now time.Time) []*RunProgressStep { - steps := make([]*RunProgressStep, 0) - byKey := make(map[string]*RunProgressStep) - last := make(map[string]*time.Time) - - for _, e := range events { - step, ok := byKey[e.Key] - if !ok { - step = &RunProgressStep{Key: e.Key, Name: RunStepName(e.Key), StartedAt: e.CreatedAt} - byKey[e.Key] = step - steps = append(steps, step) - } - step.Events++ - step.Status = e.Status - last[e.Key] = e.CreatedAt +func pbRunProgressToAction(in *pb.WorkflowRunProgress) *RunProgress { + if in == nil { + return nil } - for _, s := range steps { - end := last[s.Key] - if s.Status == runEventStatusStarted { - end = &now - } - if s.StartedAt != nil && end != nil && end.After(*s.StartedAt) { - s.Duration = end.Sub(*s.StartedAt) - } + out := &RunProgress{ + RequiredTotal: int(in.GetRequiredTotal()), RequiredProvided: int(in.GetRequiredProvided()), + AttestationPolicies: pbRunEventPolicyCountToAction(in.GetAttestationPolicies()), + Materials: make([]*RunProgressMaterial, 0, len(in.GetMaterials())), } - - return steps -} - -// 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 + 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 strings.TrimPrefix(key, runEventKeyPrefix) + 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 102b8e0ed..d9e62c27d 100644 --- a/app/cli/pkg/action/workflow_run_describe_test.go +++ b/app/cli/pkg/action/workflow_run_describe_test.go @@ -20,18 +20,14 @@ import ( "encoding/json" "os" "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/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" ) @@ -165,180 +161,22 @@ func TestPBPolicyEvaluationsRefToAction(t *testing.T) { } } -func materialRunEvent(at time.Time, name, status, message string) *RunEvent { - return &RunEvent{ - CreatedAt: &at, Type: "material", Key: "chainloop.material." + name, Status: status, Message: message, - Material: &RunEventMaterial{Name: name, MaterialType: testSBOMKind, Value: name + ".json"}, - } -} - -func TestBuildRunProgress(t *testing.T) { - start := time.Date(2026, 11, 30, 10, 0, 0, 0, time.UTC) - now := start.Add(5*time.Minute + 45*time.Second) - contract := []*schemaapi.CraftingSchema_Material{ - {Name: testSBOM, Type: schemaapi.CraftingSchema_Material_SBOM_CYCLONEDX_JSON}, - {Name: testImage, Type: schemaapi.CraftingSchema_Material_CONTAINER_IMAGE}, - {Name: "sast-report", Type: schemaapi.CraftingSchema_Material_SARIF, Optional: true}, - } - started := &RunEvent{CreatedAt: &start, Type: "attestation", Key: testAttKey, Status: "started"} - - testCases := []struct { - name string - events []*RunEvent - // expected state of each material, by name - want map[string]RunProgressMaterial - wantRequired [2]int // provided, total - wantStepDuration map[string]time.Duration - }{ - { - name: "failed add shows the material as missing with the error", - events: []*RunEvent{ - started, - materialRunEvent(start.Add(3*time.Minute), testSBOM, "failed", "invalid CycloneDX document"), - }, - want: map[string]RunProgressMaterial{ - testSBOM: {Required: true, InContract: true, Provided: false, FailedAdds: 1, Error: "invalid CycloneDX document"}, - testImage: {Required: true, InContract: true}, - "sast-report": {InContract: true}, - }, - wantRequired: [2]int{0, 2}, - wantStepDuration: map[string]time.Duration{testAttKey: 5*time.Minute + 45*time.Second}, - }, - { - name: "failed then repeated add shows the material as provided", - events: []*RunEvent{ - started, - materialRunEvent(start.Add(3*time.Minute), testSBOM, "failed", "invalid CycloneDX document"), - materialRunEvent(start.Add(4*time.Minute), testSBOM, "succeeded", ""), - }, - want: map[string]RunProgressMaterial{ - testSBOM: {Required: true, InContract: true, Provided: true, FailedAdds: 1, Value: testSBOMFile}, - testImage: {Required: true, InContract: true}, - }, - wantRequired: [2]int{1, 2}, - wantStepDuration: map[string]time.Duration{testSBOMKey: time.Minute}, - }, - { - name: "material not in the contract", - events: []*RunEvent{ - started, - materialRunEvent(start.Add(time.Minute), "build-log", "succeeded", ""), - }, - want: map[string]RunProgressMaterial{ - "build-log": {InContract: false, Provided: true, Value: "build-log.json"}, - testSBOM: {Required: true, InContract: true}, - }, - wantRequired: [2]int{0, 2}, - }, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - got := buildRunProgress(contract, tc.events, now) - - byName := make(map[string]*RunProgressMaterial) - for _, m := range got.Materials { - byName[m.Name] = m - } - - for name, want := range tc.want { - m, ok := byName[name] - require.True(t, ok, "material %q", name) - assert.Equal(t, want.Required, m.Required, "required %q", name) - assert.Equal(t, want.InContract, m.InContract, "in contract %q", name) - assert.Equal(t, want.Provided, m.Provided, "provided %q", name) - assert.Equal(t, want.FailedAdds, m.FailedAdds, "failed adds %q", name) - assert.Equal(t, want.Error, m.Error, "error %q", name) - assert.Equal(t, want.Value, m.Value, "value %q", name) - } - - assert.Equal(t, tc.wantRequired[0], got.RequiredProvided) - assert.Equal(t, tc.wantRequired[1], got.RequiredTotal) - - for key, d := range tc.wantStepDuration { - var found bool - for _, s := range got.Steps { - if s.Key == key { - found = true - assert.Equal(t, d, s.Duration, "duration of %q", key) - } - } - assert.True(t, found, "step %q", key) - } - }) - } -} - -// A group counts once as required, and is provided when any member is -func TestBuildRunProgressGroups(t *testing.T) { - now := time.Now() - contract := []*schemaapi.CraftingSchema_Material{ - {Name: testImage, Type: schemaapi.CraftingSchema_Material_CONTAINER_IMAGE}, - {Name: "cdx", Type: schemaapi.CraftingSchema_Material_SBOM_CYCLONEDX_JSON, Group: testSBOM}, - {Name: "spdx", Type: schemaapi.CraftingSchema_Material_SBOM_SPDX_JSON, Group: testSBOM}, - } - - testCases := []struct { - name string - events []*RunEvent - wantProvided int - }{ - {name: "no member provided", wantProvided: 0}, - {name: "one member provided", events: []*RunEvent{materialRunEvent(now, "spdx", "succeeded", "")}, wantProvided: 1}, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - got := buildRunProgress(contract, tc.events, now) - assert.Equal(t, 2, got.RequiredTotal, "image, and the sbom group once") - assert.Equal(t, tc.wantProvided, got.RequiredProvided) - assert.Equal(t, testSBOM, got.Materials[1].Group) - assert.False(t, got.Materials[1].Required) - }) - } -} - -// The attestation policy results come from the started event. The closing event has none. -func TestBuildRunProgressAttestationPolicies(t *testing.T) { - now := time.Now() - initCounts := &RunEventPolicyCount{Evaluated: 2, Passed: 2} - started := &RunEvent{CreatedAt: &now, Key: testAttKey, Status: "started", Attestation: &RunEventAttestation{Policies: initCounts}} - stored := &RunEvent{CreatedAt: &now, Key: testAttKey, Status: "succeeded", Attestation: &RunEventAttestation{AttestationDigest: "sha256:abc"}} - - assert.Equal(t, initCounts, buildRunProgress(nil, []*RunEvent{started}, now).AttestationPolicies) - assert.Equal(t, initCounts, buildRunProgress(nil, []*RunEvent{started, stored}, now).AttestationPolicies) -} - -// fakeRunViewServer serves View for one run, and ListEvents with a configured answer +// fakeRunViewServer serves View for one run, with the events and the progress it is given type fakeRunViewServer struct { pb.UnimplementedWorkflowRunServiceServer - status pb.RunStatus - events []*pb.WorkflowRunEvent - eventsErr error + status pb.RunStatus + events []*pb.WorkflowRunEvent + progress *pb.WorkflowRunProgress } 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(), - ContractVersion: &pb.WorkflowContractVersionItem{ - //nolint:staticcheck // the V1 body is the fallback that describe reads - Contract: &pb.WorkflowContractVersionItem_V1{V1: &schemaapi.CraftingSchema{Materials: []*schemaapi.CraftingSchema_Material{ - {Name: testSBOM, Type: schemaapi.CraftingSchema_Material_SBOM_CYCLONEDX_JSON}, - }}}, - }, - }, + WorkflowRun: &pb.WorkflowRunItem{Id: testRunID, Status: f.status, CreatedAt: timestamppb.Now()}, + Events: f.events, + Progress: f.progress, }}, nil } -func (f *fakeRunViewServer) ListEvents(context.Context, *pb.WorkflowRunServiceListEventsRequest) (*pb.WorkflowRunServiceListEventsResponse, error) { - if f.eventsErr != nil { - return nil, f.eventsErr - } - - return &pb.WorkflowRunServiceListEventsResponse{Events: f.events}, nil -} - func TestWorkflowRunDescribeEvents(t *testing.T) { sbomFailed := &pb.WorkflowRunEvent{ Id: "1", CreatedAt: timestamppb.Now(), Source: pb.WorkflowRunEvent_SOURCE_CLI, Type: pb.WorkflowRunEvent_TYPE_MATERIAL, @@ -349,18 +187,29 @@ func TestWorkflowRunDescribeEvents(t *testing.T) { 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: "invalid CycloneDX document", FailedAttempts: 1}, + {Name: "cdx", Requirement: pb.WorkflowRunProgress_REQUIREMENT_ONE_OF_GROUP, Group: "sboms", Status: pb.WorkflowRunProgress_STATUS_PROVIDED, Value: "bom.json"}, + }, + } testCases := []struct { name string server *fakeRunViewServer wantEvents int - wantProgress bool + wantProgress *RunProgress }{ { - name: "run in progress", - server: &fakeRunViewServer{status: pb.RunStatus_RUN_STATUS_INITIALIZED, events: []*pb.WorkflowRunEvent{sbomFailed}}, - wantEvents: 1, - wantProgress: true, + 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: "invalid CycloneDX document", FailedAttempts: 1}, + {Name: "cdx", Requirement: RunMaterialOneOfGroup, Group: "sboms", Status: RunMaterialProvided, Value: "bom.json"}, + }}, }, { name: "expired run shows the timeline as history", @@ -368,17 +217,9 @@ func TestWorkflowRunDescribeEvents(t *testing.T) { wantEvents: 2, }, { - name: "run in progress with no events, as from an older CLI", + name: "older control plane, with no events and no progress", server: &fakeRunViewServer{status: pb.RunStatus_RUN_STATUS_INITIALIZED}, }, - { - name: "older control plane", - server: &fakeRunViewServer{status: pb.RunStatus_RUN_STATUS_INITIALIZED, eventsErr: status.Error(codes.Unimplemented, "unknown method")}, - }, - { - name: "other error", - server: &fakeRunViewServer{status: pb.RunStatus_RUN_STATUS_INITIALIZED, eventsErr: status.Error(codes.Internal, "boom")}, - }, } for _, tc := range testCases { @@ -387,19 +228,10 @@ func TestWorkflowRunDescribeEvents(t *testing.T) { got, err := NewWorkflowRunDescribe(&ActionsOpts{CPConnection: conn, Logger: zerolog.Nop()}). Run(context.Background(), &WorkflowRunDescribeOpts{RunID: testRunID}) - require.NoError(t, err, "describe never fails because of events") + require.NoError(t, err) assert.Len(t, got.Events, tc.wantEvents) - if !tc.wantProgress { - assert.Nil(t, got.Progress) - return - } - - require.NotNil(t, got.Progress) - require.Len(t, got.Progress.Materials, 1) - sbom := got.Progress.Materials[0] - assert.False(t, sbom.Provided) - assert.Equal(t, "invalid CycloneDX document", sbom.Error) + 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 96bc30712..667399f57 100644 --- a/app/controlplane/api/controlplane/v1/workflow_run.pb.go +++ b/app/controlplane/api/controlplane/v1/workflow_run.pb.go @@ -134,7 +134,7 @@ func (x WorkflowRunEvent_Source) Number() protoreflect.EnumNumber { // Deprecated: Use WorkflowRunEvent_Source.Descriptor instead. func (WorkflowRunEvent_Source) EnumDescriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{19, 0} + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{17, 0} } type WorkflowRunEvent_Type int32 @@ -183,7 +183,7 @@ func (x WorkflowRunEvent_Type) Number() protoreflect.EnumNumber { // Deprecated: Use WorkflowRunEvent_Type.Descriptor instead. func (WorkflowRunEvent_Type) EnumDescriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{19, 1} + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{17, 1} } type WorkflowRunEvent_Status int32 @@ -238,7 +238,117 @@ func (x WorkflowRunEvent_Status) Number() protoreflect.EnumNumber { // Deprecated: Use WorkflowRunEvent_Status.Descriptor instead. func (WorkflowRunEvent_Status) EnumDescriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{19, 2} + 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{21, 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{21, 1} } type FindOrCreateWorkflowRequest struct { @@ -1195,103 +1305,6 @@ func (*AttestationServiceRecordEventResponse) Descriptor() ([]byte, []int) { return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{16} } -type WorkflowRunServiceListEventsRequest 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"` - // Optional. Return only the events recorded after this one. - AfterEventId string `protobuf:"bytes,2,opt,name=after_event_id,json=afterEventId,proto3" json:"after_event_id,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *WorkflowRunServiceListEventsRequest) Reset() { - *x = WorkflowRunServiceListEventsRequest{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[17] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *WorkflowRunServiceListEventsRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*WorkflowRunServiceListEventsRequest) ProtoMessage() {} - -func (x *WorkflowRunServiceListEventsRequest) 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 { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use WorkflowRunServiceListEventsRequest.ProtoReflect.Descriptor instead. -func (*WorkflowRunServiceListEventsRequest) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{17} -} - -func (x *WorkflowRunServiceListEventsRequest) GetWorkflowRunId() string { - if x != nil { - return x.WorkflowRunId - } - return "" -} - -func (x *WorkflowRunServiceListEventsRequest) GetAfterEventId() string { - if x != nil { - return x.AfterEventId - } - return "" -} - -type WorkflowRunServiceListEventsResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Events []*WorkflowRunEvent `protobuf:"bytes,1,rep,name=events,proto3" json:"events,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *WorkflowRunServiceListEventsResponse) Reset() { - *x = WorkflowRunServiceListEventsResponse{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[18] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *WorkflowRunServiceListEventsResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*WorkflowRunServiceListEventsResponse) ProtoMessage() {} - -func (x *WorkflowRunServiceListEventsResponse) 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 WorkflowRunServiceListEventsResponse.ProtoReflect.Descriptor instead. -func (*WorkflowRunServiceListEventsResponse) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{18} -} - -func (x *WorkflowRunServiceListEventsResponse) GetEvents() []*WorkflowRunEvent { - if x != nil { - return x.Events - } - return nil -} - // A progress event of a workflow run. Unsigned and informational only. // It is never part of the attestation. type WorkflowRunEvent struct { @@ -1316,7 +1329,7 @@ type WorkflowRunEvent struct { func (x *WorkflowRunEvent) Reset() { *x = WorkflowRunEvent{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[19] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[17] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1328,7 +1341,7 @@ func (x *WorkflowRunEvent) String() string { func (*WorkflowRunEvent) ProtoMessage() {} func (x *WorkflowRunEvent) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[19] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[17] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1341,7 +1354,7 @@ func (x *WorkflowRunEvent) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkflowRunEvent.ProtoReflect.Descriptor instead. func (*WorkflowRunEvent) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{19} + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{17} } func (x *WorkflowRunEvent) GetId() string { @@ -1472,7 +1485,7 @@ type WorkflowRunServiceListRequest struct { func (x *WorkflowRunServiceListRequest) Reset() { *x = WorkflowRunServiceListRequest{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[20] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[18] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1484,7 +1497,7 @@ func (x *WorkflowRunServiceListRequest) String() string { func (*WorkflowRunServiceListRequest) ProtoMessage() {} func (x *WorkflowRunServiceListRequest) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[20] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[18] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1497,7 +1510,7 @@ func (x *WorkflowRunServiceListRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkflowRunServiceListRequest.ProtoReflect.Descriptor instead. func (*WorkflowRunServiceListRequest) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{20} + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{18} } func (x *WorkflowRunServiceListRequest) GetWorkflowName() string { @@ -1575,7 +1588,7 @@ type WorkflowRunServiceListResponse struct { func (x *WorkflowRunServiceListResponse) Reset() { *x = WorkflowRunServiceListResponse{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[21] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[19] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1587,7 +1600,7 @@ func (x *WorkflowRunServiceListResponse) String() string { func (*WorkflowRunServiceListResponse) ProtoMessage() {} func (x *WorkflowRunServiceListResponse) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[21] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[19] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1600,7 +1613,7 @@ func (x *WorkflowRunServiceListResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkflowRunServiceListResponse.ProtoReflect.Descriptor instead. func (*WorkflowRunServiceListResponse) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{21} + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{19} } func (x *WorkflowRunServiceListResponse) GetResult() []*WorkflowRunItem { @@ -1634,7 +1647,7 @@ type WorkflowRunServiceViewRequest struct { func (x *WorkflowRunServiceViewRequest) Reset() { *x = WorkflowRunServiceViewRequest{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[22] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[20] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1646,7 +1659,7 @@ func (x *WorkflowRunServiceViewRequest) String() string { func (*WorkflowRunServiceViewRequest) ProtoMessage() {} func (x *WorkflowRunServiceViewRequest) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[22] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[20] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1659,7 +1672,7 @@ func (x *WorkflowRunServiceViewRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkflowRunServiceViewRequest.ProtoReflect.Descriptor instead. func (*WorkflowRunServiceViewRequest) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{22} + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{20} } func (x *WorkflowRunServiceViewRequest) GetRef() isWorkflowRunServiceViewRequest_Ref { @@ -1710,6 +1723,78 @@ func (*WorkflowRunServiceViewRequest_Id) isWorkflowRunServiceViewRequest_Ref() { func (*WorkflowRunServiceViewRequest_Digest) isWorkflowRunServiceViewRequest_Ref() {} +// 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[21] + 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[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 WorkflowRunProgress.ProtoReflect.Descriptor instead. +func (*WorkflowRunProgress) Descriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{21} +} + +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"` @@ -1719,7 +1804,7 @@ type WorkflowRunServiceViewResponse struct { func (x *WorkflowRunServiceViewResponse) Reset() { *x = WorkflowRunServiceViewResponse{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[23] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[22] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1731,7 +1816,7 @@ func (x *WorkflowRunServiceViewResponse) String() string { func (*WorkflowRunServiceViewResponse) ProtoMessage() {} func (x *WorkflowRunServiceViewResponse) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[23] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[22] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1744,7 +1829,7 @@ func (x *WorkflowRunServiceViewResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkflowRunServiceViewResponse.ProtoReflect.Descriptor instead. func (*WorkflowRunServiceViewResponse) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{23} + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{22} } func (x *WorkflowRunServiceViewResponse) GetResult() *WorkflowRunServiceViewResponse_Result { @@ -1763,7 +1848,7 @@ type AttestationServiceGetUploadCredsRequest struct { func (x *AttestationServiceGetUploadCredsRequest) Reset() { *x = AttestationServiceGetUploadCredsRequest{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[24] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[23] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1775,7 +1860,7 @@ func (x *AttestationServiceGetUploadCredsRequest) String() string { func (*AttestationServiceGetUploadCredsRequest) ProtoMessage() {} func (x *AttestationServiceGetUploadCredsRequest) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[24] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[23] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1788,7 +1873,7 @@ func (x *AttestationServiceGetUploadCredsRequest) ProtoReflect() protoreflect.Me // Deprecated: Use AttestationServiceGetUploadCredsRequest.ProtoReflect.Descriptor instead. func (*AttestationServiceGetUploadCredsRequest) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{24} + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{23} } func (x *AttestationServiceGetUploadCredsRequest) GetWorkflowRunId() string { @@ -1807,7 +1892,7 @@ type AttestationServiceGetUploadCredsResponse struct { func (x *AttestationServiceGetUploadCredsResponse) Reset() { *x = AttestationServiceGetUploadCredsResponse{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[25] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[24] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1819,7 +1904,7 @@ func (x *AttestationServiceGetUploadCredsResponse) String() string { func (*AttestationServiceGetUploadCredsResponse) ProtoMessage() {} func (x *AttestationServiceGetUploadCredsResponse) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[25] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[24] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1832,7 +1917,7 @@ func (x *AttestationServiceGetUploadCredsResponse) ProtoReflect() protoreflect.M // Deprecated: Use AttestationServiceGetUploadCredsResponse.ProtoReflect.Descriptor instead. func (*AttestationServiceGetUploadCredsResponse) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{25} + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{24} } func (x *AttestationServiceGetUploadCredsResponse) GetResult() *AttestationServiceGetUploadCredsResponse_Result { @@ -1852,7 +1937,7 @@ type AttestationServiceGetContractResponse_Result struct { func (x *AttestationServiceGetContractResponse_Result) Reset() { *x = AttestationServiceGetContractResponse_Result{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[26] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[25] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1864,7 +1949,7 @@ func (x *AttestationServiceGetContractResponse_Result) String() string { func (*AttestationServiceGetContractResponse_Result) ProtoMessage() {} func (x *AttestationServiceGetContractResponse_Result) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[26] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[25] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1920,7 +2005,7 @@ type AttestationServiceInitResponse_Result struct { func (x *AttestationServiceInitResponse_Result) Reset() { *x = AttestationServiceInitResponse_Result{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[27] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[26] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1932,7 +2017,7 @@ func (x *AttestationServiceInitResponse_Result) String() string { func (*AttestationServiceInitResponse_Result) ProtoMessage() {} func (x *AttestationServiceInitResponse_Result) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[27] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[26] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2023,7 +2108,7 @@ type AttestationServiceInitResponse_SigningOptions struct { func (x *AttestationServiceInitResponse_SigningOptions) Reset() { *x = AttestationServiceInitResponse_SigningOptions{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[28] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[27] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2035,7 +2120,7 @@ func (x *AttestationServiceInitResponse_SigningOptions) String() string { func (*AttestationServiceInitResponse_SigningOptions) ProtoMessage() {} func (x *AttestationServiceInitResponse_SigningOptions) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[28] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[27] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2075,7 +2160,7 @@ type AttestationServiceStoreResponse_Result struct { func (x *AttestationServiceStoreResponse_Result) Reset() { *x = AttestationServiceStoreResponse_Result{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[29] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[28] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2087,7 +2172,7 @@ func (x *AttestationServiceStoreResponse_Result) String() string { func (*AttestationServiceStoreResponse_Result) ProtoMessage() {} func (x *AttestationServiceStoreResponse_Result) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[29] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[28] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2119,14 +2204,17 @@ type WorkflowRunEvent_AttestationAttributes struct { 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"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + 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[30] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[29] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2138,7 +2226,7 @@ func (x *WorkflowRunEvent_AttestationAttributes) String() string { func (*WorkflowRunEvent_AttestationAttributes) ProtoMessage() {} func (x *WorkflowRunEvent_AttestationAttributes) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[30] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[29] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2151,7 +2239,7 @@ func (x *WorkflowRunEvent_AttestationAttributes) ProtoReflect() protoreflect.Mes // Deprecated: Use WorkflowRunEvent_AttestationAttributes.ProtoReflect.Descriptor instead. func (*WorkflowRunEvent_AttestationAttributes) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{19, 0} + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{17, 0} } func (x *WorkflowRunEvent_AttestationAttributes) GetContractName() string { @@ -2203,6 +2291,82 @@ func (x *WorkflowRunEvent_AttestationAttributes) GetPolicies() *WorkflowRunEvent return nil } +func (x *WorkflowRunEvent_AttestationAttributes) GetExpectedMaterials() []*WorkflowRunEvent_ExpectedMaterial { + if x != nil { + return x.ExpectedMaterials + } + return nil +} + +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 *WorkflowRunEvent_ExpectedMaterial) Reset() { + *x = WorkflowRunEvent_ExpectedMaterial{} + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[30] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *WorkflowRunEvent_ExpectedMaterial) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WorkflowRunEvent_ExpectedMaterial) ProtoMessage() {} + +func (x *WorkflowRunEvent_ExpectedMaterial) 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 { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// 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 *WorkflowRunEvent_ExpectedMaterial) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *WorkflowRunEvent_ExpectedMaterial) GetMaterialType() string { + if x != nil { + return x.MaterialType + } + return "" +} + +func (x *WorkflowRunEvent_ExpectedMaterial) GetOptional() bool { + if x != nil { + return x.Optional + } + return false +} + +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"` @@ -2244,7 +2408,7 @@ func (x *WorkflowRunEvent_MaterialAttributes) ProtoReflect() protoreflect.Messag // Deprecated: Use WorkflowRunEvent_MaterialAttributes.ProtoReflect.Descriptor instead. func (*WorkflowRunEvent_MaterialAttributes) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{19, 1} + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{17, 2} } func (x *WorkflowRunEvent_MaterialAttributes) GetName() string { @@ -2334,7 +2498,7 @@ func (x *WorkflowRunEvent_PolicyCounts) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkflowRunEvent_PolicyCounts.ProtoReflect.Descriptor instead. func (*WorkflowRunEvent_PolicyCounts) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{19, 2} + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{17, 3} } func (x *WorkflowRunEvent_PolicyCounts) GetEvaluated() int32 { @@ -2372,20 +2536,136 @@ func (x *WorkflowRunEvent_PolicyCounts) GetViolatedPolicies() []string { 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[33] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *WorkflowRunProgress_Material) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*WorkflowRunProgress_Material) ProtoMessage() {} + +func (x *WorkflowRunProgress_Material) 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 { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use WorkflowRunProgress_Material.ProtoReflect.Descriptor instead. +func (*WorkflowRunProgress_Material) Descriptor() ([]byte, []int) { + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{21, 0} +} + +func (x *WorkflowRunProgress_Material) GetName() string { + if x != nil { + 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"` WorkflowRun *WorkflowRunItem `protobuf:"bytes,1,opt,name=workflow_run,json=workflowRun,proto3" json:"workflow_run,omitempty"` Attestation *AttestationItem `protobuf:"bytes,2,opt,name=attestation,proto3" json:"attestation,omitempty"` // It will be nil if the verification is not possible (old or non-keyless attestations) - Verification *WorkflowRunServiceViewResponse_VerificationResult `protobuf:"bytes,3,opt,name=verification,proto3" json:"verification,omitempty"` + Verification *WorkflowRunServiceViewResponse_VerificationResult `protobuf:"bytes,3,opt,name=verification,proto3" json:"verification,omitempty"` + // 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,6,opt,name=progress,proto3" json:"progress,omitempty"` + // Timeline of the run, oldest first. Reported data, never part of the attestation. + Events []*WorkflowRunEvent `protobuf:"bytes,7,rep,name=events,proto3" json:"events,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *WorkflowRunServiceViewResponse_Result) Reset() { *x = WorkflowRunServiceViewResponse_Result{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[33] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[34] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2397,7 +2677,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[33] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[34] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2410,7 +2690,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{23, 0} + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{22, 0} } func (x *WorkflowRunServiceViewResponse_Result) GetOrgName() string { @@ -2441,6 +2721,20 @@ func (x *WorkflowRunServiceViewResponse_Result) GetVerification() *WorkflowRunSe return nil } +func (x *WorkflowRunServiceViewResponse_Result) GetProgress() *WorkflowRunProgress { + if x != nil { + return x.Progress + } + return nil +} + +func (x *WorkflowRunServiceViewResponse_Result) GetEvents() []*WorkflowRunEvent { + if x != nil { + return x.Events + } + return nil +} + type WorkflowRunServiceViewResponse_VerificationResult struct { state protoimpl.MessageState `protogen:"open.v1"` // if it can be verified this will hold the result of the verification @@ -2453,7 +2747,7 @@ type WorkflowRunServiceViewResponse_VerificationResult struct { func (x *WorkflowRunServiceViewResponse_VerificationResult) Reset() { *x = WorkflowRunServiceViewResponse_VerificationResult{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[34] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[35] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2465,7 +2759,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[34] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[35] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2478,7 +2772,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{23, 1} + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{22, 1} } func (x *WorkflowRunServiceViewResponse_VerificationResult) GetVerified() bool { @@ -2505,7 +2799,7 @@ type AttestationServiceGetUploadCredsResponse_Result struct { func (x *AttestationServiceGetUploadCredsResponse_Result) Reset() { *x = AttestationServiceGetUploadCredsResponse_Result{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[35] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[36] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2517,7 +2811,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[35] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[36] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2530,7 +2824,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{25, 0} + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{24, 0} } func (x *AttestationServiceGetUploadCredsResponse_Result) GetToken() string { @@ -2636,12 +2930,7 @@ const file_controlplane_v1_workflow_run_proto_rawDesc = "" + "$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\"\x8a\x01\n" + - "#WorkflowRunServiceListEventsRequest\x120\n" + - "\x0fworkflow_run_id\x18\x01 \x01(\tB\b\xbaH\x05r\x03\xb0\x01\x01R\rworkflowRunId\x121\n" + - "\x0eafter_event_id\x18\x02 \x01(\tB\v\xbaH\b\xd8\x01\x01r\x03\xb0\x01\x01R\fafterEventId\"a\n" + - "$WorkflowRunServiceListEventsResponse\x129\n" + - "\x06events\x18\x01 \x03(\v2!.controlplane.v1.WorkflowRunEventR\x06events\"\xca\r\n" + + "%AttestationServiceRecordEventResponse\"\xd6\x0f\n" + "\x10WorkflowRunEvent\x12\x0e\n" + "\x02id\x18\x01 \x01(\tR\x02id\x129\n" + "\n" + @@ -2656,7 +2945,7 @@ const file_controlplane_v1_workflow_run_proto_rawDesc = "" + "\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\xf1\x02\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" + @@ -2666,7 +2955,13 @@ const file_controlplane_v1_workflow_run_proto_rawDesc = "" + "\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\x1a\xbe\x02\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" + @@ -2723,14 +3018,43 @@ 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\"\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\"\xdd\x04\n" + "\x1eWorkflowRunServiceViewResponse\x12N\n" + - "\x06result\x18\x01 \x01(\v26.controlplane.v1.WorkflowRunServiceViewResponse.ResultR\x06result\x1a\x94\x02\n" + + "\x06result\x18\x01 \x01(\v26.controlplane.v1.WorkflowRunServiceViewResponse.ResultR\x06result\x1a\x91\x03\n" + "\x06Result\x12\x19\n" + "\borg_name\x18\x05 \x01(\tR\aorgName\x12C\n" + "\fworkflow_run\x18\x01 \x01(\v2 .controlplane.v1.WorkflowRunItemR\vworkflowRun\x12B\n" + "\vattestation\x18\x02 \x01(\v2 .controlplane.v1.AttestationItemR\vattestation\x12f\n" + - "\fverification\x18\x03 \x01(\v2B.controlplane.v1.WorkflowRunServiceViewResponse.VerificationResultR\fverification\x1aW\n" + + "\fverification\x18\x03 \x01(\v2B.controlplane.v1.WorkflowRunServiceViewResponse.VerificationResultR\fverification\x12@\n" + + "\bprogress\x18\x06 \x01(\v2$.controlplane.v1.WorkflowRunProgressR\bprogress\x129\n" + + "\x06events\x18\a \x03(\v2!.controlplane.v1.WorkflowRunEventR\x06events\x1aW\n" + "\x12VerificationResult\x12\x1a\n" + "\bverified\x18\x01 \x01(\bR\bverified\x12%\n" + "\x0efailure_reason\x18\x02 \x01(\tR\rfailureReason\"Q\n" + @@ -2750,12 +3074,10 @@ const file_controlplane_v1_workflow_run_proto_rawDesc = "" + "\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\xe1\x02\n" + + "\x0eGetPolicyGroup\x128.controlplane.v1.AttestationServiceGetPolicyGroupRequest\x1a9.controlplane.v1.AttestationServiceGetPolicyGroupResponse2\xe6\x01\n" + "\x12WorkflowRunService\x12g\n" + "\x04List\x12..controlplane.v1.WorkflowRunServiceListRequest\x1a/.controlplane.v1.WorkflowRunServiceListResponse\x12g\n" + - "\x04View\x12..controlplane.v1.WorkflowRunServiceViewRequest\x1a/.controlplane.v1.WorkflowRunServiceViewResponse\x12y\n" + - "\n" + - "ListEvents\x124.controlplane.v1.WorkflowRunServiceListEventsRequest\x1a5.controlplane.v1.WorkflowRunServiceListEventsResponseBLZJgithub.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1;v1b\x06proto3" + "\x04View\x12..controlplane.v1.WorkflowRunServiceViewRequest\x1a/.controlplane.v1.WorkflowRunServiceViewResponseBLZJgithub.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1;v1b\x06proto3" var ( file_controlplane_v1_workflow_run_proto_rawDescOnce sync.Once @@ -2769,132 +3091,140 @@ 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, 4) -var file_controlplane_v1_workflow_run_proto_msgTypes = make([]protoimpl.MessageInfo, 36) +var file_controlplane_v1_workflow_run_proto_enumTypes = make([]protoimpl.EnumInfo, 6) +var file_controlplane_v1_workflow_run_proto_msgTypes = make([]protoimpl.MessageInfo, 37) var file_controlplane_v1_workflow_run_proto_goTypes = []any{ (AttestationServiceCancelRequest_TriggerType)(0), // 0: controlplane.v1.AttestationServiceCancelRequest.TriggerType (WorkflowRunEvent_Source)(0), // 1: controlplane.v1.WorkflowRunEvent.Source (WorkflowRunEvent_Type)(0), // 2: controlplane.v1.WorkflowRunEvent.Type (WorkflowRunEvent_Status)(0), // 3: controlplane.v1.WorkflowRunEvent.Status - (*FindOrCreateWorkflowRequest)(nil), // 4: controlplane.v1.FindOrCreateWorkflowRequest - (*FindOrCreateWorkflowResponse)(nil), // 5: controlplane.v1.FindOrCreateWorkflowResponse - (*AttestationServiceGetPolicyRequest)(nil), // 6: controlplane.v1.AttestationServiceGetPolicyRequest - (*AttestationServiceGetPolicyResponse)(nil), // 7: controlplane.v1.AttestationServiceGetPolicyResponse - (*RemotePolicyReference)(nil), // 8: controlplane.v1.RemotePolicyReference - (*AttestationServiceGetPolicyGroupRequest)(nil), // 9: controlplane.v1.AttestationServiceGetPolicyGroupRequest - (*AttestationServiceGetPolicyGroupResponse)(nil), // 10: controlplane.v1.AttestationServiceGetPolicyGroupResponse - (*AttestationServiceGetContractRequest)(nil), // 11: controlplane.v1.AttestationServiceGetContractRequest - (*AttestationServiceGetContractResponse)(nil), // 12: controlplane.v1.AttestationServiceGetContractResponse - (*AttestationServiceInitRequest)(nil), // 13: controlplane.v1.AttestationServiceInitRequest - (*AttestationServiceInitResponse)(nil), // 14: controlplane.v1.AttestationServiceInitResponse - (*AttestationServiceStoreRequest)(nil), // 15: controlplane.v1.AttestationServiceStoreRequest - (*AttestationServiceStoreResponse)(nil), // 16: controlplane.v1.AttestationServiceStoreResponse - (*AttestationServiceCancelRequest)(nil), // 17: controlplane.v1.AttestationServiceCancelRequest - (*AttestationServiceCancelResponse)(nil), // 18: controlplane.v1.AttestationServiceCancelResponse - (*AttestationServiceRecordEventRequest)(nil), // 19: controlplane.v1.AttestationServiceRecordEventRequest - (*AttestationServiceRecordEventResponse)(nil), // 20: controlplane.v1.AttestationServiceRecordEventResponse - (*WorkflowRunServiceListEventsRequest)(nil), // 21: controlplane.v1.WorkflowRunServiceListEventsRequest - (*WorkflowRunServiceListEventsResponse)(nil), // 22: controlplane.v1.WorkflowRunServiceListEventsResponse + (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 - (*WorkflowRunServiceViewResponse)(nil), // 27: controlplane.v1.WorkflowRunServiceViewResponse - (*AttestationServiceGetUploadCredsRequest)(nil), // 28: controlplane.v1.AttestationServiceGetUploadCredsRequest - (*AttestationServiceGetUploadCredsResponse)(nil), // 29: controlplane.v1.AttestationServiceGetUploadCredsResponse - (*AttestationServiceGetContractResponse_Result)(nil), // 30: controlplane.v1.AttestationServiceGetContractResponse.Result - (*AttestationServiceInitResponse_Result)(nil), // 31: controlplane.v1.AttestationServiceInitResponse.Result - (*AttestationServiceInitResponse_SigningOptions)(nil), // 32: controlplane.v1.AttestationServiceInitResponse.SigningOptions - (*AttestationServiceStoreResponse_Result)(nil), // 33: controlplane.v1.AttestationServiceStoreResponse.Result - (*WorkflowRunEvent_AttestationAttributes)(nil), // 34: controlplane.v1.WorkflowRunEvent.AttestationAttributes - (*WorkflowRunEvent_MaterialAttributes)(nil), // 35: controlplane.v1.WorkflowRunEvent.MaterialAttributes - (*WorkflowRunEvent_PolicyCounts)(nil), // 36: controlplane.v1.WorkflowRunEvent.PolicyCounts - (*WorkflowRunServiceViewResponse_Result)(nil), // 37: controlplane.v1.WorkflowRunServiceViewResponse.Result - (*WorkflowRunServiceViewResponse_VerificationResult)(nil), // 38: controlplane.v1.WorkflowRunServiceViewResponse.VerificationResult - (*AttestationServiceGetUploadCredsResponse_Result)(nil), // 39: controlplane.v1.AttestationServiceGetUploadCredsResponse.Result - (*WorkflowItem)(nil), // 40: controlplane.v1.WorkflowItem - (*v1.Policy)(nil), // 41: workflowcontract.v1.Policy - (*v1.PolicyGroup)(nil), // 42: workflowcontract.v1.PolicyGroup - (v1.CraftingSchema_Runner_RunnerType)(0), // 43: workflowcontract.v1.CraftingSchema.Runner.RunnerType - (*timestamppb.Timestamp)(nil), // 44: google.protobuf.Timestamp - (RunStatus)(0), // 45: controlplane.v1.RunStatus - (PolicyViolationsFilter)(0), // 46: controlplane.v1.PolicyViolationsFilter - (PolicyStatusFilter)(0), // 47: controlplane.v1.PolicyStatusFilter - (PolicyGatesFilter)(0), // 48: controlplane.v1.PolicyGatesFilter - (*CursorPaginationRequest)(nil), // 49: controlplane.v1.CursorPaginationRequest - (*WorkflowRunItem)(nil), // 50: controlplane.v1.WorkflowRunItem - (*CursorPaginationResponse)(nil), // 51: controlplane.v1.CursorPaginationResponse - (*WorkflowContractVersionItem)(nil), // 52: controlplane.v1.WorkflowContractVersionItem - (*AttestationItem)(nil), // 53: controlplane.v1.AttestationItem - (*CASBackendItem)(nil), // 54: controlplane.v1.CASBackendItem + (*WorkflowRunProgress)(nil), // 27: controlplane.v1.WorkflowRunProgress + (*WorkflowRunServiceViewResponse)(nil), // 28: controlplane.v1.WorkflowRunServiceViewResponse + (*AttestationServiceGetUploadCredsRequest)(nil), // 29: controlplane.v1.AttestationServiceGetUploadCredsRequest + (*AttestationServiceGetUploadCredsResponse)(nil), // 30: controlplane.v1.AttestationServiceGetUploadCredsResponse + (*AttestationServiceGetContractResponse_Result)(nil), // 31: controlplane.v1.AttestationServiceGetContractResponse.Result + (*AttestationServiceInitResponse_Result)(nil), // 32: controlplane.v1.AttestationServiceInitResponse.Result + (*AttestationServiceInitResponse_SigningOptions)(nil), // 33: controlplane.v1.AttestationServiceInitResponse.SigningOptions + (*AttestationServiceStoreResponse_Result)(nil), // 34: controlplane.v1.AttestationServiceStoreResponse.Result + (*WorkflowRunEvent_AttestationAttributes)(nil), // 35: controlplane.v1.WorkflowRunEvent.AttestationAttributes + (*WorkflowRunEvent_ExpectedMaterial)(nil), // 36: controlplane.v1.WorkflowRunEvent.ExpectedMaterial + (*WorkflowRunEvent_MaterialAttributes)(nil), // 37: controlplane.v1.WorkflowRunEvent.MaterialAttributes + (*WorkflowRunEvent_PolicyCounts)(nil), // 38: controlplane.v1.WorkflowRunEvent.PolicyCounts + (*WorkflowRunProgress_Material)(nil), // 39: controlplane.v1.WorkflowRunProgress.Material + (*WorkflowRunServiceViewResponse_Result)(nil), // 40: controlplane.v1.WorkflowRunServiceViewResponse.Result + (*WorkflowRunServiceViewResponse_VerificationResult)(nil), // 41: controlplane.v1.WorkflowRunServiceViewResponse.VerificationResult + (*AttestationServiceGetUploadCredsResponse_Result)(nil), // 42: controlplane.v1.AttestationServiceGetUploadCredsResponse.Result + (*WorkflowItem)(nil), // 43: controlplane.v1.WorkflowItem + (*v1.Policy)(nil), // 44: workflowcontract.v1.Policy + (*v1.PolicyGroup)(nil), // 45: workflowcontract.v1.PolicyGroup + (v1.CraftingSchema_Runner_RunnerType)(0), // 46: workflowcontract.v1.CraftingSchema.Runner.RunnerType + (*timestamppb.Timestamp)(nil), // 47: google.protobuf.Timestamp + (RunStatus)(0), // 48: controlplane.v1.RunStatus + (PolicyViolationsFilter)(0), // 49: controlplane.v1.PolicyViolationsFilter + (PolicyStatusFilter)(0), // 50: controlplane.v1.PolicyStatusFilter + (PolicyGatesFilter)(0), // 51: controlplane.v1.PolicyGatesFilter + (*CursorPaginationRequest)(nil), // 52: controlplane.v1.CursorPaginationRequest + (*WorkflowRunItem)(nil), // 53: controlplane.v1.WorkflowRunItem + (*CursorPaginationResponse)(nil), // 54: controlplane.v1.CursorPaginationResponse + (*WorkflowContractVersionItem)(nil), // 55: controlplane.v1.WorkflowContractVersionItem + (*AttestationItem)(nil), // 56: controlplane.v1.AttestationItem + (*CASBackendItem)(nil), // 57: controlplane.v1.CASBackendItem } var file_controlplane_v1_workflow_run_proto_depIdxs = []int32{ - 40, // 0: controlplane.v1.FindOrCreateWorkflowResponse.result:type_name -> controlplane.v1.WorkflowItem - 41, // 1: controlplane.v1.AttestationServiceGetPolicyResponse.policy:type_name -> workflowcontract.v1.Policy - 8, // 2: controlplane.v1.AttestationServiceGetPolicyResponse.reference:type_name -> controlplane.v1.RemotePolicyReference - 42, // 3: controlplane.v1.AttestationServiceGetPolicyGroupResponse.group:type_name -> workflowcontract.v1.PolicyGroup - 8, // 4: controlplane.v1.AttestationServiceGetPolicyGroupResponse.reference:type_name -> controlplane.v1.RemotePolicyReference - 30, // 5: controlplane.v1.AttestationServiceGetContractResponse.result:type_name -> controlplane.v1.AttestationServiceGetContractResponse.Result - 43, // 6: controlplane.v1.AttestationServiceInitRequest.runner:type_name -> workflowcontract.v1.CraftingSchema.Runner.RunnerType - 31, // 7: controlplane.v1.AttestationServiceInitResponse.result:type_name -> controlplane.v1.AttestationServiceInitResponse.Result - 33, // 8: controlplane.v1.AttestationServiceStoreResponse.result:type_name -> controlplane.v1.AttestationServiceStoreResponse.Result + 43, // 0: controlplane.v1.FindOrCreateWorkflowResponse.result:type_name -> controlplane.v1.WorkflowItem + 44, // 1: controlplane.v1.AttestationServiceGetPolicyResponse.policy:type_name -> workflowcontract.v1.Policy + 10, // 2: controlplane.v1.AttestationServiceGetPolicyResponse.reference:type_name -> controlplane.v1.RemotePolicyReference + 45, // 3: controlplane.v1.AttestationServiceGetPolicyGroupResponse.group:type_name -> workflowcontract.v1.PolicyGroup + 10, // 4: controlplane.v1.AttestationServiceGetPolicyGroupResponse.reference:type_name -> controlplane.v1.RemotePolicyReference + 31, // 5: controlplane.v1.AttestationServiceGetContractResponse.result:type_name -> controlplane.v1.AttestationServiceGetContractResponse.Result + 46, // 6: controlplane.v1.AttestationServiceInitRequest.runner:type_name -> workflowcontract.v1.CraftingSchema.Runner.RunnerType + 32, // 7: controlplane.v1.AttestationServiceInitResponse.result:type_name -> controlplane.v1.AttestationServiceInitResponse.Result + 34, // 8: controlplane.v1.AttestationServiceStoreResponse.result:type_name -> controlplane.v1.AttestationServiceStoreResponse.Result 0, // 9: controlplane.v1.AttestationServiceCancelRequest.trigger:type_name -> controlplane.v1.AttestationServiceCancelRequest.TriggerType 23, // 10: controlplane.v1.AttestationServiceRecordEventRequest.event:type_name -> controlplane.v1.WorkflowRunEvent - 23, // 11: controlplane.v1.WorkflowRunServiceListEventsResponse.events:type_name -> controlplane.v1.WorkflowRunEvent - 44, // 12: controlplane.v1.WorkflowRunEvent.created_at:type_name -> google.protobuf.Timestamp - 1, // 13: controlplane.v1.WorkflowRunEvent.source:type_name -> controlplane.v1.WorkflowRunEvent.Source - 2, // 14: controlplane.v1.WorkflowRunEvent.type:type_name -> controlplane.v1.WorkflowRunEvent.Type - 3, // 15: controlplane.v1.WorkflowRunEvent.status:type_name -> controlplane.v1.WorkflowRunEvent.Status - 34, // 16: controlplane.v1.WorkflowRunEvent.attestation:type_name -> controlplane.v1.WorkflowRunEvent.AttestationAttributes - 35, // 17: controlplane.v1.WorkflowRunEvent.material:type_name -> controlplane.v1.WorkflowRunEvent.MaterialAttributes - 45, // 18: controlplane.v1.WorkflowRunServiceListRequest.status:type_name -> controlplane.v1.RunStatus - 46, // 19: controlplane.v1.WorkflowRunServiceListRequest.policy_violations:type_name -> controlplane.v1.PolicyViolationsFilter - 47, // 20: controlplane.v1.WorkflowRunServiceListRequest.policy_status:type_name -> controlplane.v1.PolicyStatusFilter - 48, // 21: controlplane.v1.WorkflowRunServiceListRequest.policy_gates:type_name -> controlplane.v1.PolicyGatesFilter - 49, // 22: controlplane.v1.WorkflowRunServiceListRequest.pagination:type_name -> controlplane.v1.CursorPaginationRequest - 50, // 23: controlplane.v1.WorkflowRunServiceListResponse.result:type_name -> controlplane.v1.WorkflowRunItem - 51, // 24: controlplane.v1.WorkflowRunServiceListResponse.pagination:type_name -> controlplane.v1.CursorPaginationResponse - 37, // 25: controlplane.v1.WorkflowRunServiceViewResponse.result:type_name -> controlplane.v1.WorkflowRunServiceViewResponse.Result - 39, // 26: controlplane.v1.AttestationServiceGetUploadCredsResponse.result:type_name -> controlplane.v1.AttestationServiceGetUploadCredsResponse.Result - 40, // 27: controlplane.v1.AttestationServiceGetContractResponse.Result.workflow:type_name -> controlplane.v1.WorkflowItem - 52, // 28: controlplane.v1.AttestationServiceGetContractResponse.Result.contract:type_name -> controlplane.v1.WorkflowContractVersionItem - 50, // 29: controlplane.v1.AttestationServiceInitResponse.Result.workflow_run:type_name -> controlplane.v1.WorkflowRunItem - 32, // 30: controlplane.v1.AttestationServiceInitResponse.Result.signing_options:type_name -> controlplane.v1.AttestationServiceInitResponse.SigningOptions - 36, // 31: controlplane.v1.WorkflowRunEvent.AttestationAttributes.policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts - 36, // 32: controlplane.v1.WorkflowRunEvent.MaterialAttributes.policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts - 50, // 33: controlplane.v1.WorkflowRunServiceViewResponse.Result.workflow_run:type_name -> controlplane.v1.WorkflowRunItem - 53, // 34: controlplane.v1.WorkflowRunServiceViewResponse.Result.attestation:type_name -> controlplane.v1.AttestationItem - 38, // 35: controlplane.v1.WorkflowRunServiceViewResponse.Result.verification:type_name -> controlplane.v1.WorkflowRunServiceViewResponse.VerificationResult - 54, // 36: controlplane.v1.AttestationServiceGetUploadCredsResponse.Result.backend:type_name -> controlplane.v1.CASBackendItem - 4, // 37: controlplane.v1.AttestationService.FindOrCreateWorkflow:input_type -> controlplane.v1.FindOrCreateWorkflowRequest - 11, // 38: controlplane.v1.AttestationService.GetContract:input_type -> controlplane.v1.AttestationServiceGetContractRequest - 13, // 39: controlplane.v1.AttestationService.Init:input_type -> controlplane.v1.AttestationServiceInitRequest - 15, // 40: controlplane.v1.AttestationService.Store:input_type -> controlplane.v1.AttestationServiceStoreRequest - 28, // 41: controlplane.v1.AttestationService.GetUploadCreds:input_type -> controlplane.v1.AttestationServiceGetUploadCredsRequest - 17, // 42: controlplane.v1.AttestationService.Cancel:input_type -> controlplane.v1.AttestationServiceCancelRequest - 19, // 43: controlplane.v1.AttestationService.RecordEvent:input_type -> controlplane.v1.AttestationServiceRecordEventRequest - 6, // 44: controlplane.v1.AttestationService.GetPolicy:input_type -> controlplane.v1.AttestationServiceGetPolicyRequest - 9, // 45: controlplane.v1.AttestationService.GetPolicyGroup:input_type -> controlplane.v1.AttestationServiceGetPolicyGroupRequest - 24, // 46: controlplane.v1.WorkflowRunService.List:input_type -> controlplane.v1.WorkflowRunServiceListRequest - 26, // 47: controlplane.v1.WorkflowRunService.View:input_type -> controlplane.v1.WorkflowRunServiceViewRequest - 21, // 48: controlplane.v1.WorkflowRunService.ListEvents:input_type -> controlplane.v1.WorkflowRunServiceListEventsRequest - 5, // 49: controlplane.v1.AttestationService.FindOrCreateWorkflow:output_type -> controlplane.v1.FindOrCreateWorkflowResponse - 12, // 50: controlplane.v1.AttestationService.GetContract:output_type -> controlplane.v1.AttestationServiceGetContractResponse - 14, // 51: controlplane.v1.AttestationService.Init:output_type -> controlplane.v1.AttestationServiceInitResponse - 16, // 52: controlplane.v1.AttestationService.Store:output_type -> controlplane.v1.AttestationServiceStoreResponse - 29, // 53: controlplane.v1.AttestationService.GetUploadCreds:output_type -> controlplane.v1.AttestationServiceGetUploadCredsResponse - 18, // 54: controlplane.v1.AttestationService.Cancel:output_type -> controlplane.v1.AttestationServiceCancelResponse - 20, // 55: controlplane.v1.AttestationService.RecordEvent:output_type -> controlplane.v1.AttestationServiceRecordEventResponse - 7, // 56: controlplane.v1.AttestationService.GetPolicy:output_type -> controlplane.v1.AttestationServiceGetPolicyResponse - 10, // 57: controlplane.v1.AttestationService.GetPolicyGroup:output_type -> controlplane.v1.AttestationServiceGetPolicyGroupResponse - 25, // 58: controlplane.v1.WorkflowRunService.List:output_type -> controlplane.v1.WorkflowRunServiceListResponse - 27, // 59: controlplane.v1.WorkflowRunService.View:output_type -> controlplane.v1.WorkflowRunServiceViewResponse - 22, // 60: controlplane.v1.WorkflowRunService.ListEvents:output_type -> controlplane.v1.WorkflowRunServiceListEventsResponse - 49, // [49:61] is the sub-list for method output_type - 37, // [37:49] is the sub-list for method input_type - 37, // [37:37] is the sub-list for extension type_name - 37, // [37:37] is the sub-list for extension extendee - 0, // [0:37] is the sub-list for field type_name + 47, // 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 + 35, // 15: controlplane.v1.WorkflowRunEvent.attestation:type_name -> controlplane.v1.WorkflowRunEvent.AttestationAttributes + 37, // 16: controlplane.v1.WorkflowRunEvent.material:type_name -> controlplane.v1.WorkflowRunEvent.MaterialAttributes + 48, // 17: controlplane.v1.WorkflowRunServiceListRequest.status:type_name -> controlplane.v1.RunStatus + 49, // 18: controlplane.v1.WorkflowRunServiceListRequest.policy_violations:type_name -> controlplane.v1.PolicyViolationsFilter + 50, // 19: controlplane.v1.WorkflowRunServiceListRequest.policy_status:type_name -> controlplane.v1.PolicyStatusFilter + 51, // 20: controlplane.v1.WorkflowRunServiceListRequest.policy_gates:type_name -> controlplane.v1.PolicyGatesFilter + 52, // 21: controlplane.v1.WorkflowRunServiceListRequest.pagination:type_name -> controlplane.v1.CursorPaginationRequest + 53, // 22: controlplane.v1.WorkflowRunServiceListResponse.result:type_name -> controlplane.v1.WorkflowRunItem + 54, // 23: controlplane.v1.WorkflowRunServiceListResponse.pagination:type_name -> controlplane.v1.CursorPaginationResponse + 39, // 24: controlplane.v1.WorkflowRunProgress.materials:type_name -> controlplane.v1.WorkflowRunProgress.Material + 38, // 25: controlplane.v1.WorkflowRunProgress.attestation_policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts + 40, // 26: controlplane.v1.WorkflowRunServiceViewResponse.result:type_name -> controlplane.v1.WorkflowRunServiceViewResponse.Result + 42, // 27: controlplane.v1.AttestationServiceGetUploadCredsResponse.result:type_name -> controlplane.v1.AttestationServiceGetUploadCredsResponse.Result + 43, // 28: controlplane.v1.AttestationServiceGetContractResponse.Result.workflow:type_name -> controlplane.v1.WorkflowItem + 55, // 29: controlplane.v1.AttestationServiceGetContractResponse.Result.contract:type_name -> controlplane.v1.WorkflowContractVersionItem + 53, // 30: controlplane.v1.AttestationServiceInitResponse.Result.workflow_run:type_name -> controlplane.v1.WorkflowRunItem + 33, // 31: controlplane.v1.AttestationServiceInitResponse.Result.signing_options:type_name -> controlplane.v1.AttestationServiceInitResponse.SigningOptions + 38, // 32: controlplane.v1.WorkflowRunEvent.AttestationAttributes.policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts + 36, // 33: controlplane.v1.WorkflowRunEvent.AttestationAttributes.expected_materials:type_name -> controlplane.v1.WorkflowRunEvent.ExpectedMaterial + 38, // 34: controlplane.v1.WorkflowRunEvent.MaterialAttributes.policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts + 4, // 35: controlplane.v1.WorkflowRunProgress.Material.requirement:type_name -> controlplane.v1.WorkflowRunProgress.Requirement + 5, // 36: controlplane.v1.WorkflowRunProgress.Material.status:type_name -> controlplane.v1.WorkflowRunProgress.Status + 38, // 37: controlplane.v1.WorkflowRunProgress.Material.policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts + 53, // 38: controlplane.v1.WorkflowRunServiceViewResponse.Result.workflow_run:type_name -> controlplane.v1.WorkflowRunItem + 56, // 39: controlplane.v1.WorkflowRunServiceViewResponse.Result.attestation:type_name -> controlplane.v1.AttestationItem + 41, // 40: controlplane.v1.WorkflowRunServiceViewResponse.Result.verification:type_name -> controlplane.v1.WorkflowRunServiceViewResponse.VerificationResult + 27, // 41: controlplane.v1.WorkflowRunServiceViewResponse.Result.progress:type_name -> controlplane.v1.WorkflowRunProgress + 23, // 42: controlplane.v1.WorkflowRunServiceViewResponse.Result.events:type_name -> controlplane.v1.WorkflowRunEvent + 57, // 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 + 29, // 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 + 7, // 55: controlplane.v1.AttestationService.FindOrCreateWorkflow:output_type -> controlplane.v1.FindOrCreateWorkflowResponse + 14, // 56: controlplane.v1.AttestationService.GetContract:output_type -> controlplane.v1.AttestationServiceGetContractResponse + 16, // 57: controlplane.v1.AttestationService.Init:output_type -> controlplane.v1.AttestationServiceInitResponse + 18, // 58: controlplane.v1.AttestationService.Store:output_type -> controlplane.v1.AttestationServiceStoreResponse + 30, // 59: controlplane.v1.AttestationService.GetUploadCreds:output_type -> controlplane.v1.AttestationServiceGetUploadCredsResponse + 20, // 60: controlplane.v1.AttestationService.Cancel:output_type -> controlplane.v1.AttestationServiceCancelResponse + 22, // 61: controlplane.v1.AttestationService.RecordEvent:output_type -> controlplane.v1.AttestationServiceRecordEventResponse + 9, // 62: controlplane.v1.AttestationService.GetPolicy:output_type -> controlplane.v1.AttestationServiceGetPolicyResponse + 12, // 63: controlplane.v1.AttestationService.GetPolicyGroup:output_type -> controlplane.v1.AttestationServiceGetPolicyGroupResponse + 25, // 64: controlplane.v1.WorkflowRunService.List:output_type -> controlplane.v1.WorkflowRunServiceListResponse + 28, // 65: controlplane.v1.WorkflowRunService.View:output_type -> controlplane.v1.WorkflowRunServiceViewResponse + 55, // [55:66] is the sub-list for method output_type + 44, // [44:55] 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() } @@ -2906,11 +3236,11 @@ func file_controlplane_v1_workflow_run_proto_init() { file_controlplane_v1_response_messages_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[19].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[22].OneofWrappers = []any{ + file_controlplane_v1_workflow_run_proto_msgTypes[20].OneofWrappers = []any{ (*WorkflowRunServiceViewRequest_Id)(nil), (*WorkflowRunServiceViewRequest_Digest)(nil), } @@ -2919,8 +3249,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: 4, - NumMessages: 36, + NumEnums: 6, + NumMessages: 37, 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 7343633a0..89afdfac8 100644 --- a/app/controlplane/api/controlplane/v1/workflow_run.proto +++ b/app/controlplane/api/controlplane/v1/workflow_run.proto @@ -46,9 +46,9 @@ service AttestationService { // Administrative service for the operator service WorkflowRunService { rpc List(WorkflowRunServiceListRequest) returns (WorkflowRunServiceListResponse); + // View returns the run, its attestation, its timeline of events, and, while the run + // is in progress, its progress rpc View(WorkflowRunServiceViewRequest) returns (WorkflowRunServiceViewResponse); - // Events of a run, oldest first. Optional after_event_id returns only newer events. - rpc ListEvents(WorkflowRunServiceListEventsRequest) returns (WorkflowRunServiceListEventsResponse); } message FindOrCreateWorkflowRequest { @@ -217,19 +217,6 @@ message AttestationServiceRecordEventRequest { message AttestationServiceRecordEventResponse {} -message WorkflowRunServiceListEventsRequest { - string workflow_run_id = 1 [(buf.validate.field).string.uuid = true]; - // Optional. Return only the events recorded after this one. - string after_event_id = 2 [(buf.validate.field) = { - ignore: IGNORE_IF_ZERO_VALUE - string: {uuid: true} - }]; -} - -message WorkflowRunServiceListEventsResponse { - repeated WorkflowRunEvent events = 1; -} - // A progress event of a workflow run. Unsigned and informational only. // It is never part of the attestation. message WorkflowRunEvent { @@ -290,6 +277,17 @@ message WorkflowRunEvent { 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 { @@ -392,6 +390,50 @@ message WorkflowRunServiceViewRequest { bool verify = 3; } +// 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; @@ -401,6 +443,11 @@ message WorkflowRunServiceViewResponse { AttestationItem attestation = 2; // It will be nil if the verification is not possible (old or non-keyless attestations) VerificationResult verification = 3; + // 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 = 6; + // Timeline of the run, oldest first. Reported data, never part of the attestation. + repeated WorkflowRunEvent events = 7; } message VerificationResult { 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 fec70a703..d7b582cfa 100644 --- a/app/controlplane/api/controlplane/v1/workflow_run_grpc.pb.go +++ b/app/controlplane/api/controlplane/v1/workflow_run_grpc.pb.go @@ -428,9 +428,8 @@ var AttestationService_ServiceDesc = grpc.ServiceDesc{ } const ( - WorkflowRunService_List_FullMethodName = "/controlplane.v1.WorkflowRunService/List" - WorkflowRunService_View_FullMethodName = "/controlplane.v1.WorkflowRunService/View" - WorkflowRunService_ListEvents_FullMethodName = "/controlplane.v1.WorkflowRunService/ListEvents" + WorkflowRunService_List_FullMethodName = "/controlplane.v1.WorkflowRunService/List" + WorkflowRunService_View_FullMethodName = "/controlplane.v1.WorkflowRunService/View" ) // WorkflowRunServiceClient is the client API for WorkflowRunService service. @@ -438,9 +437,9 @@ const ( // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. type WorkflowRunServiceClient interface { List(ctx context.Context, in *WorkflowRunServiceListRequest, opts ...grpc.CallOption) (*WorkflowRunServiceListResponse, error) + // View returns the run, its attestation, its timeline of events, and, while the run + // is in progress, its progress View(ctx context.Context, in *WorkflowRunServiceViewRequest, opts ...grpc.CallOption) (*WorkflowRunServiceViewResponse, error) - // Events of a run, oldest first. Optional after_event_id returns only newer events. - ListEvents(ctx context.Context, in *WorkflowRunServiceListEventsRequest, opts ...grpc.CallOption) (*WorkflowRunServiceListEventsResponse, error) } type workflowRunServiceClient struct { @@ -469,23 +468,14 @@ func (c *workflowRunServiceClient) View(ctx context.Context, in *WorkflowRunServ return out, nil } -func (c *workflowRunServiceClient) ListEvents(ctx context.Context, in *WorkflowRunServiceListEventsRequest, opts ...grpc.CallOption) (*WorkflowRunServiceListEventsResponse, error) { - out := new(WorkflowRunServiceListEventsResponse) - err := c.cc.Invoke(ctx, WorkflowRunService_ListEvents_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 returns the run, its attestation, its timeline of events, and, while the run + // is in progress, its progress View(context.Context, *WorkflowRunServiceViewRequest) (*WorkflowRunServiceViewResponse, error) - // Events of a run, oldest first. Optional after_event_id returns only newer events. - ListEvents(context.Context, *WorkflowRunServiceListEventsRequest) (*WorkflowRunServiceListEventsResponse, error) mustEmbedUnimplementedWorkflowRunServiceServer() } @@ -499,9 +489,6 @@ 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) ListEvents(context.Context, *WorkflowRunServiceListEventsRequest) (*WorkflowRunServiceListEventsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ListEvents not implemented") -} func (UnimplementedWorkflowRunServiceServer) mustEmbedUnimplementedWorkflowRunServiceServer() {} // UnsafeWorkflowRunServiceServer may be embedded to opt out of forward compatibility for this service. @@ -551,24 +538,6 @@ func _WorkflowRunService_View_Handler(srv interface{}, ctx context.Context, dec return interceptor(ctx, in, info, handler) } -func _WorkflowRunService_ListEvents_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(WorkflowRunServiceListEventsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(WorkflowRunServiceServer).ListEvents(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: WorkflowRunService_ListEvents_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(WorkflowRunServiceServer).ListEvents(ctx, req.(*WorkflowRunServiceListEventsRequest)) - } - 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) @@ -584,10 +553,6 @@ var WorkflowRunService_ServiceDesc = grpc.ServiceDesc{ MethodName: "View", Handler: _WorkflowRunService_View_Handler, }, - { - MethodName: "ListEvents", - Handler: _WorkflowRunService_ListEvents_Handler, - }, }, Streams: []grpc.StreamDesc{}, Metadata: "controlplane/v1/workflow_run.proto", 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 51b8a87a4..ede4d3371 100644 --- a/app/controlplane/api/gen/frontend/controlplane/v1/workflow_run.ts +++ b/app/controlplane/api/gen/frontend/controlplane/v1/workflow_run.ts @@ -233,16 +233,6 @@ export interface AttestationServiceRecordEventRequest { export interface AttestationServiceRecordEventResponse { } -export interface WorkflowRunServiceListEventsRequest { - workflowRunId: string; - /** Optional. Return only the events recorded after this one. */ - afterEventId: string; -} - -export interface WorkflowRunServiceListEventsResponse { - events: WorkflowRunEvent[]; -} - /** * A progress event of a workflow run. Unsigned and informational only. * It is never part of the attestation. @@ -399,6 +389,19 @@ export interface WorkflowRunEvent_AttestationAttributes { 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 { @@ -477,6 +480,131 @@ export interface WorkflowRunServiceViewRequest { verify: boolean; } +/** 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; } @@ -487,6 +615,13 @@ export interface WorkflowRunServiceViewResponse_Result { attestation?: AttestationItem; /** It will be nil if the verification is not possible (old or non-keyless attestations) */ verification?: WorkflowRunServiceViewResponse_VerificationResult; + /** + * 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[]; } export interface WorkflowRunServiceViewResponse_VerificationResult { @@ -2286,145 +2421,6 @@ export const AttestationServiceRecordEventResponse = { }, }; -function createBaseWorkflowRunServiceListEventsRequest(): WorkflowRunServiceListEventsRequest { - return { workflowRunId: "", afterEventId: "" }; -} - -export const WorkflowRunServiceListEventsRequest = { - encode(message: WorkflowRunServiceListEventsRequest, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { - if (message.workflowRunId !== "") { - writer.uint32(10).string(message.workflowRunId); - } - if (message.afterEventId !== "") { - writer.uint32(18).string(message.afterEventId); - } - return writer; - }, - - decode(input: _m0.Reader | Uint8Array, length?: number): WorkflowRunServiceListEventsRequest { - const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input); - let end = length === undefined ? reader.len : reader.pos + length; - const message = createBaseWorkflowRunServiceListEventsRequest(); - while (reader.pos < end) { - const tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - if (tag !== 10) { - break; - } - - message.workflowRunId = reader.string(); - continue; - case 2: - if (tag !== 18) { - break; - } - - message.afterEventId = reader.string(); - continue; - } - if ((tag & 7) === 4 || tag === 0) { - break; - } - reader.skipType(tag & 7); - } - return message; - }, - - fromJSON(object: any): WorkflowRunServiceListEventsRequest { - return { - workflowRunId: isSet(object.workflowRunId) ? String(object.workflowRunId) : "", - afterEventId: isSet(object.afterEventId) ? String(object.afterEventId) : "", - }; - }, - - toJSON(message: WorkflowRunServiceListEventsRequest): unknown { - const obj: any = {}; - message.workflowRunId !== undefined && (obj.workflowRunId = message.workflowRunId); - message.afterEventId !== undefined && (obj.afterEventId = message.afterEventId); - return obj; - }, - - create, I>>( - base?: I, - ): WorkflowRunServiceListEventsRequest { - return WorkflowRunServiceListEventsRequest.fromPartial(base ?? {}); - }, - - fromPartial, I>>( - object: I, - ): WorkflowRunServiceListEventsRequest { - const message = createBaseWorkflowRunServiceListEventsRequest(); - message.workflowRunId = object.workflowRunId ?? ""; - message.afterEventId = object.afterEventId ?? ""; - return message; - }, -}; - -function createBaseWorkflowRunServiceListEventsResponse(): WorkflowRunServiceListEventsResponse { - return { events: [] }; -} - -export const WorkflowRunServiceListEventsResponse = { - encode(message: WorkflowRunServiceListEventsResponse, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer { - for (const v of message.events) { - WorkflowRunEvent.encode(v!, writer.uint32(10).fork()).ldelim(); - } - return writer; - }, - - decode(input: _m0.Reader | Uint8Array, length?: number): WorkflowRunServiceListEventsResponse { - const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input); - let end = length === undefined ? reader.len : reader.pos + length; - const message = createBaseWorkflowRunServiceListEventsResponse(); - while (reader.pos < end) { - const tag = reader.uint32(); - switch (tag >>> 3) { - case 1: - if (tag !== 10) { - break; - } - - message.events.push(WorkflowRunEvent.decode(reader, reader.uint32())); - continue; - } - if ((tag & 7) === 4 || tag === 0) { - break; - } - reader.skipType(tag & 7); - } - return message; - }, - - fromJSON(object: any): WorkflowRunServiceListEventsResponse { - return { events: Array.isArray(object?.events) ? object.events.map((e: any) => WorkflowRunEvent.fromJSON(e)) : [] }; - }, - - toJSON(message: WorkflowRunServiceListEventsResponse): unknown { - const obj: any = {}; - if (message.events) { - obj.events = message.events.map((e) => e ? WorkflowRunEvent.toJSON(e) : undefined); - } else { - obj.events = []; - } - return obj; - }, - - create, I>>( - base?: I, - ): WorkflowRunServiceListEventsResponse { - return WorkflowRunServiceListEventsResponse.fromPartial(base ?? {}); - }, - - fromPartial, I>>( - object: I, - ): WorkflowRunServiceListEventsResponse { - const message = createBaseWorkflowRunServiceListEventsResponse(); - message.events = object.events?.map((e) => WorkflowRunEvent.fromPartial(e)) || []; - return message; - }, -}; - function createBaseWorkflowRunEvent(): WorkflowRunEvent { return { id: "", @@ -2615,6 +2611,7 @@ function createBaseWorkflowRunEvent_AttestationAttributes(): WorkflowRunEvent_At cliVersion: "", attestationDigest: "", policies: undefined, + expectedMaterials: [], }; } @@ -2641,6 +2638,9 @@ export const WorkflowRunEvent_AttestationAttributes = { 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; }, @@ -2700,6 +2700,13 @@ export const WorkflowRunEvent_AttestationAttributes = { 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; @@ -2718,6 +2725,9 @@ export const WorkflowRunEvent_AttestationAttributes = { 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)) + : [], }; }, @@ -2731,6 +2741,13 @@ export const WorkflowRunEvent_AttestationAttributes = { 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; }, @@ -2753,6 +2770,109 @@ export const WorkflowRunEvent_AttestationAttributes = { 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; }, }; @@ -3370,6 +3490,290 @@ export const WorkflowRunServiceViewRequest = { }, }; +function createBaseWorkflowRunProgress(): WorkflowRunProgress { + return { materials: [], requiredTotal: 0, requiredProvided: 0, attestationPolicies: undefined }; +} + +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.requiredTotal !== 0) { + writer.uint32(16).int32(message.requiredTotal); + } + 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): WorkflowRunProgress { + const reader = input instanceof _m0.Reader ? input : _m0.Reader.create(input); + let end = length === undefined ? reader.len : reader.pos + length; + const message = createBaseWorkflowRunProgress(); + while (reader.pos < end) { + const tag = reader.uint32(); + switch (tag >>> 3) { + case 1: + if (tag !== 10) { + break; + } + + 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.materialType = reader.string(); + continue; + case 3: + if (tag !== 24) { + break; + } + + 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) { + break; + } + reader.skipType(tag & 7); + } + return message; + }, + + fromJSON(object: any): WorkflowRunProgress_Material { + return { + 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: WorkflowRunProgress_Material): unknown { + const obj: any = {}; + 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): WorkflowRunProgress_Material { + return WorkflowRunProgress_Material.fromPartial(base ?? {}); + }, + + 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; + }, +}; + function createBaseWorkflowRunServiceViewResponse(): WorkflowRunServiceViewResponse { return { result: undefined }; } @@ -3432,7 +3836,14 @@ export const WorkflowRunServiceViewResponse = { }; function createBaseWorkflowRunServiceViewResponse_Result(): WorkflowRunServiceViewResponse_Result { - return { orgName: "", workflowRun: undefined, attestation: undefined, verification: undefined }; + return { + orgName: "", + workflowRun: undefined, + attestation: undefined, + verification: undefined, + progress: undefined, + events: [], + }; } export const WorkflowRunServiceViewResponse_Result = { @@ -3449,6 +3860,12 @@ export const WorkflowRunServiceViewResponse_Result = { if (message.verification !== undefined) { WorkflowRunServiceViewResponse_VerificationResult.encode(message.verification, writer.uint32(26).fork()).ldelim(); } + if (message.progress !== undefined) { + WorkflowRunProgress.encode(message.progress, writer.uint32(50).fork()).ldelim(); + } + for (const v of message.events) { + WorkflowRunEvent.encode(v!, writer.uint32(58).fork()).ldelim(); + } return writer; }, @@ -3487,6 +3904,20 @@ export const WorkflowRunServiceViewResponse_Result = { message.verification = WorkflowRunServiceViewResponse_VerificationResult.decode(reader, reader.uint32()); continue; + case 6: + if (tag !== 50) { + break; + } + + message.progress = WorkflowRunProgress.decode(reader, reader.uint32()); + continue; + case 7: + if (tag !== 58) { + break; + } + + message.events.push(WorkflowRunEvent.decode(reader, reader.uint32())); + continue; } if ((tag & 7) === 4 || tag === 0) { break; @@ -3504,6 +3935,8 @@ export const WorkflowRunServiceViewResponse_Result = { verification: isSet(object.verification) ? WorkflowRunServiceViewResponse_VerificationResult.fromJSON(object.verification) : undefined, + progress: isSet(object.progress) ? WorkflowRunProgress.fromJSON(object.progress) : undefined, + events: Array.isArray(object?.events) ? object.events.map((e: any) => WorkflowRunEvent.fromJSON(e)) : [], }; }, @@ -3517,6 +3950,13 @@ export const WorkflowRunServiceViewResponse_Result = { message.verification !== undefined && (obj.verification = message.verification ? WorkflowRunServiceViewResponse_VerificationResult.toJSON(message.verification) : 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.events = []; + } return obj; }, @@ -3540,6 +3980,10 @@ export const WorkflowRunServiceViewResponse_Result = { message.verification = (object.verification !== undefined && object.verification !== null) ? WorkflowRunServiceViewResponse_VerificationResult.fromPartial(object.verification) : undefined; + message.progress = (object.progress !== undefined && object.progress !== null) + ? WorkflowRunProgress.fromPartial(object.progress) + : undefined; + message.events = object.events?.map((e) => WorkflowRunEvent.fromPartial(e)) || []; return message; }, }; @@ -4197,15 +4641,14 @@ export interface WorkflowRunService { request: DeepPartial, metadata?: grpc.Metadata, ): Promise; + /** + * View returns the run, its attestation, its timeline of events, and, while the run + * is in progress, its progress + */ View( request: DeepPartial, metadata?: grpc.Metadata, ): Promise; - /** Events of a run, oldest first. Optional after_event_id returns only newer events. */ - ListEvents( - request: DeepPartial, - metadata?: grpc.Metadata, - ): Promise; } export class WorkflowRunServiceClientImpl implements WorkflowRunService { @@ -4215,7 +4658,6 @@ export class WorkflowRunServiceClientImpl implements WorkflowRunService { this.rpc = rpc; this.List = this.List.bind(this); this.View = this.View.bind(this); - this.ListEvents = this.ListEvents.bind(this); } List( @@ -4231,17 +4673,6 @@ export class WorkflowRunServiceClientImpl implements WorkflowRunService { ): Promise { return this.rpc.unary(WorkflowRunServiceViewDesc, WorkflowRunServiceViewRequest.fromPartial(request), metadata); } - - ListEvents( - request: DeepPartial, - metadata?: grpc.Metadata, - ): Promise { - return this.rpc.unary( - WorkflowRunServiceListEventsDesc, - WorkflowRunServiceListEventsRequest.fromPartial(request), - metadata, - ); - } } export const WorkflowRunServiceDesc = { serviceName: "controlplane.v1.WorkflowRunService" }; @@ -4292,29 +4723,6 @@ export const WorkflowRunServiceViewDesc: UnaryMethodDefinitionish = { } as any, }; -export const WorkflowRunServiceListEventsDesc: UnaryMethodDefinitionish = { - methodName: "ListEvents", - service: WorkflowRunServiceDesc, - requestStream: false, - responseStream: false, - requestType: { - serializeBinary() { - return WorkflowRunServiceListEventsRequest.encode(this).finish(); - }, - } as any, - responseType: { - deserializeBinary(data: Uint8Array) { - const value = WorkflowRunServiceListEventsResponse.decode(data); - return { - ...value, - toObject() { - return value; - }, - }; - }, - } as any, -}; - interface UnaryMethodDefinitionishR extends grpc.UnaryMethodDefinition { requestStream: any; responseStream: any; 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 index 3e3126a61..ba098aec5 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.AttestationAttributes.jsonschema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.AttestationAttributes.jsonschema.json @@ -20,6 +20,13 @@ "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" }, @@ -46,6 +53,13 @@ "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" 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 index a18146e3b..1fb51db33 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.AttestationAttributes.schema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunEvent.AttestationAttributes.schema.json @@ -20,6 +20,13 @@ "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" }, @@ -46,6 +53,13 @@ "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" 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.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.WorkflowRunServiceListEventsRequest.jsonschema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceListEventsRequest.jsonschema.json deleted file mode 100644 index 8204f8dcf..000000000 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceListEventsRequest.jsonschema.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "$id": "controlplane.v1.WorkflowRunServiceListEventsRequest.jsonschema.json", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "additionalProperties": false, - "patternProperties": { - "^(after_event_id)$": { - "description": "Optional. Return only the events recorded after this one.", - "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" - }, - "^(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": { - "afterEventId": { - "description": "Optional. Return only the events recorded after this one.", - "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" - }, - "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 List Events Request", - "type": "object" -} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceListEventsRequest.schema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceListEventsRequest.schema.json deleted file mode 100644 index f4855db29..000000000 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceListEventsRequest.schema.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "$id": "controlplane.v1.WorkflowRunServiceListEventsRequest.schema.json", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "additionalProperties": false, - "patternProperties": { - "^(afterEventId)$": { - "description": "Optional. Return only the events recorded after this one.", - "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" - }, - "^(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": { - "after_event_id": { - "description": "Optional. Return only the events recorded after this one.", - "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" - }, - "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 List Events Request", - "type": "object" -} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceListEventsResponse.jsonschema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceListEventsResponse.jsonschema.json deleted file mode 100644 index 88751148f..000000000 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceListEventsResponse.jsonschema.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "$id": "controlplane.v1.WorkflowRunServiceListEventsResponse.jsonschema.json", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "additionalProperties": false, - "properties": { - "events": { - "items": { - "$ref": "controlplane.v1.WorkflowRunEvent.jsonschema.json" - }, - "type": "array" - } - }, - "title": "Workflow Run Service List Events Response", - "type": "object" -} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceListEventsResponse.schema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceListEventsResponse.schema.json deleted file mode 100644 index 5ecf1973d..000000000 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceListEventsResponse.schema.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "$id": "controlplane.v1.WorkflowRunServiceListEventsResponse.schema.json", - "$schema": "https://json-schema.org/draft/2020-12/schema", - "additionalProperties": false, - "properties": { - "events": { - "items": { - "$ref": "controlplane.v1.WorkflowRunEvent.schema.json" - }, - "type": "array" - } - }, - "title": "Workflow Run Service List Events Response", - "type": "object" -} diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceViewResponse.Result.jsonschema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceViewResponse.Result.jsonschema.json index 826ee43ca..e844089f0 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceViewResponse.Result.jsonschema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceViewResponse.Result.jsonschema.json @@ -14,9 +14,20 @@ "attestation": { "$ref": "controlplane.v1.AttestationItem.jsonschema.json" }, + "events": { + "description": "Timeline of the run, oldest first. Reported data, never part of the attestation.", + "items": { + "$ref": "controlplane.v1.WorkflowRunEvent.jsonschema.json" + }, + "type": "array" + }, "orgName": { "type": "string" }, + "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." + }, "verification": { "$ref": "controlplane.v1.WorkflowRunServiceViewResponse.VerificationResult.jsonschema.json", "description": "It will be nil if the verification is not possible (old or non-keyless attestations)" diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceViewResponse.Result.schema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceViewResponse.Result.schema.json index 19169799e..f39b88a4c 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceViewResponse.Result.schema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceViewResponse.Result.schema.json @@ -14,9 +14,20 @@ "attestation": { "$ref": "controlplane.v1.AttestationItem.schema.json" }, + "events": { + "description": "Timeline of the run, oldest first. Reported data, never part of the attestation.", + "items": { + "$ref": "controlplane.v1.WorkflowRunEvent.schema.json" + }, + "type": "array" + }, "org_name": { "type": "string" }, + "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." + }, "verification": { "$ref": "controlplane.v1.WorkflowRunServiceViewResponse.VerificationResult.schema.json", "description": "It will be nil if the verification is not possible (old or non-keyless attestations)" diff --git a/app/controlplane/internal/service/workflowrun.go b/app/controlplane/internal/service/workflowrun.go index 837d3dd99..685cda79f 100644 --- a/app/controlplane/internal/service/workflowrun.go +++ b/app/controlplane/internal/service/workflowrun.go @@ -429,6 +429,22 @@ func (s *WorkflowRunService) View(ctx context.Context, req *pb.WorkflowRunServic Verification: verificationResult, } + // The timeline is reported data. A failure to read it does not fail the view. + events, err := s.runEventUseCase.List(ctx, run.ID.String()) + if err != nil { + s.log.Warnw("msg", "failed to list the events of the run", "run", run.ID.String(), "error", err) + } else { + res.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) { + res.Progress = bizWorkflowRunProgressToPb(biz.BuildWorkflowRunProgress(contractAndVersion.Version.Schema, events)) + } + } + return &pb.WorkflowRunServiceViewResponse{Result: res}, nil } @@ -604,36 +620,6 @@ func (s *WorkflowRunService) validateAndGetProjectID(ctx context.Context, orgID, return project.ID, nil } -// ListEvents returns the progress events of a run, oldest first. It applies the same checks as View. -func (s *WorkflowRunService) ListEvents(ctx context.Context, req *pb.WorkflowRunServiceListEventsRequest) (*pb.WorkflowRunServiceListEventsResponse, 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(), req.GetAfterEventId()) - if err != nil { - return nil, handleUseCaseErr(ctx, err, s.log) - } - - result := make([]*pb.WorkflowRunEvent, 0, len(events)) - for _, e := range events { - result = append(result, bizWorkflowRunEventToPb(e)) - } - - return &pb.WorkflowRunServiceListEventsResponse{Events: result}, nil -} - var ( pbToBizRunEventType = map[pb.WorkflowRunEvent_Type]biz.WorkflowRunEventType{ pb.WorkflowRunEvent_TYPE_ATTESTATION: biz.WorkflowRunEventTypeAttestation, @@ -693,6 +679,7 @@ func pbWorkflowRunEventToBiz(in *pb.WorkflowRunEvent) (*biz.WorkflowRunEvent, er CLIVersion: a.GetCliVersion(), AttestationDigest: a.GetAttestationDigest(), Policies: pbPolicyCountsToBiz(a.GetPolicies()), + ExpectedMaterials: pbExpectedMaterialsToBiz(a.GetExpectedMaterials()), }} case *pb.WorkflowRunEvent_Material: m := attrs.Material @@ -765,6 +752,7 @@ func bizWorkflowRunEventToPb(in *biz.WorkflowRunEvent) *pb.WorkflowRunEvent { CliVersion: a.CLIVersion, AttestationDigest: a.AttestationDigest, Policies: bizPolicyCountsToPb(a.Policies), + ExpectedMaterials: bizExpectedMaterialsToPb(a.ExpectedMaterials), }} case attrs.Material != nil: m := attrs.Material @@ -781,3 +769,70 @@ func bizWorkflowRunEventToPb(in *biz.WorkflowRunEvent) *pb.WorkflowRunEvent { 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 index c0d6fc2e2..e150eb502 100644 --- a/app/controlplane/internal/service/workflowrunevent_integration_test.go +++ b/app/controlplane/internal/service/workflowrunevent_integration_test.go @@ -34,8 +34,8 @@ import ( "github.com/stretchr/testify/suite" ) -// RecordEvent copies the checks of Store, and ListEvents copies the checks of View. No new -// policy is involved, so every caller keeps the access it has to the run itself. +// RecordEvent copies the checks of Store, and View returns the events with its own checks. 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 @@ -190,7 +190,7 @@ func (s *workflowRunEventRBACIntegrationSuite) TestCallerTable() { apiCtx func() context.Context runID func() string wantRecord runEventOutcome - wantList runEventOutcome + wantView runEventOutcome }{ { name: "org API token, accepted by Store", @@ -198,7 +198,7 @@ func (s *workflowRunEventRBACIntegrationSuite) TestCallerTable() { apiCtx: func() context.Context { return s.apiCtxForToken(s.org, s.orgToken) }, runID: func() string { return s.runA.ID.String() }, wantRecord: allowed, - wantList: allowed, + wantView: allowed, }, { name: "project admin user, accepted by Store", @@ -206,7 +206,7 @@ func (s *workflowRunEventRBACIntegrationSuite) TestCallerTable() { apiCtx: func() context.Context { return s.apiCtxForUser(s.org, authz.RoleProjectAdmin) }, runID: func() string { return s.runA.ID.String() }, wantRecord: allowed, - wantList: allowed, + wantView: allowed, }, { name: "token pinned to another workflow of the same project", @@ -215,7 +215,7 @@ func (s *workflowRunEventRBACIntegrationSuite) TestCallerTable() { runID: func() string { return s.runA.ID.String() }, wantRecord: forbidden, // as for View, which allows the project of the token - wantList: allowed, + wantView: allowed, }, { name: "API token scoped to another project", @@ -223,7 +223,7 @@ func (s *workflowRunEventRBACIntegrationSuite) TestCallerTable() { apiCtx: func() context.Context { return s.apiCtxForToken(s.org, s.projectBToken) }, runID: func() string { return s.runA.ID.String() }, wantRecord: forbidden, - wantList: forbidden, + wantView: forbidden, }, { name: "user who can only view the project", @@ -231,7 +231,7 @@ func (s *workflowRunEventRBACIntegrationSuite) TestCallerTable() { apiCtx: func() context.Context { return s.apiCtxForUser(s.org, authz.RoleProjectViewer) }, runID: func() string { return s.runA.ID.String() }, wantRecord: forbidden, - wantList: allowed, + wantView: allowed, }, { name: "user with no access to the project", @@ -239,7 +239,7 @@ func (s *workflowRunEventRBACIntegrationSuite) TestCallerTable() { apiCtx: func() context.Context { return s.apiCtxForUser(s.org, "") }, runID: func() string { return s.runA.ID.String() }, wantRecord: forbidden, - wantList: forbidden, + wantView: forbidden, }, { name: "org API token, run in another organization", @@ -247,7 +247,7 @@ func (s *workflowRunEventRBACIntegrationSuite) TestCallerTable() { apiCtx: func() context.Context { return s.apiCtxForToken(s.org, s.orgToken) }, runID: func() string { return s.runOtherOrg.ID.String() }, wantRecord: notFound, - wantList: notFound, + wantView: notFound, }, { name: "project admin user, run in another organization", @@ -255,7 +255,7 @@ func (s *workflowRunEventRBACIntegrationSuite) TestCallerTable() { apiCtx: func() context.Context { return s.apiCtxForUser(s.org, authz.RoleProjectAdmin) }, runID: func() string { return s.runOtherOrg.ID.String() }, wantRecord: notFound, - wantList: notFound, + wantView: notFound, }, } @@ -273,46 +273,58 @@ func (s *workflowRunEventRBACIntegrationSuite) TestCallerTable() { s.assertOutcome(tc.wantRecord, storeErr) } - _, err = s.runSvc.ListEvents(tc.apiCtx(), &pb.WorkflowRunServiceListEventsRequest{WorkflowRunId: tc.runID()}) - s.assertOutcome(tc.wantList, err) - _, viewErr := s.runSvc.View(tc.apiCtx(), &pb.WorkflowRunServiceViewRequest{Ref: &pb.WorkflowRunServiceViewRequest_Id{Id: tc.runID()}}) - s.assertOutcome(tc.wantList, viewErr) + s.assertOutcome(tc.wantView, viewErr) }) } } -func (s *workflowRunEventRBACIntegrationSuite) TestRecordAndList() { +func (s *workflowRunEventRBACIntegrationSuite) TestRecordAndView() { ctx := s.attCtxForToken(s.org, s.orgToken) runID := s.runA.ID.String() _, err := s.attSvc.RecordEvent(ctx, materialEventRequest(runID)) s.Require().NoError(err) - resp, err := s.runSvc.ListEvents(s.apiCtxForToken(s.org, s.orgToken), &pb.WorkflowRunServiceListEventsRequest{WorkflowRunId: runID}) - s.Require().NoError(err) - s.Require().Len(resp.GetEvents(), 1) + view := func() *pb.WorkflowRunServiceViewResponse_Result { + resp, err := s.runSvc.View(s.apiCtxForToken(s.org, s.orgToken), &pb.WorkflowRunServiceViewRequest{Ref: &pb.WorkflowRunServiceViewRequest_Id{Id: runID}}) + s.Require().NoError(err) + return resp.GetResult() + } + + res := view() + s.Require().Len(res.GetEvents(), 1) - got := resp.GetEvents()[0] + 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") - resp, err = s.runSvc.ListEvents(s.apiCtxForToken(s.org, s.orgToken), &pb.WorkflowRunServiceListEventsRequest{ - WorkflowRunId: runID, AfterEventId: got.GetId(), - }) - s.Require().NoError(err) - s.Require().Len(resp.GetEvents(), 1) - s.Equal(pb.WorkflowRunEvent_SOURCE_CONTROL_PLANE, resp.GetEvents()[0].GetSource()) - s.Equal(pb.WorkflowRunEvent_STATUS_SUCCEEDED, resp.GetEvents()[0].GetStatus()) + // 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() { diff --git a/app/controlplane/pkg/authz/authz.go b/app/controlplane/pkg/authz/authz.go index 0765e01fd..89ab52bf3 100644 --- a/app/controlplane/pkg/authz/authz.go +++ b/app/controlplane/pkg/authz/authz.go @@ -394,9 +394,8 @@ 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/ListEvents": {Policies: []*Policy{PolicyWorkflowRunRead}}, + "/controlplane.v1.WorkflowRunService/List": {Policies: []*Policy{PolicyWorkflowRunList}}, + "/controlplane.v1.WorkflowRunService/View": {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/biz/mocks/WorkflowRunEventRepo.go b/app/controlplane/pkg/biz/mocks/WorkflowRunEventRepo.go index 77276923a..1fbb8af29 100644 --- a/app/controlplane/pkg/biz/mocks/WorkflowRunEventRepo.go +++ b/app/controlplane/pkg/biz/mocks/WorkflowRunEventRepo.go @@ -196,8 +196,8 @@ func (_c *WorkflowRunEventRepo_DeleteOlderThan_Call) RunAndReturn(run func(ctx c } // List provides a mock function for the type WorkflowRunEventRepo -func (_mock *WorkflowRunEventRepo) List(ctx context.Context, runID uuid.UUID, afterID *uuid.UUID) ([]*biz.WorkflowRunEvent, error) { - ret := _mock.Called(ctx, runID, afterID) +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") @@ -205,18 +205,18 @@ func (_mock *WorkflowRunEventRepo) List(ctx context.Context, runID uuid.UUID, af var r0 []*biz.WorkflowRunEvent var r1 error - if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, *uuid.UUID) ([]*biz.WorkflowRunEvent, error)); ok { - return returnFunc(ctx, runID, afterID) + 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, *uuid.UUID) []*biz.WorkflowRunEvent); ok { - r0 = returnFunc(ctx, runID, afterID) + 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, *uuid.UUID) error); ok { - r1 = returnFunc(ctx, runID, afterID) + if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID) error); ok { + r1 = returnFunc(ctx, runID) } else { r1 = ret.Error(1) } @@ -231,12 +231,11 @@ type WorkflowRunEventRepo_List_Call struct { // List is a helper method to define mock.On call // - ctx context.Context // - runID uuid.UUID -// - afterID *uuid.UUID -func (_e *WorkflowRunEventRepo_Expecter) List(ctx any, runID any, afterID any) *WorkflowRunEventRepo_List_Call { - return &WorkflowRunEventRepo_List_Call{Call: _e.mock.On("List", ctx, runID, afterID)} +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, afterID *uuid.UUID)) *WorkflowRunEventRepo_List_Call { +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 { @@ -246,14 +245,9 @@ func (_c *WorkflowRunEventRepo_List_Call) Run(run func(ctx context.Context, runI if args[1] != nil { arg1 = args[1].(uuid.UUID) } - var arg2 *uuid.UUID - if args[2] != nil { - arg2 = args[2].(*uuid.UUID) - } run( arg0, arg1, - arg2, ) }) return _c @@ -264,7 +258,7 @@ func (_c *WorkflowRunEventRepo_List_Call) Return(workflowRunEvents []*biz.Workfl return _c } -func (_c *WorkflowRunEventRepo_List_Call) RunAndReturn(run func(ctx context.Context, runID uuid.UUID, afterID *uuid.UUID) ([]*biz.WorkflowRunEvent, error)) *WorkflowRunEventRepo_List_Call { +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/workflowrunevent.go b/app/controlplane/pkg/biz/workflowrunevent.go index aeadd74d1..00c1ef665 100644 --- a/app/controlplane/pkg/biz/workflowrunevent.go +++ b/app/controlplane/pkg/biz/workflowrunevent.go @@ -116,6 +116,17 @@ type WorkflowRunEventAttestationAttributes struct { 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 { @@ -140,9 +151,8 @@ 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. When afterID is set, it returns only - // the events recorded after that one. An afterID of another run returns no events. - List(ctx context.Context, runID uuid.UUID, afterID *uuid.UUID) ([]*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) } @@ -213,7 +223,7 @@ func validateWorkflowRunEvent(ev *WorkflowRunEvent) error { } // List returns the events of a run, oldest first. -func (uc *WorkflowRunEventUseCase) List(ctx context.Context, runID string, afterID string) ([]*WorkflowRunEvent, error) { +func (uc *WorkflowRunEventUseCase) List(ctx context.Context, runID string) ([]*WorkflowRunEvent, error) { ctx, span := otelx.Start(ctx, workflowRunEventTracer, "WorkflowRunEventUseCase.List") defer span.End() @@ -222,16 +232,7 @@ func (uc *WorkflowRunEventUseCase) List(ctx context.Context, runID string, after return nil, NewErrInvalidUUID(err) } - var afterUUID *uuid.UUID - if afterID != "" { - id, err := uuid.Parse(afterID) - if err != nil { - return nil, NewErrInvalidUUID(err) - } - afterUUID = &id - } - - return uc.repo.List(ctx, runUUID, afterUUID) + return uc.repo.List(ctx, runUUID) } // DeleteOlderThan deletes the events created before t, in batches of batchSize. diff --git a/app/controlplane/pkg/biz/workflowrunprogress.go b/app/controlplane/pkg/biz/workflowrunprogress.go new file mode 100644 index 000000000..981d62a65 --- /dev/null +++ b/app/controlplane/pkg/biz/workflowrunprogress.go @@ -0,0 +1,205 @@ +// +// 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 + // error of the last add, when it failed + 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.lastError = e, "" + case WorkflowRunEventStatusFailed: + a.lastError = 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.lastError != "" { + 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..490f95979 --- /dev/null +++ b/app/controlplane/pkg/biz/workflowrunprogress_test.go @@ -0,0 +1,190 @@ +// +// 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" +) + +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, then a successful one", contract: contract, + events: []*WorkflowRunEvent{failed(progressSBOM, "bad bomFormat"), added(progressSBOM, "sbom.json")}, + material: progressSBOM, wantTotal: 1, wantProvided: 1, + want: &WorkflowRunProgressMaterial{Name: progressSBOM, MaterialType: progressCycloneDX, Requirement: WorkflowRunMaterialRequired, + Status: WorkflowRunMaterialProvided, Value: "sbom.json", FailedAttempts: 1}, + }, + { + name: "successful add, then a rejected duplicate add", contract: contract, + events: []*WorkflowRunEvent{added(progressSBOM, "sbom.json"), failed(progressSBOM, progressDupErr)}, + material: progressSBOM, wantTotal: 1, wantProvided: 1, + want: &WorkflowRunProgressMaterial{Name: progressSBOM, MaterialType: progressCycloneDX, Requirement: WorkflowRunMaterialRequired, + Status: WorkflowRunMaterialProvided, Value: "sbom.json", LastError: progressDupErr, FailedAttempts: 1}, + }, + { + name: "successful add, then a failed replacement", contract: contract, + events: []*WorkflowRunEvent{added(progressSBOM, "sbom.json"), failed(progressSBOM, "invalid CycloneDX document")}, + material: progressSBOM, wantTotal: 1, wantProvided: 1, + want: &WorkflowRunProgressMaterial{Name: progressSBOM, MaterialType: progressCycloneDX, Requirement: WorkflowRunMaterialRequired, + Status: WorkflowRunMaterialProvided, Value: "sbom.json", 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, "sbom.json")}, + material: progressSBOM, wantTotal: 1, wantProvided: 1, + want: &WorkflowRunProgressMaterial{Name: progressSBOM, MaterialType: progressCycloneDX, Requirement: WorkflowRunMaterialRequired, + Status: WorkflowRunMaterialProvided, Value: "sbom.json"}, + }, + { + 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: "CONTAINER_IMAGE"}, + )}, + material: progressImage, wantTotal: 2, + want: &WorkflowRunProgressMaterial{Name: progressImage, MaterialType: "CONTAINER_IMAGE", 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: "notes", Type: schemav1.CraftingSchema_Material_STRING, Optional: true}, + ), + events: []*WorkflowRunEvent{added("cyclonedx", "bom.json")}, + material: "notes", wantTotal: 1, wantProvided: 1, + want: &WorkflowRunProgressMaterial{Name: "notes", 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/workflowrunevent.go b/app/controlplane/pkg/data/workflowrunevent.go index 3096bb4bd..73b8432a1 100644 --- a/app/controlplane/pkg/data/workflowrunevent.go +++ b/app/controlplane/pkg/data/workflowrunevent.go @@ -101,36 +101,12 @@ func createWorkflowRunEvent(ctx context.Context, client *ent.Client, event *biz. return ev, nil } -func (r *WorkflowRunEventRepo) List(ctx context.Context, runID uuid.UUID, afterID *uuid.UUID) ([]*biz.WorkflowRunEvent, error) { +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)) - if afterID != nil { - // The reference event must belong to the same run - after, err := r.data.DB.WorkflowRunEvent.Query(). - Where(workflowrunevent.ID(*afterID), workflowrunevent.WorkflowRunID(runID)). - Only(ctx) - if err != nil { - if ent.IsNotFound(err) { - return []*biz.WorkflowRunEvent{}, nil - } - return nil, fmt.Errorf("failed to find workflow run event: %w", err) - } - - // Newer than the reference event, with the ID as a tie breaker of the same time - q = q.Where(func(s *sql.Selector) { - s.Where(sql.Or( - sql.GT(s.C(workflowrunevent.FieldCreatedAt), after.CreatedAt), - sql.And( - sql.EQ(s.C(workflowrunevent.FieldCreatedAt), after.CreatedAt), - sql.GT(s.C(workflowrunevent.FieldID), after.ID), - ), - )) - }) - } - 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) diff --git a/app/controlplane/pkg/data/workflowrunevent_integration_test.go b/app/controlplane/pkg/data/workflowrunevent_integration_test.go index ea5bf5f48..27db60b0e 100644 --- a/app/controlplane/pkg/data/workflowrunevent_integration_test.go +++ b/app/controlplane/pkg/data/workflowrunevent_integration_test.go @@ -163,28 +163,22 @@ func (s *workflowRunEventIntegrationTestSuite) TestList() { ids = append(ids, ev.ID) } - otherRunID := s.newRun() - otherEv, err := repo.Create(ctx, materialEvent(otherRunID, "x", biz.WorkflowRunEventStatusSucceeded), 10) + // the events of another run never show + _, err := repo.Create(ctx, materialEvent(s.newRun(), "x", biz.WorkflowRunEventStatusSucceeded), 10) s.Require().NoError(err) - unknown := uuid.New() testCases := []struct { - name string - runID uuid.UUID - afterID *uuid.UUID - want []uuid.UUID + name string + runID uuid.UUID + want []uuid.UUID }{ - {name: "all events, oldest first", runID: runID, want: ids}, - {name: "after the first event", runID: runID, afterID: &ids[0], want: ids[1:]}, - {name: "after the last event", runID: runID, afterID: &ids[2], want: nil}, - {name: "after an event of another run", runID: runID, afterID: &otherEv.ID, want: nil}, - {name: "after an unknown event", runID: runID, afterID: &unknown, want: nil}, + {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, tc.afterID) + got, err := repo.List(ctx, tc.runID) s.Require().NoError(err) gotIDs := make([]uuid.UUID, 0, len(got)) @@ -307,7 +301,7 @@ func (s *workflowRunEventIntegrationTestSuite) TestClosingEvent() { s.Require().NoError(tc.finish(runID)) - events, err := s.Repos.WorkflowRunEvent.List(ctx, runID, nil) + events, err := s.Repos.WorkflowRunEvent.List(ctx, runID) s.Require().NoError(err) s.Require().Len(events, 2) @@ -340,7 +334,7 @@ func (s *workflowRunEventIntegrationTestSuite) TestExpireSkipsFinishedRun() { s.Require().NoError(err) s.Equal(biz.WorkflowRunSuccess, run.State) - events, err := s.Repos.WorkflowRunEvent.List(ctx, runID, nil) + 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/docs/plans/issue-3825-attestation-progress-events.md b/docs/plans/issue-3825-attestation-progress-events.md index 03ac3b038..9778795a5 100644 --- a/docs/plans/issue-3825-attestation-progress-events.md +++ b/docs/plans/issue-3825-attestation-progress-events.md @@ -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: View with events and progress"]:::changed biz["run events use case"]:::new fin["store, cancel, expire"]:::changed exp["run expiry job"]:::changed @@ -96,7 +96,7 @@ 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 the run view 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/` | @@ -106,7 +106,7 @@ One new table. A deleted run deletes its events. An index on the run and the tim ### 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,6 @@ 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); } + +message AttestationServiceRecordEventRequest { @@ -128,12 +126,25 @@ R-003, R-005, R-008 (M1) and R-009 (M2). `app/controlplane/api/controlplane/v1/w +} +message AttestationServiceRecordEventResponse {} + -+message WorkflowRunServiceListEventsRequest { -+ 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 WorkflowRunServiceViewResponse { ++ message Result { ++ // ... existing fields ++ // Progress of a run in progress, built by the control plane. Not set for a finished run. ++ WorkflowRunProgress progress = 6; ++ // Timeline of the run, oldest first ++ repeated WorkflowRunEvent events = 7; ++ } +} -+message WorkflowRunServiceListEventsResponse { -+ repeated WorkflowRunEvent events = 1; ++ ++// 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 { @@ -152,7 +163,9 @@ R-003, R-005, R-008 (M1) and R-009 (M2). `app/controlplane/api/controlplane/v1/w + 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 PolicyCounts { int32 evaluated = 1; int32 passed = 2; int32 violated = 3; int32 skipped = 4; repeated string violated_policies = 5; } +} @@ -211,32 +224,31 @@ 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, R-010 | none | +| 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, R-010, R-011 | 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` and `add`, the store closes the timeline, 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 and read calls, the closing events, and the deletion of old events. The CLI records events from `init` and `add`, the store closes the timeline, and `describe` shows them. The write call copies `Store`, the run view returns the events and the progress, 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` | +| `View` (events and progress) | no change: its 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_consistency_test.go` | Add `RecordEvent` to the exempt list next to `Store` and `Cancel`. |
@@ -244,7 +256,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 +267,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,11 +292,11 @@ 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 the events and progress in 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 and MATERIAL, 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. `View` 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. A failure to read the events does not fail `View`. -| Caller | `RecordEvent` | `ListEvents` | +| Caller | `RecordEvent` | `View` | |--------|---------------|--------------| | Any caller that `Store` accepts for the run | allowed | allowed | | Token pinned to another workflow | denied | as for `View` | @@ -296,8 +308,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 the events and the progress to `View`. | +| `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 that `View` returns the events and the progress of a run in progress. |
@@ -322,7 +335,7 @@ Add a retention duration to the attestations section of the config, with a defau
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`). `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. +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 | |-----------------------------|----------| @@ -339,16 +352,16 @@ Add a recorder to the CLI actions: `Record(ctx, event) error` sends with a 2-sec
-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 of a run in progress from the start event. It shows the timeline as a tree: one line for each step, with the events of a repeated step below it. 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. 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` shows the events and the progress that `View` returns, with no logic of its own for the checklist (spec D-012). A step of the timeline shows its last successful add, with the failed attempts below it. It shows the timeline as a tree: one line for each step, with the events of a repeated step below it. 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. An older control plane returns no events and no progress, and `describe` shows the run as before. | File | Change | |------|--------| -| `app/cli/pkg/action/workflow_run_describe.go` | Call `ListEvents`, build the checklist and the steps. | +| `app/cli/pkg/action/workflow_run_describe.go` | Map the events and the progress of the `View` response. | | `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_test.go` | Add table tests: a run in progress with its progress, an expired run, an older control plane with no events. | +| `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`, `View` returns no events, and the `add` and `describe` callers succeed. |
diff --git a/docs/specs/issue-3825-attestation-progress-events.md b/docs/specs/issue-3825-attestation-progress-events.md index 1c082408a..d1ea21e5a 100644 --- a/docs/specs/issue-3825-attestation-progress-events.md +++ b/docs/specs/issue-3825-attestation-progress-events.md @@ -68,8 +68,10 @@ Superseded by R-010. 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: @@ -105,6 +107,10 @@ Supersedes R-001. The CLI MUST record a run event at each action of the attestat - 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. The run view of the control plane MUST return the events of the run, oldest first, with the permissions of the run view. For a run in progress, it 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. @@ -127,11 +133,11 @@ Supersedes R-001. The CLI MUST record a run event at each action of the attestat 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 run view 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 in the run view (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. +**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.~~ It polls the run view while the run is in progress (D-012). ```mermaid sequenceDiagram @@ -151,7 +157,7 @@ sequenceDiagram CP-->>U: signed attestation + timeline as history ``` -Dashed arrows are best effort. A failed event does not stop the attestation. Since D-011, the CLI sends no push event. +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, "view run + list events" is one call, the run view, which also returns the progress. ## Decision Record @@ -200,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. @@ -236,13 +244,21 @@ The CLI records no `chainloop.push` event. The closing event of the store (R-006 - 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: The run view returns the progress and the events +Supersedes D-007. The run view call returns the events and, for a run in progress, the progress (R-011). The control plane builds the progress. There is no separate read call for events. +- Why: a run in progress has no attestation yet, so its run view is small, and a client can poll it. After the store, the run is finished and no client polls it. One call gives the UI and other tools all the data to show, with no join of the contract and the events in each client. The control plane builds the progress once, so all clients show the same result. +- Alternatives considered: + - A separate read call for events, 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. + - A separate read call that also returns the progress: two calls for one page, and two sets of the same checks. +- 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). R-010 supersedes R-001. +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 From b99a43c2416b71954cda559ccae922629be892f3 Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Tue, 1 Dec 2026 12:02:07 +0100 Subject: [PATCH 16/20] test: use constants for repeated strings in the progress tests Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1cdb3220-119c-4a14-ac50-52d5437ee4eb --- app/cli/pkg/action/runevents_test.go | 11 ++++--- .../pkg/action/workflow_run_describe_test.go | 10 +++---- .../pkg/biz/workflowrunprogress_test.go | 30 +++++++++++-------- 3 files changed, 29 insertions(+), 22 deletions(-) diff --git a/app/cli/pkg/action/runevents_test.go b/app/cli/pkg/action/runevents_test.go index fcbb5b411..4cb188e11 100644 --- a/app/cli/pkg/action/runevents_test.go +++ b/app/cli/pkg/action/runevents_test.go @@ -56,6 +56,9 @@ const ( testCommit = "commit-1234" testSBOMGate = "sbom-gate" testLicenses = "cdx-licenses" + testSBOMs = "sboms" + testCDX = "cdx" + testInvalid = "invalid CycloneDX document" ) const testRunID = "4f8d2b7e-8c1b-4b1e-9f3a-2a6f1b2c3d4e" @@ -261,7 +264,7 @@ func TestAttestationAddArchiveEvents(t *testing.T) { }) require.NoError(t, err) - res, err := add.Run(context.Background(), "", "sboms", zipPath, testSBOMKind, nil, nil, nil) + res, err := add.Run(context.Background(), "", testSBOMs, zipPath, testSBOMKind, nil, nil, nil) require.NoError(t, err) require.Len(t, res, tc.entries) @@ -307,7 +310,7 @@ func TestArchiveAddedEvent(t *testing.T) { flagName string wantKey string }{ - {name: "with --name", flagName: "sboms", wantKey: "chainloop.material.sboms"}, + {name: "with --name", flagName: testSBOMs, wantKey: "chainloop.material." + testSBOMs}, {name: "with no --name, the archive file name", wantKey: "chainloop.material.bundle"}, } @@ -520,7 +523,7 @@ func TestAttestationStartedEventExpectedMaterials(t *testing.T) { 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: "cdx", Type: schemaapi.CraftingSchema_Material_SBOM_CYCLONEDX_JSON, Group: "sboms"}, + {Name: testCDX, Type: schemaapi.CraftingSchema_Material_SBOM_CYCLONEDX_JSON, Group: testSBOMs}, }}}, Attestation: &api.Attestation{}, } @@ -530,5 +533,5 @@ func TestAttestationStartedEventExpectedMaterials(t *testing.T) { 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, "sboms", got[2].GetGroup()) + assert.Equal(t, testSBOMs, got[2].GetGroup()) } diff --git a/app/cli/pkg/action/workflow_run_describe_test.go b/app/cli/pkg/action/workflow_run_describe_test.go index d9e62c27d..957a368fd 100644 --- a/app/cli/pkg/action/workflow_run_describe_test.go +++ b/app/cli/pkg/action/workflow_run_describe_test.go @@ -180,7 +180,7 @@ func (f *fakeRunViewServer) View(context.Context, *pb.WorkflowRunServiceViewRequ 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: "invalid CycloneDX document", + Key: testSBOMKey, Status: pb.WorkflowRunEvent_STATUS_FAILED, Message: testInvalid, Attributes: &pb.WorkflowRunEvent_Material{Material: &pb.WorkflowRunEvent_MaterialAttributes{Name: testSBOM, InContract: true}}, } expired := &pb.WorkflowRunEvent{ @@ -191,8 +191,8 @@ func TestWorkflowRunDescribeEvents(t *testing.T) { RequiredTotal: 2, RequiredProvided: 1, Materials: []*pb.WorkflowRunProgress_Material{ {Name: testSBOM, MaterialType: testSBOMKind, Requirement: pb.WorkflowRunProgress_REQUIREMENT_REQUIRED, - Status: pb.WorkflowRunProgress_STATUS_FAILED, LastError: "invalid CycloneDX document", FailedAttempts: 1}, - {Name: "cdx", Requirement: pb.WorkflowRunProgress_REQUIREMENT_ONE_OF_GROUP, Group: "sboms", Status: pb.WorkflowRunProgress_STATUS_PROVIDED, Value: "bom.json"}, + 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"}, }, } @@ -207,8 +207,8 @@ func TestWorkflowRunDescribeEvents(t *testing.T) { 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: "invalid CycloneDX document", FailedAttempts: 1}, - {Name: "cdx", Requirement: RunMaterialOneOfGroup, Group: "sboms", Status: RunMaterialProvided, Value: "bom.json"}, + {Name: testSBOM, Type: testSBOMKind, Requirement: RunMaterialRequired, Status: RunMaterialFailed, LastError: testInvalid, FailedAttempts: 1}, + {Name: testCDX, Requirement: RunMaterialOneOfGroup, Group: testSBOMs, Status: RunMaterialProvided, Value: "bom.json"}, }}, }, { diff --git a/app/controlplane/pkg/biz/workflowrunprogress_test.go b/app/controlplane/pkg/biz/workflowrunprogress_test.go index 490f95979..9c9b455eb 100644 --- a/app/controlplane/pkg/biz/workflowrunprogress_test.go +++ b/app/controlplane/pkg/biz/workflowrunprogress_test.go @@ -28,8 +28,12 @@ const ( 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{ @@ -74,24 +78,24 @@ func TestBuildWorkflowRunProgress(t *testing.T) { }, { name: "failed add, then a successful one", contract: contract, - events: []*WorkflowRunEvent{failed(progressSBOM, "bad bomFormat"), added(progressSBOM, "sbom.json")}, + 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: "sbom.json", FailedAttempts: 1}, + Status: WorkflowRunMaterialProvided, Value: progressSBOMFile, FailedAttempts: 1}, }, { name: "successful add, then a rejected duplicate add", contract: contract, - events: []*WorkflowRunEvent{added(progressSBOM, "sbom.json"), failed(progressSBOM, progressDupErr)}, + 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: "sbom.json", LastError: progressDupErr, FailedAttempts: 1}, + Status: WorkflowRunMaterialProvided, Value: progressSBOMFile, LastError: progressDupErr, FailedAttempts: 1}, }, { name: "successful add, then a failed replacement", contract: contract, - events: []*WorkflowRunEvent{added(progressSBOM, "sbom.json"), failed(progressSBOM, "invalid CycloneDX document")}, + 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: "sbom.json", LastError: "invalid CycloneDX document", FailedAttempts: 1}, + Status: WorkflowRunMaterialProvided, Value: progressSBOMFile, LastError: "invalid CycloneDX document", FailedAttempts: 1}, }, { name: "material that only a policy group requires, from the start event", @@ -102,10 +106,10 @@ func TestBuildWorkflowRunProgress(t *testing.T) { }, { name: "provided policy group material is in the contract", - events: []*WorkflowRunEvent{started(&WorkflowRunEventExpectedMaterial{Name: progressSBOM, MaterialType: progressCycloneDX}), added(progressSBOM, "sbom.json")}, + 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: "sbom.json"}, + Status: WorkflowRunMaterialProvided, Value: progressSBOMFile}, }, { name: "the start event list wins over the contract", @@ -113,10 +117,10 @@ func TestBuildWorkflowRunProgress(t *testing.T) { contract: contract, events: []*WorkflowRunEvent{started( &WorkflowRunEventExpectedMaterial{Name: progressSBOM, MaterialType: progressCycloneDX}, - &WorkflowRunEventExpectedMaterial{Name: progressImage, MaterialType: "CONTAINER_IMAGE"}, + &WorkflowRunEventExpectedMaterial{Name: progressImage, MaterialType: progressImageType}, )}, material: progressImage, wantTotal: 2, - want: &WorkflowRunProgressMaterial{Name: progressImage, MaterialType: "CONTAINER_IMAGE", Requirement: WorkflowRunMaterialRequired, Status: WorkflowRunMaterialMissing}, + want: &WorkflowRunProgressMaterial{Name: progressImage, MaterialType: progressImageType, Requirement: WorkflowRunMaterialRequired, Status: WorkflowRunMaterialMissing}, }, { name: "material not in the contract", @@ -130,11 +134,11 @@ func TestBuildWorkflowRunProgress(t *testing.T) { 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: "notes", Type: schemav1.CraftingSchema_Material_STRING, Optional: true}, + &schemav1.CraftingSchema_Material{Name: progressNotes, Type: schemav1.CraftingSchema_Material_STRING, Optional: true}, ), events: []*WorkflowRunEvent{added("cyclonedx", "bom.json")}, - material: "notes", wantTotal: 1, wantProvided: 1, - want: &WorkflowRunProgressMaterial{Name: "notes", MaterialType: "STRING", Requirement: WorkflowRunMaterialOptional, Status: WorkflowRunMaterialMissing}, + material: progressNotes, wantTotal: 1, wantProvided: 1, + want: &WorkflowRunProgressMaterial{Name: progressNotes, MaterialType: "STRING", Requirement: WorkflowRunMaterialOptional, Status: WorkflowRunMaterialMissing}, }, } From 6dfba1cd6691ae3bbbab0abcaacef4dbd62313d8 Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Tue, 1 Dec 2026 12:05:13 +0100 Subject: [PATCH 17/20] docs: align the plan with the progress in the run view Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1cdb3220-119c-4a14-ac50-52d5437ee4eb --- .../issue-3825-attestation-progress-events.md | 62 ++++++++++--------- 1 file changed, 33 insertions(+), 29 deletions(-) diff --git a/docs/plans/issue-3825-attestation-progress-events.md b/docs/plans/issue-3825-attestation-progress-events.md index 9778795a5..22374d054 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. The run view of the workflow run API 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 run view keeps its access rules. ### Rollout @@ -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 the run view. **Data model** @@ -99,7 +99,7 @@ One new table. A deleted run deletes its events. An index on the run and the tim | Other parts of the product | The platform UI can poll the run view 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 @@ -181,24 +181,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 the run view. 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: @@ -224,12 +226,12 @@ 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, R-010, R-011 | 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` and `add`, the store closes the timeline, and `describe` shows them. The write call copies `Store`, the run view returns the events and the progress, 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. Its run view 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`, the run view returns the events and the progress, 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. @@ -297,9 +299,9 @@ Wrap the status update and the insert of the closing `chainloop.attestation` eve `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. `View` 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. A failure to read the events does not fail `View`. | Caller | `RecordEvent` | `View` | -|--------|---------------|--------------| +|--------|---------------|--------| | 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 | @@ -347,19 +349,21 @@ Add a recorder to the CLI actions: `Record(ctx, event) error` sends with a 2-sec |------|--------| | `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` | 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. | +| `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, R-011) -`describe` shows the events and the progress that `View` returns, with no logic of its own for the checklist (spec D-012). A step of the timeline shows its last successful add, with the failed attempts below it. It shows the timeline as a tree: one line for each step, with the events of a repeated step below it. 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. An older control plane returns no events and no progress, and `describe` shows the run as before. +`describe` shows the events and the progress that `View` 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. An older control plane returns no events and no progress, and `describe` shows the run as before. | File | Change | |------|--------| | `app/cli/pkg/action/workflow_run_describe.go` | Map the events and the progress of the `View` response. | -| `app/cli/cmd/workflow_workflow_run_describe.go` | Print the materials, policies, and timeline. | +| `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, an older control plane with no events. | | `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`, `View` returns no events, and the `add` and `describe` callers succeed. | @@ -404,7 +408,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 the run view, with up to 1,000 events and the progress, can serve the poll rate of the platform UI. | Risk | Mitigation | |------|------------| From d9200876426e93ea6d1ae4affab04a5eda5ad80e Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Tue, 1 Dec 2026 12:12:46 +0100 Subject: [PATCH 18/20] fix: show a failed add with no error text as failed in the progress Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1cdb3220-119c-4a14-ac50-52d5437ee4eb --- app/controlplane/pkg/biz/workflowrunprogress.go | 13 +++++++------ .../pkg/biz/workflowrunprogress_test.go | 6 ++++++ .../plans/issue-3825-attestation-progress-events.md | 2 +- 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/app/controlplane/pkg/biz/workflowrunprogress.go b/app/controlplane/pkg/biz/workflowrunprogress.go index 981d62a65..5bd5437db 100644 --- a/app/controlplane/pkg/biz/workflowrunprogress.go +++ b/app/controlplane/pkg/biz/workflowrunprogress.go @@ -97,9 +97,10 @@ func BuildWorkflowRunProgress(contract *Contract, events []*WorkflowRunEvent) *W // the attempts of each material, in the order they were first reported type attempts struct { lastSuccess *WorkflowRunEvent - // error of the last add, when it failed - lastError string - failed int32 + // whether the last add failed, and its error + lastFailed bool + lastError string + failed int32 } byName := make(map[string]*attempts) var order []string @@ -117,9 +118,9 @@ func BuildWorkflowRunProgress(contract *Contract, events []*WorkflowRunEvent) *W } switch e.Status { case WorkflowRunEventStatusSucceeded: - a.lastSuccess, a.lastError = e, "" + a.lastSuccess, a.lastFailed, a.lastError = e, false, "" case WorkflowRunEventStatusFailed: - a.lastError = e.Message + a.lastFailed, a.lastError = true, e.Message a.failed++ } case attrs.Attestation != nil && e.Status == WorkflowRunEventStatusStarted: @@ -143,7 +144,7 @@ func BuildWorkflowRunProgress(contract *Contract, events []*WorkflowRunEvent) *W } m.FailedAttempts, m.LastError = a.failed, a.lastError - if a.lastError != "" { + if a.lastFailed { m.Status = WorkflowRunMaterialFailed } diff --git a/app/controlplane/pkg/biz/workflowrunprogress_test.go b/app/controlplane/pkg/biz/workflowrunprogress_test.go index 9c9b455eb..4f798fd78 100644 --- a/app/controlplane/pkg/biz/workflowrunprogress_test.go +++ b/app/controlplane/pkg/biz/workflowrunprogress_test.go @@ -76,6 +76,12 @@ func TestBuildWorkflowRunProgress(t *testing.T) { 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)}, diff --git a/docs/plans/issue-3825-attestation-progress-events.md b/docs/plans/issue-3825-attestation-progress-events.md index 22374d054..2a811d992 100644 --- a/docs/plans/issue-3825-attestation-progress-events.md +++ b/docs/plans/issue-3825-attestation-progress-events.md @@ -296,7 +296,7 @@ Wrap the status update and the insert of the closing `chainloop.attestation` eve
04 / 07 · Serve the write call with the checks of Store, and the events and progress in 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 and MATERIAL, with a key that starts with `chainloop.`, and an attributes field that matches the type. `View` 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. A failure to read the events does not fail `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. `View` 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. A failure to read the events does not fail `View`. `View` then returns no events and no progress, because a progress with no events would show all the materials as missing. | Caller | `RecordEvent` | `View` | |--------|---------------|--------| From 26ef6ca1c6dceaa538e3c54679c85692fa93b4e9 Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Tue, 1 Dec 2026 12:32:25 +0100 Subject: [PATCH 19/20] feat: serve the run progress and events in their own GetProgress call WorkflowRunService.View goes back to its main behavior. The new GetProgress call, with the checks of View, returns the events of a run and, while it is in progress, the progress that the control plane builds. describe calls it after View, and an older control plane without it shows the run as before. A run with no events from the CLI, as from an older CLI, shows no timeline. Spec: R-011 and D-012 describe the separate call. Refs #3825 Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1cdb3220-119c-4a14-ac50-52d5437ee4eb --- app/cli/cmd/workflow_run_timeline.go | 5 +- app/cli/cmd/workflow_run_timeline_test.go | 22 +- app/cli/pkg/action/runevents_compat_test.go | 4 +- app/cli/pkg/action/workflow_run_describe.go | 28 +- .../pkg/action/workflow_run_describe_test.go | 34 +- .../api/controlplane/v1/workflow_run.pb.go | 396 +++++++++++------- .../api/controlplane/v1/workflow_run.proto | 21 +- .../controlplane/v1/workflow_run_grpc.pb.go | 47 ++- .../frontend/controlplane/v1/workflow_run.ts | 249 ++++++++--- ...nServiceGetProgressRequest.jsonschema.json | 19 + ...owRunServiceGetProgressRequest.schema.json | 19 + ...ServiceGetProgressResponse.jsonschema.json | 20 + ...wRunServiceGetProgressResponse.schema.json | 20 + ...ServiceViewResponse.Result.jsonschema.json | 11 - ...wRunServiceViewResponse.Result.schema.json | 11 - .../internal/service/workflowrun.go | 58 ++- .../workflowrunevent_integration_test.go | 15 +- app/controlplane/pkg/authz/authz.go | 5 +- .../issue-3825-attestation-progress-events.md | 53 +-- .../issue-3825-attestation-progress-events.md | 20 +- 20 files changed, 734 insertions(+), 323 deletions(-) create mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceGetProgressRequest.jsonschema.json create mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceGetProgressRequest.schema.json create mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceGetProgressResponse.jsonschema.json create mode 100644 app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceGetProgressResponse.schema.json diff --git a/app/cli/cmd/workflow_run_timeline.go b/app/cli/cmd/workflow_run_timeline.go index 01c7ae9bb..f525ad47a 100644 --- a/app/cli/cmd/workflow_run_timeline.go +++ b/app/cli/cmd/workflow_run_timeline.go @@ -33,6 +33,7 @@ const ( timelineMaxDetail = 120 timelineFailed = "failed" + timelineSourceCLI = "cli" timelineStarted = "started" timelineSucceeded = "succeeded" ) @@ -52,7 +53,9 @@ type timelineNode struct { // 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) { - if len(events) == 0 { + // 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 } diff --git a/app/cli/cmd/workflow_run_timeline_test.go b/app/cli/cmd/workflow_run_timeline_test.go index 53a6ed35a..13d1a2431 100644 --- a/app/cli/cmd/workflow_run_timeline_test.go +++ b/app/cli/cmd/workflow_run_timeline_test.go @@ -34,10 +34,10 @@ func TestRenderRunTimeline(t *testing.T) { v := start.Add(d) return &v } - started := &action.RunEvent{CreatedAt: at(0), Key: timelineKeyAttestation, Status: "started", Attestation: &action.RunEventAttestation{ + 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), Key: "chainloop.material." + name, Status: status, Message: msg, + return &action.RunEvent{CreatedAt: at(d), Source: timelineSourceCLI, Key: "chainloop.material." + name, Status: status, Message: msg, Material: &action.RunEventMaterial{Name: name, Policies: policies}} } @@ -102,7 +102,7 @@ func TestRenderRunTimeline(t *testing.T) { events: []*action.RunEvent{ started, material(451*time.Second, "vulnerability-report", "succeeded", "", nil), - {CreatedAt: at(501 * time.Second), Key: timelineKeyAttestation, Status: "succeeded", Attestation: &action.RunEventAttestation{ + {CreatedAt: at(501 * time.Second), Key: timelineKeyAttestation, Status: timelineSucceeded, Attestation: &action.RunEventAttestation{ AttestationDigest: "sha256:4de7a1b2c3d4e5f60718293a4b5c6d7e8f"}}, }, stored: &action.PolicyEvaluationStatus{Total: 3, Passed: 3}, @@ -144,8 +144,16 @@ func TestRenderRunTimeline(t *testing.T) { } } -func TestRenderRunTimelineNoEvents(t *testing.T) { - var buf bytes.Buffer - renderRunTimeline(&buf, nil, nil, nil, time.Now()) - assert.Empty(t, 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/pkg/action/runevents_compat_test.go b/app/cli/pkg/action/runevents_compat_test.go index fa1696db1..9dad7e2d1 100644 --- a/app/cli/pkg/action/runevents_compat_test.go +++ b/app/cli/pkg/action/runevents_compat_test.go @@ -56,8 +56,8 @@ func TestRunEventsAgainstOlderControlPlane(t *testing.T) { conn := newBufConn(t, func(s *grpc.Server) { attDesc := withoutMethods(pb.AttestationService_ServiceDesc, "RecordEvent") s.RegisterService(&attDesc, attSvc) - // an older View returns no events and no progress - pb.RegisterWorkflowRunServiceServer(s, runSvc) + runDesc := withoutMethods(pb.WorkflowRunService_ServiceDesc, "GetProgress") + s.RegisterService(&runDesc, runSvc) }) t.Run("the recorder gets Unimplemented and turns off", func(t *testing.T) { diff --git a/app/cli/pkg/action/workflow_run_describe.go b/app/cli/pkg/action/workflow_run_describe.go index 4ad136b2b..1f3b9557c 100644 --- a/app/cli/pkg/action/workflow_run_describe.go +++ b/app/cli/pkg/action/workflow_run_describe.go @@ -38,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 { @@ -214,11 +216,8 @@ func (action *WorkflowRunDescribe) Run(ctx context.Context, opts *WorkflowRunDes item.WorkflowRun.FinishedAt = toTimePtr(wr.FinishedAt.AsTime()) } - // An older control plane returns no events and no progress: describe shows the run as before - for _, e := range resp.GetResult().GetEvents() { - item.Events = append(item.Events, pbRunEventToAction(e)) - } - item.Progress = pbRunProgressToAction(resp.GetResult().GetProgress()) + // 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 @@ -675,6 +674,25 @@ var ( } ) +// 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 diff --git a/app/cli/pkg/action/workflow_run_describe_test.go b/app/cli/pkg/action/workflow_run_describe_test.go index 957a368fd..85fa7e3cb 100644 --- a/app/cli/pkg/action/workflow_run_describe_test.go +++ b/app/cli/pkg/action/workflow_run_describe_test.go @@ -28,6 +28,8 @@ import ( "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" ) @@ -161,22 +163,30 @@ func TestPBPolicyEvaluationsRefToAction(t *testing.T) { } } -// fakeRunViewServer serves View for one run, with the events and the progress it is given +// 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 + 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()}, - Events: f.events, - Progress: f.progress, }}, 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, @@ -217,9 +227,17 @@ func TestWorkflowRunDescribeEvents(t *testing.T) { wantEvents: 2, }, { - name: "older control plane, with no events and no progress", + 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 { @@ -228,7 +246,7 @@ func TestWorkflowRunDescribeEvents(t *testing.T) { got, err := NewWorkflowRunDescribe(&ActionsOpts{CPConnection: conn, Logger: zerolog.Nop()}). Run(context.Background(), &WorkflowRunDescribeOpts{RunID: testRunID}) - require.NoError(t, err) + 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 667399f57..1bbfe1b77 100644 --- a/app/controlplane/api/controlplane/v1/workflow_run.pb.go +++ b/app/controlplane/api/controlplane/v1/workflow_run.pb.go @@ -293,7 +293,7 @@ func (x WorkflowRunProgress_Requirement) Number() protoreflect.EnumNumber { // Deprecated: Use WorkflowRunProgress_Requirement.Descriptor instead. func (WorkflowRunProgress_Requirement) EnumDescriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{21, 0} + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{23, 0} } type WorkflowRunProgress_Status int32 @@ -348,7 +348,7 @@ func (x WorkflowRunProgress_Status) Number() protoreflect.EnumNumber { // Deprecated: Use WorkflowRunProgress_Status.Descriptor instead. func (WorkflowRunProgress_Status) EnumDescriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{21, 1} + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{23, 1} } type FindOrCreateWorkflowRequest struct { @@ -1723,6 +1723,105 @@ 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"` @@ -1739,7 +1838,7 @@ type WorkflowRunProgress struct { func (x *WorkflowRunProgress) Reset() { *x = WorkflowRunProgress{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[21] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[23] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1751,7 +1850,7 @@ func (x *WorkflowRunProgress) String() string { func (*WorkflowRunProgress) ProtoMessage() {} func (x *WorkflowRunProgress) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[21] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[23] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1764,7 +1863,7 @@ func (x *WorkflowRunProgress) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkflowRunProgress.ProtoReflect.Descriptor instead. func (*WorkflowRunProgress) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{21} + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{23} } func (x *WorkflowRunProgress) GetMaterials() []*WorkflowRunProgress_Material { @@ -1804,7 +1903,7 @@ type WorkflowRunServiceViewResponse struct { func (x *WorkflowRunServiceViewResponse) Reset() { *x = WorkflowRunServiceViewResponse{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[22] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[24] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1816,7 +1915,7 @@ func (x *WorkflowRunServiceViewResponse) String() string { func (*WorkflowRunServiceViewResponse) ProtoMessage() {} func (x *WorkflowRunServiceViewResponse) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[22] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[24] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1829,7 +1928,7 @@ func (x *WorkflowRunServiceViewResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkflowRunServiceViewResponse.ProtoReflect.Descriptor instead. func (*WorkflowRunServiceViewResponse) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{22} + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{24} } func (x *WorkflowRunServiceViewResponse) GetResult() *WorkflowRunServiceViewResponse_Result { @@ -1848,7 +1947,7 @@ type AttestationServiceGetUploadCredsRequest struct { func (x *AttestationServiceGetUploadCredsRequest) Reset() { *x = AttestationServiceGetUploadCredsRequest{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[23] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[25] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1860,7 +1959,7 @@ func (x *AttestationServiceGetUploadCredsRequest) String() string { func (*AttestationServiceGetUploadCredsRequest) ProtoMessage() {} func (x *AttestationServiceGetUploadCredsRequest) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[23] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[25] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1873,7 +1972,7 @@ func (x *AttestationServiceGetUploadCredsRequest) ProtoReflect() protoreflect.Me // Deprecated: Use AttestationServiceGetUploadCredsRequest.ProtoReflect.Descriptor instead. func (*AttestationServiceGetUploadCredsRequest) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{23} + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{25} } func (x *AttestationServiceGetUploadCredsRequest) GetWorkflowRunId() string { @@ -1892,7 +1991,7 @@ type AttestationServiceGetUploadCredsResponse struct { func (x *AttestationServiceGetUploadCredsResponse) Reset() { *x = AttestationServiceGetUploadCredsResponse{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[24] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[26] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1904,7 +2003,7 @@ func (x *AttestationServiceGetUploadCredsResponse) String() string { func (*AttestationServiceGetUploadCredsResponse) ProtoMessage() {} func (x *AttestationServiceGetUploadCredsResponse) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[24] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[26] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1917,7 +2016,7 @@ func (x *AttestationServiceGetUploadCredsResponse) ProtoReflect() protoreflect.M // Deprecated: Use AttestationServiceGetUploadCredsResponse.ProtoReflect.Descriptor instead. func (*AttestationServiceGetUploadCredsResponse) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{24} + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{26} } func (x *AttestationServiceGetUploadCredsResponse) GetResult() *AttestationServiceGetUploadCredsResponse_Result { @@ -1937,7 +2036,7 @@ type AttestationServiceGetContractResponse_Result struct { func (x *AttestationServiceGetContractResponse_Result) Reset() { *x = AttestationServiceGetContractResponse_Result{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[25] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[27] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1949,7 +2048,7 @@ func (x *AttestationServiceGetContractResponse_Result) String() string { func (*AttestationServiceGetContractResponse_Result) ProtoMessage() {} func (x *AttestationServiceGetContractResponse_Result) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[25] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[27] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2005,7 +2104,7 @@ type AttestationServiceInitResponse_Result struct { func (x *AttestationServiceInitResponse_Result) Reset() { *x = AttestationServiceInitResponse_Result{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[26] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[28] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2017,7 +2116,7 @@ func (x *AttestationServiceInitResponse_Result) String() string { func (*AttestationServiceInitResponse_Result) ProtoMessage() {} func (x *AttestationServiceInitResponse_Result) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[26] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[28] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2108,7 +2207,7 @@ type AttestationServiceInitResponse_SigningOptions struct { func (x *AttestationServiceInitResponse_SigningOptions) Reset() { *x = AttestationServiceInitResponse_SigningOptions{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[27] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[29] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2120,7 +2219,7 @@ func (x *AttestationServiceInitResponse_SigningOptions) String() string { func (*AttestationServiceInitResponse_SigningOptions) ProtoMessage() {} func (x *AttestationServiceInitResponse_SigningOptions) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[27] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[29] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2160,7 +2259,7 @@ type AttestationServiceStoreResponse_Result struct { func (x *AttestationServiceStoreResponse_Result) Reset() { *x = AttestationServiceStoreResponse_Result{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[28] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[30] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2172,7 +2271,7 @@ func (x *AttestationServiceStoreResponse_Result) String() string { func (*AttestationServiceStoreResponse_Result) ProtoMessage() {} func (x *AttestationServiceStoreResponse_Result) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[28] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[30] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2214,7 +2313,7 @@ type WorkflowRunEvent_AttestationAttributes struct { func (x *WorkflowRunEvent_AttestationAttributes) Reset() { *x = WorkflowRunEvent_AttestationAttributes{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[29] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[31] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2226,7 +2325,7 @@ func (x *WorkflowRunEvent_AttestationAttributes) String() string { func (*WorkflowRunEvent_AttestationAttributes) ProtoMessage() {} func (x *WorkflowRunEvent_AttestationAttributes) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[29] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[31] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2311,7 +2410,7 @@ type WorkflowRunEvent_ExpectedMaterial struct { func (x *WorkflowRunEvent_ExpectedMaterial) Reset() { *x = WorkflowRunEvent_ExpectedMaterial{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[30] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[32] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2323,7 +2422,7 @@ func (x *WorkflowRunEvent_ExpectedMaterial) String() string { func (*WorkflowRunEvent_ExpectedMaterial) ProtoMessage() {} func (x *WorkflowRunEvent_ExpectedMaterial) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[30] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[32] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2383,7 +2482,7 @@ type WorkflowRunEvent_MaterialAttributes struct { func (x *WorkflowRunEvent_MaterialAttributes) Reset() { *x = WorkflowRunEvent_MaterialAttributes{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[31] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[33] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2395,7 +2494,7 @@ func (x *WorkflowRunEvent_MaterialAttributes) String() string { func (*WorkflowRunEvent_MaterialAttributes) ProtoMessage() {} func (x *WorkflowRunEvent_MaterialAttributes) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[31] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[33] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2473,7 +2572,7 @@ type WorkflowRunEvent_PolicyCounts struct { func (x *WorkflowRunEvent_PolicyCounts) Reset() { *x = WorkflowRunEvent_PolicyCounts{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[32] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[34] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2485,7 +2584,7 @@ func (x *WorkflowRunEvent_PolicyCounts) String() string { func (*WorkflowRunEvent_PolicyCounts) ProtoMessage() {} func (x *WorkflowRunEvent_PolicyCounts) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[32] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[34] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2556,7 +2655,7 @@ type WorkflowRunProgress_Material struct { func (x *WorkflowRunProgress_Material) Reset() { *x = WorkflowRunProgress_Material{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[33] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[35] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2568,7 +2667,7 @@ func (x *WorkflowRunProgress_Material) String() string { func (*WorkflowRunProgress_Material) ProtoMessage() {} func (x *WorkflowRunProgress_Material) ProtoReflect() protoreflect.Message { - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[33] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[35] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2581,7 +2680,7 @@ func (x *WorkflowRunProgress_Material) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkflowRunProgress_Material.ProtoReflect.Descriptor instead. func (*WorkflowRunProgress_Material) Descriptor() ([]byte, []int) { - return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{21, 0} + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{23, 0} } func (x *WorkflowRunProgress_Material) GetName() string { @@ -2653,19 +2752,14 @@ type WorkflowRunServiceViewResponse_Result struct { WorkflowRun *WorkflowRunItem `protobuf:"bytes,1,opt,name=workflow_run,json=workflowRun,proto3" json:"workflow_run,omitempty"` Attestation *AttestationItem `protobuf:"bytes,2,opt,name=attestation,proto3" json:"attestation,omitempty"` // It will be nil if the verification is not possible (old or non-keyless attestations) - Verification *WorkflowRunServiceViewResponse_VerificationResult `protobuf:"bytes,3,opt,name=verification,proto3" json:"verification,omitempty"` - // 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,6,opt,name=progress,proto3" json:"progress,omitempty"` - // Timeline of the run, oldest first. Reported data, never part of the attestation. - Events []*WorkflowRunEvent `protobuf:"bytes,7,rep,name=events,proto3" json:"events,omitempty"` + Verification *WorkflowRunServiceViewResponse_VerificationResult `protobuf:"bytes,3,opt,name=verification,proto3" json:"verification,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *WorkflowRunServiceViewResponse_Result) Reset() { *x = WorkflowRunServiceViewResponse_Result{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[34] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[36] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2677,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[34] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[36] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2690,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{22, 0} + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{24, 0} } func (x *WorkflowRunServiceViewResponse_Result) GetOrgName() string { @@ -2721,20 +2815,6 @@ func (x *WorkflowRunServiceViewResponse_Result) GetVerification() *WorkflowRunSe return nil } -func (x *WorkflowRunServiceViewResponse_Result) GetProgress() *WorkflowRunProgress { - if x != nil { - return x.Progress - } - return nil -} - -func (x *WorkflowRunServiceViewResponse_Result) GetEvents() []*WorkflowRunEvent { - if x != nil { - return x.Events - } - return nil -} - type WorkflowRunServiceViewResponse_VerificationResult struct { state protoimpl.MessageState `protogen:"open.v1"` // if it can be verified this will hold the result of the verification @@ -2747,7 +2827,7 @@ type WorkflowRunServiceViewResponse_VerificationResult struct { func (x *WorkflowRunServiceViewResponse_VerificationResult) Reset() { *x = WorkflowRunServiceViewResponse_VerificationResult{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[35] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[37] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2759,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[35] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[37] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2772,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{22, 1} + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{24, 1} } func (x *WorkflowRunServiceViewResponse_VerificationResult) GetVerified() bool { @@ -2799,7 +2879,7 @@ type AttestationServiceGetUploadCredsResponse_Result struct { func (x *AttestationServiceGetUploadCredsResponse_Result) Reset() { *x = AttestationServiceGetUploadCredsResponse_Result{} - mi := &file_controlplane_v1_workflow_run_proto_msgTypes[36] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[38] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2811,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[36] + mi := &file_controlplane_v1_workflow_run_proto_msgTypes[38] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2824,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{24, 0} + return file_controlplane_v1_workflow_run_proto_rawDescGZIP(), []int{26, 0} } func (x *AttestationServiceGetUploadCredsResponse_Result) GetToken() string { @@ -3018,7 +3098,12 @@ 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\"\xb6\a\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" + @@ -3045,16 +3130,14 @@ const file_controlplane_v1_workflow_run_proto_rawDesc = "" + "\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\"\xdd\x04\n" + + "\rSTATUS_FAILED\x10\x03\"\xe0\x03\n" + "\x1eWorkflowRunServiceViewResponse\x12N\n" + - "\x06result\x18\x01 \x01(\v26.controlplane.v1.WorkflowRunServiceViewResponse.ResultR\x06result\x1a\x91\x03\n" + + "\x06result\x18\x01 \x01(\v26.controlplane.v1.WorkflowRunServiceViewResponse.ResultR\x06result\x1a\x94\x02\n" + "\x06Result\x12\x19\n" + "\borg_name\x18\x05 \x01(\tR\aorgName\x12C\n" + "\fworkflow_run\x18\x01 \x01(\v2 .controlplane.v1.WorkflowRunItemR\vworkflowRun\x12B\n" + "\vattestation\x18\x02 \x01(\v2 .controlplane.v1.AttestationItemR\vattestation\x12f\n" + - "\fverification\x18\x03 \x01(\v2B.controlplane.v1.WorkflowRunServiceViewResponse.VerificationResultR\fverification\x12@\n" + - "\bprogress\x18\x06 \x01(\v2$.controlplane.v1.WorkflowRunProgressR\bprogress\x129\n" + - "\x06events\x18\a \x03(\v2!.controlplane.v1.WorkflowRunEventR\x06events\x1aW\n" + + "\fverification\x18\x03 \x01(\v2B.controlplane.v1.WorkflowRunServiceViewResponse.VerificationResultR\fverification\x1aW\n" + "\x12VerificationResult\x12\x1a\n" + "\bverified\x18\x01 \x01(\bR\bverified\x12%\n" + "\x0efailure_reason\x18\x02 \x01(\tR\rfailureReason\"Q\n" + @@ -3074,10 +3157,11 @@ const file_controlplane_v1_workflow_run_proto_rawDesc = "" + "\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 @@ -3092,7 +3176,7 @@ func file_controlplane_v1_workflow_run_proto_rawDescGZIP() []byte { } var file_controlplane_v1_workflow_run_proto_enumTypes = make([]protoimpl.EnumInfo, 6) -var file_controlplane_v1_workflow_run_proto_msgTypes = make([]protoimpl.MessageInfo, 37) +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 (WorkflowRunEvent_Source)(0), // 1: controlplane.v1.WorkflowRunEvent.Source @@ -3121,107 +3205,111 @@ var file_controlplane_v1_workflow_run_proto_goTypes = []any{ (*WorkflowRunServiceListRequest)(nil), // 24: controlplane.v1.WorkflowRunServiceListRequest (*WorkflowRunServiceListResponse)(nil), // 25: controlplane.v1.WorkflowRunServiceListResponse (*WorkflowRunServiceViewRequest)(nil), // 26: controlplane.v1.WorkflowRunServiceViewRequest - (*WorkflowRunProgress)(nil), // 27: controlplane.v1.WorkflowRunProgress - (*WorkflowRunServiceViewResponse)(nil), // 28: controlplane.v1.WorkflowRunServiceViewResponse - (*AttestationServiceGetUploadCredsRequest)(nil), // 29: controlplane.v1.AttestationServiceGetUploadCredsRequest - (*AttestationServiceGetUploadCredsResponse)(nil), // 30: controlplane.v1.AttestationServiceGetUploadCredsResponse - (*AttestationServiceGetContractResponse_Result)(nil), // 31: controlplane.v1.AttestationServiceGetContractResponse.Result - (*AttestationServiceInitResponse_Result)(nil), // 32: controlplane.v1.AttestationServiceInitResponse.Result - (*AttestationServiceInitResponse_SigningOptions)(nil), // 33: controlplane.v1.AttestationServiceInitResponse.SigningOptions - (*AttestationServiceStoreResponse_Result)(nil), // 34: controlplane.v1.AttestationServiceStoreResponse.Result - (*WorkflowRunEvent_AttestationAttributes)(nil), // 35: controlplane.v1.WorkflowRunEvent.AttestationAttributes - (*WorkflowRunEvent_ExpectedMaterial)(nil), // 36: controlplane.v1.WorkflowRunEvent.ExpectedMaterial - (*WorkflowRunEvent_MaterialAttributes)(nil), // 37: controlplane.v1.WorkflowRunEvent.MaterialAttributes - (*WorkflowRunEvent_PolicyCounts)(nil), // 38: controlplane.v1.WorkflowRunEvent.PolicyCounts - (*WorkflowRunProgress_Material)(nil), // 39: controlplane.v1.WorkflowRunProgress.Material - (*WorkflowRunServiceViewResponse_Result)(nil), // 40: controlplane.v1.WorkflowRunServiceViewResponse.Result - (*WorkflowRunServiceViewResponse_VerificationResult)(nil), // 41: controlplane.v1.WorkflowRunServiceViewResponse.VerificationResult - (*AttestationServiceGetUploadCredsResponse_Result)(nil), // 42: controlplane.v1.AttestationServiceGetUploadCredsResponse.Result - (*WorkflowItem)(nil), // 43: controlplane.v1.WorkflowItem - (*v1.Policy)(nil), // 44: workflowcontract.v1.Policy - (*v1.PolicyGroup)(nil), // 45: workflowcontract.v1.PolicyGroup - (v1.CraftingSchema_Runner_RunnerType)(0), // 46: workflowcontract.v1.CraftingSchema.Runner.RunnerType - (*timestamppb.Timestamp)(nil), // 47: google.protobuf.Timestamp - (RunStatus)(0), // 48: controlplane.v1.RunStatus - (PolicyViolationsFilter)(0), // 49: controlplane.v1.PolicyViolationsFilter - (PolicyStatusFilter)(0), // 50: controlplane.v1.PolicyStatusFilter - (PolicyGatesFilter)(0), // 51: controlplane.v1.PolicyGatesFilter - (*CursorPaginationRequest)(nil), // 52: controlplane.v1.CursorPaginationRequest - (*WorkflowRunItem)(nil), // 53: controlplane.v1.WorkflowRunItem - (*CursorPaginationResponse)(nil), // 54: controlplane.v1.CursorPaginationResponse - (*WorkflowContractVersionItem)(nil), // 55: controlplane.v1.WorkflowContractVersionItem - (*AttestationItem)(nil), // 56: controlplane.v1.AttestationItem - (*CASBackendItem)(nil), // 57: controlplane.v1.CASBackendItem + (*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{ - 43, // 0: controlplane.v1.FindOrCreateWorkflowResponse.result:type_name -> controlplane.v1.WorkflowItem - 44, // 1: controlplane.v1.AttestationServiceGetPolicyResponse.policy:type_name -> workflowcontract.v1.Policy + 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 - 45, // 3: controlplane.v1.AttestationServiceGetPolicyGroupResponse.group:type_name -> workflowcontract.v1.PolicyGroup + 47, // 3: controlplane.v1.AttestationServiceGetPolicyGroupResponse.group:type_name -> workflowcontract.v1.PolicyGroup 10, // 4: controlplane.v1.AttestationServiceGetPolicyGroupResponse.reference:type_name -> controlplane.v1.RemotePolicyReference - 31, // 5: controlplane.v1.AttestationServiceGetContractResponse.result:type_name -> controlplane.v1.AttestationServiceGetContractResponse.Result - 46, // 6: controlplane.v1.AttestationServiceInitRequest.runner:type_name -> workflowcontract.v1.CraftingSchema.Runner.RunnerType - 32, // 7: controlplane.v1.AttestationServiceInitResponse.result:type_name -> controlplane.v1.AttestationServiceInitResponse.Result - 34, // 8: controlplane.v1.AttestationServiceStoreResponse.result:type_name -> controlplane.v1.AttestationServiceStoreResponse.Result + 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 23, // 10: controlplane.v1.AttestationServiceRecordEventRequest.event:type_name -> controlplane.v1.WorkflowRunEvent - 47, // 11: controlplane.v1.WorkflowRunEvent.created_at:type_name -> google.protobuf.Timestamp + 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 - 35, // 15: controlplane.v1.WorkflowRunEvent.attestation:type_name -> controlplane.v1.WorkflowRunEvent.AttestationAttributes - 37, // 16: controlplane.v1.WorkflowRunEvent.material:type_name -> controlplane.v1.WorkflowRunEvent.MaterialAttributes - 48, // 17: controlplane.v1.WorkflowRunServiceListRequest.status:type_name -> controlplane.v1.RunStatus - 49, // 18: controlplane.v1.WorkflowRunServiceListRequest.policy_violations:type_name -> controlplane.v1.PolicyViolationsFilter - 50, // 19: controlplane.v1.WorkflowRunServiceListRequest.policy_status:type_name -> controlplane.v1.PolicyStatusFilter - 51, // 20: controlplane.v1.WorkflowRunServiceListRequest.policy_gates:type_name -> controlplane.v1.PolicyGatesFilter - 52, // 21: controlplane.v1.WorkflowRunServiceListRequest.pagination:type_name -> controlplane.v1.CursorPaginationRequest - 53, // 22: controlplane.v1.WorkflowRunServiceListResponse.result:type_name -> controlplane.v1.WorkflowRunItem - 54, // 23: controlplane.v1.WorkflowRunServiceListResponse.pagination:type_name -> controlplane.v1.CursorPaginationResponse - 39, // 24: controlplane.v1.WorkflowRunProgress.materials:type_name -> controlplane.v1.WorkflowRunProgress.Material - 38, // 25: controlplane.v1.WorkflowRunProgress.attestation_policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts - 40, // 26: controlplane.v1.WorkflowRunServiceViewResponse.result:type_name -> controlplane.v1.WorkflowRunServiceViewResponse.Result - 42, // 27: controlplane.v1.AttestationServiceGetUploadCredsResponse.result:type_name -> controlplane.v1.AttestationServiceGetUploadCredsResponse.Result - 43, // 28: controlplane.v1.AttestationServiceGetContractResponse.Result.workflow:type_name -> controlplane.v1.WorkflowItem - 55, // 29: controlplane.v1.AttestationServiceGetContractResponse.Result.contract:type_name -> controlplane.v1.WorkflowContractVersionItem - 53, // 30: controlplane.v1.AttestationServiceInitResponse.Result.workflow_run:type_name -> controlplane.v1.WorkflowRunItem - 33, // 31: controlplane.v1.AttestationServiceInitResponse.Result.signing_options:type_name -> controlplane.v1.AttestationServiceInitResponse.SigningOptions - 38, // 32: controlplane.v1.WorkflowRunEvent.AttestationAttributes.policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts - 36, // 33: controlplane.v1.WorkflowRunEvent.AttestationAttributes.expected_materials:type_name -> controlplane.v1.WorkflowRunEvent.ExpectedMaterial - 38, // 34: controlplane.v1.WorkflowRunEvent.MaterialAttributes.policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts - 4, // 35: controlplane.v1.WorkflowRunProgress.Material.requirement:type_name -> controlplane.v1.WorkflowRunProgress.Requirement - 5, // 36: controlplane.v1.WorkflowRunProgress.Material.status:type_name -> controlplane.v1.WorkflowRunProgress.Status - 38, // 37: controlplane.v1.WorkflowRunProgress.Material.policies:type_name -> controlplane.v1.WorkflowRunEvent.PolicyCounts - 53, // 38: controlplane.v1.WorkflowRunServiceViewResponse.Result.workflow_run:type_name -> controlplane.v1.WorkflowRunItem - 56, // 39: controlplane.v1.WorkflowRunServiceViewResponse.Result.attestation:type_name -> controlplane.v1.AttestationItem - 41, // 40: controlplane.v1.WorkflowRunServiceViewResponse.Result.verification:type_name -> controlplane.v1.WorkflowRunServiceViewResponse.VerificationResult - 27, // 41: controlplane.v1.WorkflowRunServiceViewResponse.Result.progress:type_name -> controlplane.v1.WorkflowRunProgress - 23, // 42: controlplane.v1.WorkflowRunServiceViewResponse.Result.events:type_name -> controlplane.v1.WorkflowRunEvent - 57, // 43: controlplane.v1.AttestationServiceGetUploadCredsResponse.Result.backend:type_name -> controlplane.v1.CASBackendItem + 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 - 29, // 48: controlplane.v1.AttestationService.GetUploadCreds:input_type -> controlplane.v1.AttestationServiceGetUploadCredsRequest + 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 - 7, // 55: controlplane.v1.AttestationService.FindOrCreateWorkflow:output_type -> controlplane.v1.FindOrCreateWorkflowResponse - 14, // 56: controlplane.v1.AttestationService.GetContract:output_type -> controlplane.v1.AttestationServiceGetContractResponse - 16, // 57: controlplane.v1.AttestationService.Init:output_type -> controlplane.v1.AttestationServiceInitResponse - 18, // 58: controlplane.v1.AttestationService.Store:output_type -> controlplane.v1.AttestationServiceStoreResponse - 30, // 59: controlplane.v1.AttestationService.GetUploadCreds:output_type -> controlplane.v1.AttestationServiceGetUploadCredsResponse - 20, // 60: controlplane.v1.AttestationService.Cancel:output_type -> controlplane.v1.AttestationServiceCancelResponse - 22, // 61: controlplane.v1.AttestationService.RecordEvent:output_type -> controlplane.v1.AttestationServiceRecordEventResponse - 9, // 62: controlplane.v1.AttestationService.GetPolicy:output_type -> controlplane.v1.AttestationServiceGetPolicyResponse - 12, // 63: controlplane.v1.AttestationService.GetPolicyGroup:output_type -> controlplane.v1.AttestationServiceGetPolicyGroupResponse - 25, // 64: controlplane.v1.WorkflowRunService.List:output_type -> controlplane.v1.WorkflowRunServiceListResponse - 28, // 65: controlplane.v1.WorkflowRunService.View:output_type -> controlplane.v1.WorkflowRunServiceViewResponse - 55, // [55:66] is the sub-list for method output_type - 44, // [44:55] is the sub-list for method input_type + 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 @@ -3250,7 +3338,7 @@ func file_controlplane_v1_workflow_run_proto_init() { 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: 6, - NumMessages: 37, + 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 89afdfac8..53f7c5ef4 100644 --- a/app/controlplane/api/controlplane/v1/workflow_run.proto +++ b/app/controlplane/api/controlplane/v1/workflow_run.proto @@ -46,9 +46,9 @@ service AttestationService { // Administrative service for the operator service WorkflowRunService { rpc List(WorkflowRunServiceListRequest) returns (WorkflowRunServiceListResponse); - // View returns the run, its attestation, its timeline of events, and, while the run - // is in progress, its progress 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 { @@ -390,6 +390,18 @@ 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 @@ -443,11 +455,6 @@ message WorkflowRunServiceViewResponse { AttestationItem attestation = 2; // It will be nil if the verification is not possible (old or non-keyless attestations) VerificationResult verification = 3; - // 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 = 6; - // Timeline of the run, oldest first. Reported data, never part of the attestation. - repeated WorkflowRunEvent events = 7; } message VerificationResult { 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 d7b582cfa..b31ecc9d0 100644 --- a/app/controlplane/api/controlplane/v1/workflow_run_grpc.pb.go +++ b/app/controlplane/api/controlplane/v1/workflow_run_grpc.pb.go @@ -428,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. @@ -437,9 +438,9 @@ const ( // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. type WorkflowRunServiceClient interface { List(ctx context.Context, in *WorkflowRunServiceListRequest, opts ...grpc.CallOption) (*WorkflowRunServiceListResponse, error) - // View returns the run, its attestation, its timeline of events, and, while the run - // is in progress, its progress 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 { @@ -468,14 +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 returns the run, its attestation, its timeline of events, and, while the run - // is in progress, its progress 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() } @@ -489,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. @@ -538,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) @@ -553,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/gen/frontend/controlplane/v1/workflow_run.ts b/app/controlplane/api/gen/frontend/controlplane/v1/workflow_run.ts index ede4d3371..eb10c4afc 100644 --- a/app/controlplane/api/gen/frontend/controlplane/v1/workflow_run.ts +++ b/app/controlplane/api/gen/frontend/controlplane/v1/workflow_run.ts @@ -480,6 +480,20 @@ 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 */ @@ -615,13 +629,6 @@ export interface WorkflowRunServiceViewResponse_Result { attestation?: AttestationItem; /** It will be nil if the verification is not possible (old or non-keyless attestations) */ verification?: WorkflowRunServiceViewResponse_VerificationResult; - /** - * 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[]; } export interface WorkflowRunServiceViewResponse_VerificationResult { @@ -3490,6 +3497,148 @@ export const WorkflowRunServiceViewRequest = { }, }; +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 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(); + } + for (const v of message.events) { + WorkflowRunEvent.encode(v!, writer.uint32(18).fork()).ldelim(); + } + return writer; + }, + + 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 = createBaseWorkflowRunServiceGetProgressResponse(); + while (reader.pos < end) { + const tag = reader.uint32(); + switch (tag >>> 3) { + case 1: + if (tag !== 10) { + break; + } + + message.progress = WorkflowRunProgress.decode(reader, reader.uint32()); + continue; + case 2: + if (tag !== 18) { + break; + } + + message.events.push(WorkflowRunEvent.decode(reader, reader.uint32())); + continue; + } + if ((tag & 7) === 4 || tag === 0) { + break; + } + reader.skipType(tag & 7); + } + return message; + }, + + fromJSON(object: any): WorkflowRunServiceGetProgressResponse { + return { + progress: isSet(object.progress) ? WorkflowRunProgress.fromJSON(object.progress) : undefined, + events: Array.isArray(object?.events) ? object.events.map((e: any) => WorkflowRunEvent.fromJSON(e)) : [], + }; + }, + + toJSON(message: WorkflowRunServiceGetProgressResponse): unknown { + const obj: any = {}; + 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.events = []; + } + return obj; + }, + + create, I>>( + base?: I, + ): WorkflowRunServiceGetProgressResponse { + return WorkflowRunServiceGetProgressResponse.fromPartial(base ?? {}); + }, + + fromPartial, I>>( + object: I, + ): 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 createBaseWorkflowRunProgress(): WorkflowRunProgress { return { materials: [], requiredTotal: 0, requiredProvided: 0, attestationPolicies: undefined }; } @@ -3836,14 +3985,7 @@ export const WorkflowRunServiceViewResponse = { }; function createBaseWorkflowRunServiceViewResponse_Result(): WorkflowRunServiceViewResponse_Result { - return { - orgName: "", - workflowRun: undefined, - attestation: undefined, - verification: undefined, - progress: undefined, - events: [], - }; + return { orgName: "", workflowRun: undefined, attestation: undefined, verification: undefined }; } export const WorkflowRunServiceViewResponse_Result = { @@ -3860,12 +4002,6 @@ export const WorkflowRunServiceViewResponse_Result = { if (message.verification !== undefined) { WorkflowRunServiceViewResponse_VerificationResult.encode(message.verification, writer.uint32(26).fork()).ldelim(); } - if (message.progress !== undefined) { - WorkflowRunProgress.encode(message.progress, writer.uint32(50).fork()).ldelim(); - } - for (const v of message.events) { - WorkflowRunEvent.encode(v!, writer.uint32(58).fork()).ldelim(); - } return writer; }, @@ -3904,20 +4040,6 @@ export const WorkflowRunServiceViewResponse_Result = { message.verification = WorkflowRunServiceViewResponse_VerificationResult.decode(reader, reader.uint32()); continue; - case 6: - if (tag !== 50) { - break; - } - - message.progress = WorkflowRunProgress.decode(reader, reader.uint32()); - continue; - case 7: - if (tag !== 58) { - break; - } - - message.events.push(WorkflowRunEvent.decode(reader, reader.uint32())); - continue; } if ((tag & 7) === 4 || tag === 0) { break; @@ -3935,8 +4057,6 @@ export const WorkflowRunServiceViewResponse_Result = { verification: isSet(object.verification) ? WorkflowRunServiceViewResponse_VerificationResult.fromJSON(object.verification) : undefined, - progress: isSet(object.progress) ? WorkflowRunProgress.fromJSON(object.progress) : undefined, - events: Array.isArray(object?.events) ? object.events.map((e: any) => WorkflowRunEvent.fromJSON(e)) : [], }; }, @@ -3950,13 +4070,6 @@ export const WorkflowRunServiceViewResponse_Result = { message.verification !== undefined && (obj.verification = message.verification ? WorkflowRunServiceViewResponse_VerificationResult.toJSON(message.verification) : 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.events = []; - } return obj; }, @@ -3980,10 +4093,6 @@ export const WorkflowRunServiceViewResponse_Result = { message.verification = (object.verification !== undefined && object.verification !== null) ? WorkflowRunServiceViewResponse_VerificationResult.fromPartial(object.verification) : undefined; - message.progress = (object.progress !== undefined && object.progress !== null) - ? WorkflowRunProgress.fromPartial(object.progress) - : undefined; - message.events = object.events?.map((e) => WorkflowRunEvent.fromPartial(e)) || []; return message; }, }; @@ -4641,14 +4750,15 @@ export interface WorkflowRunService { request: DeepPartial, metadata?: grpc.Metadata, ): Promise; - /** - * View returns the run, its attestation, its timeline of events, and, while the run - * is in progress, its progress - */ View( 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 { @@ -4658,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( @@ -4673,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" }; @@ -4723,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; 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/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceViewResponse.Result.jsonschema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceViewResponse.Result.jsonschema.json index e844089f0..826ee43ca 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceViewResponse.Result.jsonschema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceViewResponse.Result.jsonschema.json @@ -14,20 +14,9 @@ "attestation": { "$ref": "controlplane.v1.AttestationItem.jsonschema.json" }, - "events": { - "description": "Timeline of the run, oldest first. Reported data, never part of the attestation.", - "items": { - "$ref": "controlplane.v1.WorkflowRunEvent.jsonschema.json" - }, - "type": "array" - }, "orgName": { "type": "string" }, - "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." - }, "verification": { "$ref": "controlplane.v1.WorkflowRunServiceViewResponse.VerificationResult.jsonschema.json", "description": "It will be nil if the verification is not possible (old or non-keyless attestations)" diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceViewResponse.Result.schema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceViewResponse.Result.schema.json index f39b88a4c..19169799e 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceViewResponse.Result.schema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowRunServiceViewResponse.Result.schema.json @@ -14,20 +14,9 @@ "attestation": { "$ref": "controlplane.v1.AttestationItem.schema.json" }, - "events": { - "description": "Timeline of the run, oldest first. Reported data, never part of the attestation.", - "items": { - "$ref": "controlplane.v1.WorkflowRunEvent.schema.json" - }, - "type": "array" - }, "org_name": { "type": "string" }, - "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." - }, "verification": { "$ref": "controlplane.v1.WorkflowRunServiceViewResponse.VerificationResult.schema.json", "description": "It will be nil if the verification is not possible (old or non-keyless attestations)" diff --git a/app/controlplane/internal/service/workflowrun.go b/app/controlplane/internal/service/workflowrun.go index 685cda79f..542b778e6 100644 --- a/app/controlplane/internal/service/workflowrun.go +++ b/app/controlplane/internal/service/workflowrun.go @@ -429,22 +429,6 @@ func (s *WorkflowRunService) View(ctx context.Context, req *pb.WorkflowRunServic Verification: verificationResult, } - // The timeline is reported data. A failure to read it does not fail the view. - events, err := s.runEventUseCase.List(ctx, run.ID.String()) - if err != nil { - s.log.Warnw("msg", "failed to list the events of the run", "run", run.ID.String(), "error", err) - } else { - res.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) { - res.Progress = bizWorkflowRunProgressToPb(biz.BuildWorkflowRunProgress(contractAndVersion.Version.Schema, events)) - } - } - return &pb.WorkflowRunServiceViewResponse{Result: res}, nil } @@ -603,6 +587,48 @@ func pbPolicyStatusFilterToBiz(f pb.PolicyStatusFilter) chainloop.PolicyStatus { } // validateAndGetProjectID finds a project by name and verifies it's in the visible projects list +// 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 +} + 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}) if err != nil { diff --git a/app/controlplane/internal/service/workflowrunevent_integration_test.go b/app/controlplane/internal/service/workflowrunevent_integration_test.go index e150eb502..fad838121 100644 --- a/app/controlplane/internal/service/workflowrunevent_integration_test.go +++ b/app/controlplane/internal/service/workflowrunevent_integration_test.go @@ -34,8 +34,8 @@ import ( "github.com/stretchr/testify/suite" ) -// RecordEvent copies the checks of Store, and View returns the events with its own checks. No -// new policy is involved, so every caller keeps the access it has to the run itself. +// 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 @@ -273,23 +273,26 @@ func (s *workflowRunEventRBACIntegrationSuite) TestCallerTable() { 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) TestRecordAndView() { +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.WorkflowRunServiceViewResponse_Result { - resp, err := s.runSvc.View(s.apiCtxForToken(s.org, s.orgToken), &pb.WorkflowRunServiceViewRequest{Ref: &pb.WorkflowRunServiceViewRequest_Id{Id: runID}}) + 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.GetResult() + return resp } res := view() 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/docs/plans/issue-3825-attestation-progress-events.md b/docs/plans/issue-3825-attestation-progress-events.md index 2a811d992..4065b6f82 100644 --- a/docs/plans/issue-3825-attestation-progress-events.md +++ b/docs/plans/issue-3825-attestation-progress-events.md @@ -29,7 +29,7 @@ While an attestation is in progress, `chainloop workflow run describe` shows onl ### 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. The run view of the workflow run API 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 run view keeps its access rules. +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: View with events and progress"]:::changed + svcR["workflow run API: GetProgress"]:::new biz["run events use case"]:::new fin["store, cancel, expire"]:::changed exp["run expiry job"]:::changed @@ -71,7 +71,7 @@ flowchart LR 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. `describe` gets it, and the progress that the control plane builds from it, through the run view. +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,7 +96,7 @@ 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 run view 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/` | +| 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. 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/` | @@ -117,6 +117,8 @@ R-005, R-008, R-011 (M1) and R-009 (M2). `app/controlplane/api/controlplane/v1/w service WorkflowRunService { 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 AttestationServiceRecordEventRequest { @@ -126,14 +128,14 @@ R-005, R-008, R-011 (M1) and R-009 (M2). `app/controlplane/api/controlplane/v1/w +} +message AttestationServiceRecordEventResponse {} + -+message WorkflowRunServiceViewResponse { -+ message Result { -+ // ... existing fields -+ // Progress of a run in progress, built by the control plane. Not set for a finished run. -+ WorkflowRunProgress progress = 6; -+ // Timeline of the run, oldest first -+ repeated WorkflowRunEvent events = 7; -+ } ++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. 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) @@ -181,7 +183,7 @@ $ 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 the `progress` object of the run view. 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. +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... @@ -231,7 +233,7 @@ R-007. `deployment/chainloop/values.yaml`, rendered into the control plane confi ### M1: Automatic progress -The control plane gets the event table, the write call, the closing events, and the deletion of old events. Its run view 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`, the run view returns the events and the progress, 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`, the run view returns the events and the progress, 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. @@ -245,12 +247,13 @@ Add the calls and messages of the API snippet, without the custom type, and with | 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` | -| `View` (events and progress) | no change: its 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/GetProgress` to `PolicyWorkflowRunRead`. | | `app/controlplane/pkg/authz/authz_consistency_test.go` | Add `RecordEvent` to the exempt list next to `Store` and `Cancel`. |
@@ -294,11 +297,11 @@ Wrap the status update and the insert of the closing `chainloop.attestation` eve
-04 / 07 · Serve the write call with the checks of Store, and the events and progress in View (R-011) +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 and MATERIAL, with a key that starts with `chainloop.`, and an attributes field that matches the type. `View` 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. A failure to read the events does not fail `View`. `View` then returns no events and no progress, because a progress with no events would show all the materials as missing. +`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` | `View` | +| Caller | `RecordEvent` | `GetProgress` | |--------|---------------|--------| | Any caller that `Store` accepts for the run | allowed | allowed | | Token pinned to another workflow | denied | allowed, as `View` allows the project of the token | @@ -310,9 +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 the events and the progress to `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 that `View` returns the events and the progress of a run in progress. | +| `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. |
@@ -356,16 +359,16 @@ Add a recorder to the CLI actions: `Record(ctx, event) error` sends with a 2-sec
07 / 07 · Show the progress in workflow run describe (R-004, R-011) -`describe` shows the events and the progress that `View` 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. An older control plane returns no events and no progress, and `describe` shows the run as before. +`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` | Map the events and the progress of the `View` response. | +| `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, an older control plane with no events. | -| `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`, `View` returns no events, and the `add` and `describe` callers succeed. | +| `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. |
@@ -408,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 run view, with up to 1,000 events and the progress, 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 d1ea21e5a..49a09ab86 100644 --- a/docs/specs/issue-3825-attestation-progress-events.md +++ b/docs/specs/issue-3825-attestation-progress-events.md @@ -108,7 +108,7 @@ Supersedes R-001. The CLI MUST record a run event at each action of the attestat - 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. The run view of the control plane MUST return the events of the run, oldest first, with the permissions of the run view. For a run in progress, it 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. +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 @@ -133,11 +133,11 @@ Supersedes R-003. The run view of the control plane MUST return the events of th 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.~~ `chainloop workflow run describe` shows the progress and the events that the run view returns (D-012). +**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).~~ It builds the progress of a run in progress and returns it with the events in the run view (R-011, 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).~~ 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.~~ It polls the run view while the run is in progress (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. ```mermaid sequenceDiagram @@ -157,7 +157,7 @@ sequenceDiagram CP-->>U: signed attestation + timeline as history ``` -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, "view run + list events" is one call, the run view, which also returns the progress. +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 @@ -244,12 +244,12 @@ The CLI records no `chainloop.push` event. The closing event of the store (R-006 - 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: The run view returns the progress and the events -Supersedes D-007. The run view call returns the events and, for a run in progress, the progress (R-011). The control plane builds the progress. There is no separate read call for events. -- Why: a run in progress has no attestation yet, so its run view is small, and a client can poll it. After the store, the run is finished and no client polls it. One call gives the UI and other tools all the data to show, with no join of the contract and the events in each client. The control plane builds the progress once, so all clients show the same result. +### 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 separate read call for events, 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. - - A separate read call that also returns the progress: two calls for one page, and two sets of the same checks. + - 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 From 7cb98bff694046b1b1795b926f0bd4a5c30c1ad1 Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Tue, 1 Dec 2026 12:40:00 +0100 Subject: [PATCH 20/20] docs: fix a doc comment and a stale plan line after GetProgress Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: 1cdb3220-119c-4a14-ac50-52d5437ee4eb --- app/controlplane/internal/service/workflowrun.go | 2 +- docs/plans/issue-3825-attestation-progress-events.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/controlplane/internal/service/workflowrun.go b/app/controlplane/internal/service/workflowrun.go index 542b778e6..17923e26a 100644 --- a/app/controlplane/internal/service/workflowrun.go +++ b/app/controlplane/internal/service/workflowrun.go @@ -586,7 +586,6 @@ func pbPolicyStatusFilterToBiz(f pb.PolicyStatusFilter) chainloop.PolicyStatus { } } -// validateAndGetProjectID finds a project by name and verifies it's in the visible projects list // 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) { @@ -629,6 +628,7 @@ func (s *WorkflowRunService) GetProgress(ctx context.Context, req *pb.WorkflowRu 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}) if err != nil { diff --git a/docs/plans/issue-3825-attestation-progress-events.md b/docs/plans/issue-3825-attestation-progress-events.md index 4065b6f82..9f5df0d47 100644 --- a/docs/plans/issue-3825-attestation-progress-events.md +++ b/docs/plans/issue-3825-attestation-progress-events.md @@ -233,7 +233,7 @@ R-007. `deployment/chainloop/values.yaml`, rendered into the control plane confi ### M1: Automatic progress -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`, the run view returns the events and the progress, 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.