From 5a471e939d9ba5a8be7e64a610e968aef1f2474e Mon Sep 17 00:00:00 2001 From: Jose Ignacio Paris Prieto Date: Fri, 6 Nov 2026 12:58:39 +0100 Subject: [PATCH 1/3] feat(contracts): convert a contract between organization and project level Adds an optional level to the contract update API and the --project and --org flags to 'chainloop workflow contract update', so organization admins can move a contract between the organization and a project while it keeps its revisions and workflows. Workflow updates now reject a contract of a different project, and conversions and workflow changes lock the contract. Implements spec issue-3644 (R-001 to R-010, D-008). Closes #3644 Assisted-by: Claude Code Signed-off-by: Jose Ignacio Paris Prieto Chainloop-Trace-Sessions: bc6fbb4d-3bf8-4fd0-b81e-10aa03bf1e58 --- app/cli/cmd/workflow_contract_update.go | 21 ++- app/cli/documentation/cli-reference.md | 24 ++- .../pkg/action/workflow_contract_update.go | 31 +++- .../action/workflow_contract_update_test.go | 74 ++++++++ .../controlplane/v1/workflow_contract.pb.go | 120 +++++++++---- .../controlplane/v1/workflow_contract.proto | 9 + .../controlplane/v1/workflow_contract.ts | 51 +++++- ...ntractServiceUpdateRequest.jsonschema.json | 22 +++ ...owContractServiceUpdateRequest.schema.json | 22 +++ .../internal/service/workflowcontract.go | 38 +++- .../workflowcontract_integration_test.go | 91 ++++++++-- ...ontract_scope_changed_to_organization.json | 24 +++ ..._changed_to_organization_by_api_token.json | 24 +++ ...low_contract_scope_changed_to_project.json | 24 +++ ...scope_changed_to_project_by_api_token.json | 24 +++ .../pkg/auditor/events/workflowcontract.go | 49 +++++- .../auditor/events/workflowcontract_test.go | 35 +++- .../pkg/biz/workflow_integration_test.go | 72 ++++++++ app/controlplane/pkg/biz/workflowcontract.go | 45 ++++- .../pkg/biz/workflowcontract_audit_test.go | 136 +++++++++++++++ .../biz/workflowcontract_integration_test.go | 165 +++++++++++++++++- app/controlplane/pkg/data/workflow.go | 95 ++++++---- app/controlplane/pkg/data/workflowcontract.go | 76 +++++++- 23 files changed, 1187 insertions(+), 85 deletions(-) create mode 100644 app/cli/pkg/action/workflow_contract_update_test.go create mode 100644 app/controlplane/pkg/auditor/events/testdata/workflowcontracts/workflow_contract_scope_changed_to_organization.json create mode 100644 app/controlplane/pkg/auditor/events/testdata/workflowcontracts/workflow_contract_scope_changed_to_organization_by_api_token.json create mode 100644 app/controlplane/pkg/auditor/events/testdata/workflowcontracts/workflow_contract_scope_changed_to_project.json create mode 100644 app/controlplane/pkg/auditor/events/testdata/workflowcontracts/workflow_contract_scope_changed_to_project_by_api_token.json create mode 100644 app/controlplane/pkg/biz/workflowcontract_audit_test.go diff --git a/app/cli/cmd/workflow_contract_update.go b/app/cli/cmd/workflow_contract_update.go index 8666fb875..d4785b326 100644 --- a/app/cli/cmd/workflow_contract_update.go +++ b/app/cli/cmd/workflow_contract_update.go @@ -1,5 +1,5 @@ // -// Copyright 2024-2025 The Chainloop Authors. +// Copyright 2024-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. @@ -24,10 +24,24 @@ import ( func newWorkflowContractUpdateCmd() *cobra.Command { var name, description, contractPath string var contractName string + var scope action.WorkflowContractUpdateScope cmd := &cobra.Command{ Use: "update", Short: "Update an existing contract", + Long: `Update an existing contract. + +Use --project to move an organization-level contract to a project, or --org to move a +project-level contract to the organization. Only organization administrators and +organization-level API tokens can move a contract.`, + Example: ` # Update the contract content + chainloop workflow contract update --name my-contract --contract contract.yaml + + # Move an organization-level contract to a project + chainloop workflow contract update --name my-contract --project my-project + + # Move a project-level contract to the organization + chainloop workflow contract update --name my-contract --org`, PreRunE: func(_ *cobra.Command, _ []string) error { // Validate and extract the contract name var err error @@ -44,7 +58,7 @@ func newWorkflowContractUpdateCmd() *cobra.Command { desc = &description } - res, err := action.NewWorkflowContractUpdate(ActionOpts).Run(contractName, desc, contractPath) + res, err := action.NewWorkflowContractUpdate(ActionOpts).Run(contractName, desc, contractPath, scope) if err != nil { return err } @@ -57,6 +71,9 @@ func newWorkflowContractUpdateCmd() *cobra.Command { cmd.Flags().StringVar(&name, "name", "", "contract name") cmd.Flags().StringVarP(&contractPath, "contract", "f", "", "path or URL to the contract schema") cmd.Flags().StringVar(&description, "description", "", "description of the contract") + cmd.Flags().StringVar(&scope.ProjectName, "project", "", "move the contract to this project, the contract must be at the organization level") + cmd.Flags().BoolVar(&scope.Organization, "org", false, "move the contract to the organization level") + cmd.MarkFlagsMutuallyExclusive("project", "org") return cmd } diff --git a/app/cli/documentation/cli-reference.md b/app/cli/documentation/cli-reference.md index 598681229..a5f18d0dc 100644 --- a/app/cli/documentation/cli-reference.md +++ b/app/cli/documentation/cli-reference.md @@ -3744,10 +3744,31 @@ Options inherited from parent commands Update an existing contract +Synopsis + +Update an existing contract. + +Use --project to move an organization-level contract to a project, or --org to move a +project-level contract to the organization. Only organization administrators and +organization-level API tokens can move a contract. + ``` chainloop workflow contract update [flags] ``` +Examples + +``` +Update the contract content +chainloop workflow contract update --name my-contract --contract contract.yaml + +Move an organization-level contract to a project +chainloop workflow contract update --name my-contract --project my-project + +Move a project-level contract to the organization +chainloop workflow contract update --name my-contract --org +``` + Options ``` @@ -3755,6 +3776,8 @@ Options --description string description of the contract -h, --help help for update --name string contract name +--org move the contract to the organization level +--project string move the contract to this project, the contract must be at the organization level ``` Options inherited from parent commands @@ -3768,7 +3791,6 @@ Options inherited from parent commands --debug Enable debug/verbose logging mode -i, --insecure Skip TLS transport during connection to the control plane ($CHAINLOOP_API_INSECURE) --max-recv-msg-size int Max size in bytes for incoming gRPC messages (0 = default 33554432) ($CHAINLOOP_API_MAX_RECV_MSG_SIZE) --n, --org string organization name -o, --output string Output format, valid options are json and table (default "table") -t, --token string API token. NOTE: Alternatively use the env variable CHAINLOOP_TOKEN -y, --yes Skip confirmation diff --git a/app/cli/pkg/action/workflow_contract_update.go b/app/cli/pkg/action/workflow_contract_update.go index da6c73570..490712d47 100644 --- a/app/cli/pkg/action/workflow_contract_update.go +++ b/app/cli/pkg/action/workflow_contract_update.go @@ -1,5 +1,5 @@ // -// Copyright 2024 The Chainloop Authors. +// Copyright 2024-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. @@ -17,6 +17,7 @@ package action import ( "context" + "errors" pb "github.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1" ) @@ -29,10 +30,36 @@ func NewWorkflowContractUpdate(cfg *ActionsOpts) *WorkflowContractUpdate { return &WorkflowContractUpdate{cfg} } -func (action *WorkflowContractUpdate) Run(name string, description *string, contractPath string) (*WorkflowContractWithVersionItem, error) { +// WorkflowContractUpdateScope is the level that an update converts the contract to. +// The zero value keeps the level of the contract. +type WorkflowContractUpdateScope struct { + // ProjectName converts the contract to a project-level contract of this project + ProjectName string + // Organization converts the contract to an organization-level contract + Organization bool +} + +// apply sets the level of the update request +func (s WorkflowContractUpdateScope) apply(req *pb.WorkflowContractServiceUpdateRequest) error { + switch { + case s.ProjectName != "" && s.Organization: + return errors.New("only one of a project or the organization can be set") + case s.ProjectName != "": + req.Scope = &pb.WorkflowContractServiceUpdateRequest_ProjectReference{ProjectReference: &pb.IdentityReference{Name: &s.ProjectName}} + case s.Organization: + req.Scope = &pb.WorkflowContractServiceUpdateRequest_OrganizationScoped{OrganizationScoped: true} + } + + return nil +} + +func (action *WorkflowContractUpdate) Run(name string, description *string, contractPath string, scope WorkflowContractUpdateScope) (*WorkflowContractWithVersionItem, error) { client := pb.NewWorkflowContractServiceClient(action.cfg.CPConnection) request := &pb.WorkflowContractServiceUpdateRequest{Name: name, Description: description} + if err := scope.apply(request); err != nil { + return nil, err + } if contractPath != "" { rawContract, err := LoadFileOrURL(contractPath) if err != nil { diff --git a/app/cli/pkg/action/workflow_contract_update_test.go b/app/cli/pkg/action/workflow_contract_update_test.go new file mode 100644 index 000000000..75789820a --- /dev/null +++ b/app/cli/pkg/action/workflow_contract_update_test.go @@ -0,0 +1,74 @@ +// +// 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 ( + "testing" + + pb "github.com/chainloop-dev/chainloop/app/controlplane/api/controlplane/v1" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" +) + +func TestWorkflowContractUpdateScopeApply(t *testing.T) { + projectName := "contract-project" + + testCases := []struct { + name string + scope WorkflowContractUpdateScope + want *pb.WorkflowContractServiceUpdateRequest + wantErr string + }{ + { + name: "no scope keeps the level", + want: &pb.WorkflowContractServiceUpdateRequest{}, + }, + { + name: "to a project", + scope: WorkflowContractUpdateScope{ProjectName: projectName}, + want: &pb.WorkflowContractServiceUpdateRequest{ + Scope: &pb.WorkflowContractServiceUpdateRequest_ProjectReference{ProjectReference: &pb.IdentityReference{Name: &projectName}}, + }, + }, + { + name: "to the organization", + scope: WorkflowContractUpdateScope{Organization: true}, + want: &pb.WorkflowContractServiceUpdateRequest{ + Scope: &pb.WorkflowContractServiceUpdateRequest_OrganizationScoped{OrganizationScoped: true}, + }, + }, + { + name: "both", + scope: WorkflowContractUpdateScope{ProjectName: projectName, Organization: true}, + wantErr: "only one", + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + req := &pb.WorkflowContractServiceUpdateRequest{} + err := tc.scope.apply(req) + if tc.wantErr != "" { + assert.ErrorContains(t, err, tc.wantErr) + return + } + + require.NoError(t, err) + assert.True(t, proto.Equal(tc.want, req), "got %v", req) + }) + } +} diff --git a/app/controlplane/api/controlplane/v1/workflow_contract.pb.go b/app/controlplane/api/controlplane/v1/workflow_contract.pb.go index 81dbf5878..e04a12de7 100644 --- a/app/controlplane/api/controlplane/v1/workflow_contract.pb.go +++ b/app/controlplane/api/controlplane/v1/workflow_contract.pb.go @@ -291,8 +291,16 @@ type WorkflowContractServiceUpdateRequest struct { state protoimpl.MessageState `protogen:"open.v1"` Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // Raw representation of the contract in json, yaml or cue - RawContract []byte `protobuf:"bytes,5,opt,name=raw_contract,json=rawContract,proto3" json:"raw_contract,omitempty"` - Description *string `protobuf:"bytes,4,opt,name=description,proto3,oneof" json:"description,omitempty"` + RawContract []byte `protobuf:"bytes,5,opt,name=raw_contract,json=rawContract,proto3" json:"raw_contract,omitempty"` + Description *string `protobuf:"bytes,4,opt,name=description,proto3,oneof" json:"description,omitempty"` + // Converts the contract to another level. When not set, the level does not change. + // Only organization admins and organization-level API tokens can convert a contract. + // + // Types that are valid to be assigned to Scope: + // + // *WorkflowContractServiceUpdateRequest_ProjectReference + // *WorkflowContractServiceUpdateRequest_OrganizationScoped + Scope isWorkflowContractServiceUpdateRequest_Scope `protobuf_oneof:"scope"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -348,6 +356,51 @@ func (x *WorkflowContractServiceUpdateRequest) GetDescription() string { return "" } +func (x *WorkflowContractServiceUpdateRequest) GetScope() isWorkflowContractServiceUpdateRequest_Scope { + if x != nil { + return x.Scope + } + return nil +} + +func (x *WorkflowContractServiceUpdateRequest) GetProjectReference() *IdentityReference { + if x != nil { + if x, ok := x.Scope.(*WorkflowContractServiceUpdateRequest_ProjectReference); ok { + return x.ProjectReference + } + } + return nil +} + +func (x *WorkflowContractServiceUpdateRequest) GetOrganizationScoped() bool { + if x != nil { + if x, ok := x.Scope.(*WorkflowContractServiceUpdateRequest_OrganizationScoped); ok { + return x.OrganizationScoped + } + } + return false +} + +type isWorkflowContractServiceUpdateRequest_Scope interface { + isWorkflowContractServiceUpdateRequest_Scope() +} + +type WorkflowContractServiceUpdateRequest_ProjectReference struct { + // Converts the contract to a project-level contract of this project + ProjectReference *IdentityReference `protobuf:"bytes,6,opt,name=project_reference,json=projectReference,proto3,oneof"` +} + +type WorkflowContractServiceUpdateRequest_OrganizationScoped struct { + // Converts the contract to an organization-level contract. It must be true. + OrganizationScoped bool `protobuf:"varint,7,opt,name=organization_scoped,json=organizationScoped,proto3,oneof"` +} + +func (*WorkflowContractServiceUpdateRequest_ProjectReference) isWorkflowContractServiceUpdateRequest_Scope() { +} + +func (*WorkflowContractServiceUpdateRequest_OrganizationScoped) isWorkflowContractServiceUpdateRequest_Scope() { +} + type WorkflowContractServiceUpdateResponse struct { state protoimpl.MessageState `protogen:"open.v1"` Result *WorkflowContractServiceUpdateResponse_Result `protobuf:"bytes,1,opt,name=result,proto3" json:"result,omitempty"` @@ -860,12 +913,15 @@ const file_controlplane_v1_workflow_contract_proto_rawDesc = "" + "\x11project_reference\x18\x05 \x01(\v2\".controlplane.v1.IdentityReferenceR\x10projectReferenceB\x0e\n" + "\f_description\"f\n" + "%WorkflowContractServiceCreateResponse\x12=\n" + - "\x06result\x18\x01 \x01(\v2%.controlplane.v1.WorkflowContractItemR\x06result\"\x9e\x02\n" + + "\x06result\x18\x01 \x01(\v2%.controlplane.v1.WorkflowContractItemR\x06result\"\xb6\x03\n" + "$WorkflowContractServiceUpdateRequest\x12\x9b\x01\n" + "\x04name\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\x04name\x12!\n" + "\fraw_contract\x18\x05 \x01(\fR\vrawContract\x12%\n" + - "\vdescription\x18\x04 \x01(\tH\x00R\vdescription\x88\x01\x01B\x0e\n" + + "\vdescription\x18\x04 \x01(\tH\x01R\vdescription\x88\x01\x01\x12Q\n" + + "\x11project_reference\x18\x06 \x01(\v2\".controlplane.v1.IdentityReferenceH\x00R\x10projectReference\x12:\n" + + "\x13organization_scoped\x18\a \x01(\bB\a\xbaH\x04j\x02\b\x01H\x00R\x12organizationScopedB\a\n" + + "\x05scopeB\x0e\n" + "\f_description\"\x96\x02\n" + "%WorkflowContractServiceUpdateResponse\x12U\n" + "\x06result\x18\x01 \x01(\v2=.controlplane.v1.WorkflowContractServiceUpdateResponse.ResultR\x06result\x1a\x95\x01\n" + @@ -949,31 +1005,32 @@ var file_controlplane_v1_workflow_contract_proto_depIdxs = []int32{ 15, // 0: controlplane.v1.WorkflowContractServiceListResponse.result:type_name -> controlplane.v1.WorkflowContractItem 16, // 1: controlplane.v1.WorkflowContractServiceCreateRequest.project_reference:type_name -> controlplane.v1.IdentityReference 15, // 2: controlplane.v1.WorkflowContractServiceCreateResponse.result:type_name -> controlplane.v1.WorkflowContractItem - 13, // 3: controlplane.v1.WorkflowContractServiceUpdateResponse.result:type_name -> controlplane.v1.WorkflowContractServiceUpdateResponse.Result - 14, // 4: controlplane.v1.WorkflowContractServiceDescribeResponse.result:type_name -> controlplane.v1.WorkflowContractServiceDescribeResponse.Result - 15, // 5: controlplane.v1.WorkflowContractServiceApplyResponse.result:type_name -> controlplane.v1.WorkflowContractItem - 0, // 6: controlplane.v1.WorkflowContractServiceApplyResponse.status:type_name -> controlplane.v1.WorkflowContractServiceApplyResponse.ApplyStatus - 15, // 7: controlplane.v1.WorkflowContractServiceUpdateResponse.Result.contract:type_name -> controlplane.v1.WorkflowContractItem - 17, // 8: controlplane.v1.WorkflowContractServiceUpdateResponse.Result.revision:type_name -> controlplane.v1.WorkflowContractVersionItem - 15, // 9: controlplane.v1.WorkflowContractServiceDescribeResponse.Result.contract:type_name -> controlplane.v1.WorkflowContractItem - 17, // 10: controlplane.v1.WorkflowContractServiceDescribeResponse.Result.revision:type_name -> controlplane.v1.WorkflowContractVersionItem - 1, // 11: controlplane.v1.WorkflowContractService.List:input_type -> controlplane.v1.WorkflowContractServiceListRequest - 3, // 12: controlplane.v1.WorkflowContractService.Create:input_type -> controlplane.v1.WorkflowContractServiceCreateRequest - 5, // 13: controlplane.v1.WorkflowContractService.Update:input_type -> controlplane.v1.WorkflowContractServiceUpdateRequest - 7, // 14: controlplane.v1.WorkflowContractService.Describe:input_type -> controlplane.v1.WorkflowContractServiceDescribeRequest - 9, // 15: controlplane.v1.WorkflowContractService.Delete:input_type -> controlplane.v1.WorkflowContractServiceDeleteRequest - 11, // 16: controlplane.v1.WorkflowContractService.Apply:input_type -> controlplane.v1.WorkflowContractServiceApplyRequest - 2, // 17: controlplane.v1.WorkflowContractService.List:output_type -> controlplane.v1.WorkflowContractServiceListResponse - 4, // 18: controlplane.v1.WorkflowContractService.Create:output_type -> controlplane.v1.WorkflowContractServiceCreateResponse - 6, // 19: controlplane.v1.WorkflowContractService.Update:output_type -> controlplane.v1.WorkflowContractServiceUpdateResponse - 8, // 20: controlplane.v1.WorkflowContractService.Describe:output_type -> controlplane.v1.WorkflowContractServiceDescribeResponse - 10, // 21: controlplane.v1.WorkflowContractService.Delete:output_type -> controlplane.v1.WorkflowContractServiceDeleteResponse - 12, // 22: controlplane.v1.WorkflowContractService.Apply:output_type -> controlplane.v1.WorkflowContractServiceApplyResponse - 17, // [17:23] is the sub-list for method output_type - 11, // [11:17] is the sub-list for method input_type - 11, // [11:11] is the sub-list for extension type_name - 11, // [11:11] is the sub-list for extension extendee - 0, // [0:11] is the sub-list for field type_name + 16, // 3: controlplane.v1.WorkflowContractServiceUpdateRequest.project_reference:type_name -> controlplane.v1.IdentityReference + 13, // 4: controlplane.v1.WorkflowContractServiceUpdateResponse.result:type_name -> controlplane.v1.WorkflowContractServiceUpdateResponse.Result + 14, // 5: controlplane.v1.WorkflowContractServiceDescribeResponse.result:type_name -> controlplane.v1.WorkflowContractServiceDescribeResponse.Result + 15, // 6: controlplane.v1.WorkflowContractServiceApplyResponse.result:type_name -> controlplane.v1.WorkflowContractItem + 0, // 7: controlplane.v1.WorkflowContractServiceApplyResponse.status:type_name -> controlplane.v1.WorkflowContractServiceApplyResponse.ApplyStatus + 15, // 8: controlplane.v1.WorkflowContractServiceUpdateResponse.Result.contract:type_name -> controlplane.v1.WorkflowContractItem + 17, // 9: controlplane.v1.WorkflowContractServiceUpdateResponse.Result.revision:type_name -> controlplane.v1.WorkflowContractVersionItem + 15, // 10: controlplane.v1.WorkflowContractServiceDescribeResponse.Result.contract:type_name -> controlplane.v1.WorkflowContractItem + 17, // 11: controlplane.v1.WorkflowContractServiceDescribeResponse.Result.revision:type_name -> controlplane.v1.WorkflowContractVersionItem + 1, // 12: controlplane.v1.WorkflowContractService.List:input_type -> controlplane.v1.WorkflowContractServiceListRequest + 3, // 13: controlplane.v1.WorkflowContractService.Create:input_type -> controlplane.v1.WorkflowContractServiceCreateRequest + 5, // 14: controlplane.v1.WorkflowContractService.Update:input_type -> controlplane.v1.WorkflowContractServiceUpdateRequest + 7, // 15: controlplane.v1.WorkflowContractService.Describe:input_type -> controlplane.v1.WorkflowContractServiceDescribeRequest + 9, // 16: controlplane.v1.WorkflowContractService.Delete:input_type -> controlplane.v1.WorkflowContractServiceDeleteRequest + 11, // 17: controlplane.v1.WorkflowContractService.Apply:input_type -> controlplane.v1.WorkflowContractServiceApplyRequest + 2, // 18: controlplane.v1.WorkflowContractService.List:output_type -> controlplane.v1.WorkflowContractServiceListResponse + 4, // 19: controlplane.v1.WorkflowContractService.Create:output_type -> controlplane.v1.WorkflowContractServiceCreateResponse + 6, // 20: controlplane.v1.WorkflowContractService.Update:output_type -> controlplane.v1.WorkflowContractServiceUpdateResponse + 8, // 21: controlplane.v1.WorkflowContractService.Describe:output_type -> controlplane.v1.WorkflowContractServiceDescribeResponse + 10, // 22: controlplane.v1.WorkflowContractService.Delete:output_type -> controlplane.v1.WorkflowContractServiceDeleteResponse + 12, // 23: controlplane.v1.WorkflowContractService.Apply:output_type -> controlplane.v1.WorkflowContractServiceApplyResponse + 18, // [18:24] is the sub-list for method output_type + 12, // [12:18] is the sub-list for method input_type + 12, // [12:12] is the sub-list for extension type_name + 12, // [12:12] is the sub-list for extension extendee + 0, // [0:12] is the sub-list for field type_name } func init() { file_controlplane_v1_workflow_contract_proto_init() } @@ -984,7 +1041,10 @@ func file_controlplane_v1_workflow_contract_proto_init() { file_controlplane_v1_response_messages_proto_init() file_controlplane_v1_shared_message_proto_init() file_controlplane_v1_workflow_contract_proto_msgTypes[2].OneofWrappers = []any{} - file_controlplane_v1_workflow_contract_proto_msgTypes[4].OneofWrappers = []any{} + file_controlplane_v1_workflow_contract_proto_msgTypes[4].OneofWrappers = []any{ + (*WorkflowContractServiceUpdateRequest_ProjectReference)(nil), + (*WorkflowContractServiceUpdateRequest_OrganizationScoped)(nil), + } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ diff --git a/app/controlplane/api/controlplane/v1/workflow_contract.proto b/app/controlplane/api/controlplane/v1/workflow_contract.proto index fe31f9508..1fc4f0c61 100644 --- a/app/controlplane/api/controlplane/v1/workflow_contract.proto +++ b/app/controlplane/api/controlplane/v1/workflow_contract.proto @@ -75,6 +75,15 @@ message WorkflowContractServiceUpdateRequest { bytes raw_contract = 5; optional string description = 4; + + // Converts the contract to another level. When not set, the level does not change. + // Only organization admins and organization-level API tokens can convert a contract. + oneof scope { + // Converts the contract to a project-level contract of this project + IdentityReference project_reference = 6; + // Converts the contract to an organization-level contract. It must be true. + bool organization_scoped = 7 [(buf.validate.field).bool.const = true]; + } } message WorkflowContractServiceUpdateResponse { diff --git a/app/controlplane/api/gen/frontend/controlplane/v1/workflow_contract.ts b/app/controlplane/api/gen/frontend/controlplane/v1/workflow_contract.ts index a55f52e89..1a65ad774 100644 --- a/app/controlplane/api/gen/frontend/controlplane/v1/workflow_contract.ts +++ b/app/controlplane/api/gen/frontend/controlplane/v1/workflow_contract.ts @@ -33,7 +33,15 @@ export interface WorkflowContractServiceUpdateRequest { name: string; /** Raw representation of the contract in json, yaml or cue */ rawContract: Uint8Array; - description?: string | undefined; + description?: + | string + | undefined; + /** Converts the contract to a project-level contract of this project */ + projectReference?: + | IdentityReference + | undefined; + /** Converts the contract to an organization-level contract. It must be true. */ + organizationScoped?: boolean | undefined; } export interface WorkflowContractServiceUpdateResponse { @@ -449,7 +457,13 @@ export const WorkflowContractServiceCreateResponse = { }; function createBaseWorkflowContractServiceUpdateRequest(): WorkflowContractServiceUpdateRequest { - return { name: "", rawContract: new Uint8Array(0), description: undefined }; + return { + name: "", + rawContract: new Uint8Array(0), + description: undefined, + projectReference: undefined, + organizationScoped: undefined, + }; } export const WorkflowContractServiceUpdateRequest = { @@ -463,6 +477,12 @@ export const WorkflowContractServiceUpdateRequest = { if (message.description !== undefined) { writer.uint32(34).string(message.description); } + if (message.projectReference !== undefined) { + IdentityReference.encode(message.projectReference, writer.uint32(50).fork()).ldelim(); + } + if (message.organizationScoped !== undefined) { + writer.uint32(56).bool(message.organizationScoped); + } return writer; }, @@ -494,6 +514,20 @@ export const WorkflowContractServiceUpdateRequest = { message.description = reader.string(); continue; + case 6: + if (tag !== 50) { + break; + } + + message.projectReference = IdentityReference.decode(reader, reader.uint32()); + continue; + case 7: + if (tag !== 56) { + break; + } + + message.organizationScoped = reader.bool(); + continue; } if ((tag & 7) === 4 || tag === 0) { break; @@ -508,6 +542,10 @@ export const WorkflowContractServiceUpdateRequest = { name: isSet(object.name) ? String(object.name) : "", rawContract: isSet(object.rawContract) ? bytesFromBase64(object.rawContract) : new Uint8Array(0), description: isSet(object.description) ? String(object.description) : undefined, + projectReference: isSet(object.projectReference) + ? IdentityReference.fromJSON(object.projectReference) + : undefined, + organizationScoped: isSet(object.organizationScoped) ? Boolean(object.organizationScoped) : undefined, }; }, @@ -517,6 +555,11 @@ export const WorkflowContractServiceUpdateRequest = { message.rawContract !== undefined && (obj.rawContract = base64FromBytes(message.rawContract !== undefined ? message.rawContract : new Uint8Array(0))); message.description !== undefined && (obj.description = message.description); + message.projectReference !== undefined && + (obj.projectReference = message.projectReference + ? IdentityReference.toJSON(message.projectReference) + : undefined); + message.organizationScoped !== undefined && (obj.organizationScoped = message.organizationScoped); return obj; }, @@ -533,6 +576,10 @@ export const WorkflowContractServiceUpdateRequest = { message.name = object.name ?? ""; message.rawContract = object.rawContract ?? new Uint8Array(0); message.description = object.description ?? undefined; + message.projectReference = (object.projectReference !== undefined && object.projectReference !== null) + ? IdentityReference.fromPartial(object.projectReference) + : undefined; + message.organizationScoped = object.organizationScoped ?? undefined; return message; }, }; diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowContractServiceUpdateRequest.jsonschema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowContractServiceUpdateRequest.jsonschema.json index 8b42ab0d9..933b1ef4c 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowContractServiceUpdateRequest.jsonschema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowContractServiceUpdateRequest.jsonschema.json @@ -3,6 +3,17 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, "patternProperties": { + "^(organization_scoped)$": { + "description": "Converts the contract to an organization-level contract. It must be true.", + "enum": [ + true + ], + "type": "boolean" + }, + "^(project_reference)$": { + "$ref": "controlplane.v1.IdentityReference.jsonschema.json", + "description": "Converts the contract to a project-level contract of this project" + }, "^(raw_contract)$": { "description": "Raw representation of the contract in json, yaml or cue", "pattern": "^[A-Za-z0-9+/]*={0,2}$", @@ -16,6 +27,17 @@ "name": { "type": "string" }, + "organizationScoped": { + "description": "Converts the contract to an organization-level contract. It must be true.", + "enum": [ + true + ], + "type": "boolean" + }, + "projectReference": { + "$ref": "controlplane.v1.IdentityReference.jsonschema.json", + "description": "Converts the contract to a project-level contract of this project" + }, "rawContract": { "description": "Raw representation of the contract in json, yaml or cue", "pattern": "^[A-Za-z0-9+/]*={0,2}$", diff --git a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowContractServiceUpdateRequest.schema.json b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowContractServiceUpdateRequest.schema.json index 49763fce6..46d3c5f09 100644 --- a/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowContractServiceUpdateRequest.schema.json +++ b/app/controlplane/api/gen/jsonschema/controlplane.v1.WorkflowContractServiceUpdateRequest.schema.json @@ -3,6 +3,17 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false, "patternProperties": { + "^(organizationScoped)$": { + "description": "Converts the contract to an organization-level contract. It must be true.", + "enum": [ + true + ], + "type": "boolean" + }, + "^(projectReference)$": { + "$ref": "controlplane.v1.IdentityReference.schema.json", + "description": "Converts the contract to a project-level contract of this project" + }, "^(rawContract)$": { "description": "Raw representation of the contract in json, yaml or cue", "pattern": "^[A-Za-z0-9+/]*={0,2}$", @@ -16,6 +27,17 @@ "name": { "type": "string" }, + "organization_scoped": { + "description": "Converts the contract to an organization-level contract. It must be true.", + "enum": [ + true + ], + "type": "boolean" + }, + "project_reference": { + "$ref": "controlplane.v1.IdentityReference.schema.json", + "description": "Converts the contract to a project-level contract of this project" + }, "raw_contract": { "description": "Raw representation of the contract in json, yaml or cue", "pattern": "^[A-Za-z0-9+/]*={0,2}$", diff --git a/app/controlplane/internal/service/workflowcontract.go b/app/controlplane/internal/service/workflowcontract.go index 2cdc52566..2313c392c 100644 --- a/app/controlplane/internal/service/workflowcontract.go +++ b/app/controlplane/internal/service/workflowcontract.go @@ -203,7 +203,18 @@ func (s *WorkflowContractService) Update(ctx context.Context, req *pb.WorkflowCo return nil, errors.NotFound("not found", "contract not found") } - if err := s.checkContractAccess(ctx, contract, authz.PolicyWorkflowContractUpdate, false); err != nil { + // A conversion to another level (spec issue-3644). Only the callers that manage + // organization-level contracts can convert, and this check replaces the normal access check. + var scope *biz.ContractScopeChange + if req.GetScope() != nil { + if !canConvertContracts(ctx) { + return nil, errors.Forbidden("forbidden", "only organization administrators can move a contract between the organization and a project") + } + + if scope, err = s.contractScopeChange(ctx, currentOrg.ID, req); err != nil { + return nil, err + } + } else if err := s.checkContractAccess(ctx, contract, authz.PolicyWorkflowContractUpdate, false); err != nil { return nil, err } @@ -223,6 +234,7 @@ func (s *WorkflowContractService) Update(ctx context.Context, req *pb.WorkflowCo &biz.WorkflowContractUpdateOpts{ Description: description, RawSchema: req.RawContract, + Scope: scope, }) if err != nil { return nil, handleUseCaseErr(ctx, err, s.log) @@ -236,6 +248,30 @@ func (s *WorkflowContractService) Update(ctx context.Context, req *pb.WorkflowCo return &pb.WorkflowContractServiceUpdateResponse{Result: result}, nil } +// contractScopeChange returns the level that the update request converts the contract to. +func (s *WorkflowContractService) contractScopeChange(ctx context.Context, orgID string, req *pb.WorkflowContractServiceUpdateRequest) (*biz.ContractScopeChange, error) { + switch scope := req.GetScope().(type) { + case *pb.WorkflowContractServiceUpdateRequest_OrganizationScoped: + return &biz.ContractScopeChange{}, nil + case *pb.WorkflowContractServiceUpdateRequest_ProjectReference: + project, err := s.userHasPermissionOnProject(ctx, orgID, scope.ProjectReference, authz.PolicyWorkflowContractUpdate) + if err != nil { + return nil, err + } + + return &biz.ContractScopeChange{ProjectID: &project.ID}, nil + default: + return nil, errors.BadRequest("invalid", "unknown contract scope") + } +} + +// canConvertContracts reports whether the caller can move a contract between the organization +// level and a project level. These are the callers that manage organization-level contracts: +// organization owners and admins, and organization-level API tokens (spec issue-3644, R-004). +func canConvertContracts(ctx context.Context) bool { + return canCreateContractsInRestrictedMode(ctx) +} + func (s *WorkflowContractService) Apply(ctx context.Context, req *pb.WorkflowContractServiceApplyRequest) (*pb.WorkflowContractServiceApplyResponse, error) { currentOrg, err := requireCurrentOrg(ctx) if err != nil { diff --git a/app/controlplane/internal/service/workflowcontract_integration_test.go b/app/controlplane/internal/service/workflowcontract_integration_test.go index 41094020a..296f0c0dd 100644 --- a/app/controlplane/internal/service/workflowcontract_integration_test.go +++ b/app/controlplane/internal/service/workflowcontract_integration_test.go @@ -382,28 +382,99 @@ func (s *workflowContractApplyIntegrationTestSuite) TestApplyLetsAConfinedTokenU // Organization-wide tokens and organization administrators still create contracts through Apply. func (s *workflowContractApplyIntegrationTestSuite) TestApplyLetsAnUnconfinedCallerCreateAContract() { - testCases := []applyCaller{ + for i, tc := range s.unconfinedCallers() { + s.Run(tc.name, func() { + name := fmt.Sprintf("unconfined-create-%d", i) + + resp, err := s.svc.Apply(tc.ctx, &pb.WorkflowContractServiceApplyRequest{RawSchema: namedContract(name), DryRun: true}) + s.Require().NoError(err) + s.Equal(pb.WorkflowContractServiceApplyResponse_APPLY_STATUS_CREATED, resp.GetStatus()) + + resp, err = s.svc.Apply(tc.ctx, &pb.WorkflowContractServiceApplyRequest{RawSchema: namedContract(name)}) + s.Require().NoError(err) + s.Equal(pb.WorkflowContractServiceApplyResponse_APPLY_STATUS_CREATED, resp.GetStatus()) + s.Equal(1, s.revisionOf(name)) + }) + } +} + +// unconfinedCallers are the callers that manage organization-level contracts. +func (s *workflowContractApplyIntegrationTestSuite) unconfinedCallers() []applyCaller { + orgID := uuid.MustParse(s.org.ID) + + return []applyCaller{ {name: "org token", ctx: s.apiTokenContext(authz.ResourceTypeOrganization, func(t *entities.APIToken) { - orgID := uuid.MustParse(s.org.ID) t.ScopeID = &orgID })}, {name: "instance token", ctx: s.apiTokenContext(authz.ResourceTypeInstance, nil)}, {name: "org owner", ctx: usercontext.WithAuthzSubject(s.ctx, string(authz.RoleOwner))}, {name: "org admin", ctx: usercontext.WithAuthzSubject(s.ctx, string(authz.RoleAdmin))}, } +} + +func toProjectScope(name string) *pb.WorkflowContractServiceUpdateRequest_ProjectReference { + return &pb.WorkflowContractServiceUpdateRequest_ProjectReference{ProjectReference: &pb.IdentityReference{Name: &name}} +} + +var toOrgScope = &pb.WorkflowContractServiceUpdateRequest_OrganizationScoped{OrganizationScoped: true} + +// Spec issue-3644 R-001, R-002 and R-004: the callers that manage organization-level contracts +// convert a contract in both directions. +func (s *workflowContractApplyIntegrationTestSuite) TestUpdateLetsAnUnconfinedCallerConvertAContract() { + project, err := s.Project.Create(context.Background(), s.org.ID, "convert-project") + s.Require().NoError(err) - for i, tc := range testCases { + for i, tc := range s.unconfinedCallers() { s.Run(tc.name, func() { - name := fmt.Sprintf("unconfined-create-%d", i) + name := fmt.Sprintf("unconfined-convert-%d", i) + _, err := s.WorkflowContract.Create(context.Background(), &biz.WorkflowContractCreateOpts{OrgID: s.org.ID, Name: name}) + s.Require().NoError(err) - resp, err := s.svc.Apply(tc.ctx, &pb.WorkflowContractServiceApplyRequest{RawSchema: namedContract(name), DryRun: true}) + resp, err := s.svc.Update(tc.ctx, &pb.WorkflowContractServiceUpdateRequest{Name: name, Scope: toProjectScope(project.Name)}) s.Require().NoError(err) - s.Equal(pb.WorkflowContractServiceApplyResponse_APPLY_STATUS_CREATED, resp.GetStatus()) + s.Equal(project.ID.String(), resp.GetResult().GetContract().GetScopedEntity().GetId()) + s.Equal(1, s.revisionOf(name), "a conversion creates no revision") - resp, err = s.svc.Apply(tc.ctx, &pb.WorkflowContractServiceApplyRequest{RawSchema: namedContract(name)}) + resp, err = s.svc.Update(tc.ctx, &pb.WorkflowContractServiceUpdateRequest{Name: name, Scope: toOrgScope}) s.Require().NoError(err) - s.Equal(pb.WorkflowContractServiceApplyResponse_APPLY_STATUS_CREATED, resp.GetStatus()) - s.Equal(1, s.revisionOf(name)) + s.Nil(resp.GetResult().GetContract().GetScopedEntity()) + }) + } +} + +// Spec issue-3644 R-004: a caller confined to projects can not convert a contract, in either +// direction, also when it can manage the project-level contract. +func (s *workflowContractApplyIntegrationTestSuite) TestUpdateRefusesAConfinedCallerConvertingAContract() { + project, err := s.Project.Create(context.Background(), s.org.ID, "confined-convert-project") + s.Require().NoError(err) + + orgContract, err := s.WorkflowContract.Create(context.Background(), &biz.WorkflowContractCreateOpts{OrgID: s.org.ID, Name: "confined-org-contract"}) + s.Require().NoError(err) + projectContract, err := s.WorkflowContract.Create(context.Background(), &biz.WorkflowContractCreateOpts{OrgID: s.org.ID, Name: "confined-project-contract", ProjectID: &project.ID}) + s.Require().NoError(err) + + callers := append(s.confinedTokens(project.ID), + applyCaller{name: "org member", ctx: usercontext.WithAuthzSubject(s.ctx, string(authz.RoleOrgMember))}, + applyCaller{name: "org contributor", ctx: usercontext.WithAuthzSubject(s.ctx, string(authz.RoleOrgContributor))}, + ) + + for _, tc := range callers { + s.Run(tc.name, func() { + _, err := s.svc.Update(tc.ctx, &pb.WorkflowContractServiceUpdateRequest{Name: orgContract.Name, Scope: toProjectScope(project.Name)}) + s.Require().Error(err) + s.True(kerrors.IsForbidden(err), "got %v", err) + + _, err = s.svc.Update(tc.ctx, &pb.WorkflowContractServiceUpdateRequest{Name: projectContract.Name, Scope: toOrgScope}) + s.Require().Error(err) + s.True(kerrors.IsForbidden(err), "got %v", err) + + // Nothing changed + got, err := s.WorkflowContract.FindByIDInOrg(context.Background(), s.org.ID, orgContract.ID.String()) + s.Require().NoError(err) + s.True(got.IsGlobalScoped()) + got, err = s.WorkflowContract.FindByIDInOrg(context.Background(), s.org.ID, projectContract.ID.String()) + s.Require().NoError(err) + s.True(got.IsProjectScoped()) }) } } @@ -426,7 +497,7 @@ func (s *workflowContractApplyIntegrationTestSuite) SetupTest() { s.org, err = s.Organization.CreateWithRandomName(context.Background()) s.Require().NoError(err) - s.svc = NewWorkflowSchemaService(s.WorkflowContract, s.Organization, s.User) + s.svc = NewWorkflowSchemaService(s.WorkflowContract, s.Organization, s.User, WithProjectUseCase(s.Project)) // Build a context with the current org and a bearer token, as the handler expects ctx := entities.WithCurrentOrg(context.Background(), &entities.Org{ID: s.org.ID, Name: s.org.Name}) diff --git a/app/controlplane/pkg/auditor/events/testdata/workflowcontracts/workflow_contract_scope_changed_to_organization.json b/app/controlplane/pkg/auditor/events/testdata/workflowcontracts/workflow_contract_scope_changed_to_organization.json new file mode 100644 index 000000000..3f29199b7 --- /dev/null +++ b/app/controlplane/pkg/auditor/events/testdata/workflowcontracts/workflow_contract_scope_changed_to_organization.json @@ -0,0 +1,24 @@ +{ + "ActionType": "WorkflowContractScopeChanged", + "TargetType": "WorkflowContract", + "TargetID": "1089bb36-e27b-428b-8009-d015c8737c54", + "ActorType": "USER", + "ActorID": "1089bb36-e27b-428b-8009-d015c8737c54", + "ActorEmail": "john@cyberdyne.io", + "ActorName": "John Connor", + "OrgID": "1089bb36-e27b-428b-8009-d015c8737c54", + "Description": "John Connor has moved the workflow contract test-contract from the project contract-project to the organization level", + "Info": { + "workflow_contract_id": "1089bb36-e27b-428b-8009-d015c8737c54", + "workflow_contract_name": "test-contract", + "old_scope": { + "type": "project", + "project_id": "3089bb36-e27b-428b-8009-d015c8737c56", + "project_name": "contract-project" + }, + "new_scope": { + "type": "organization" + } + }, + "Digest": "sha256:03dad56699514361bb331ed85e133cff0bc60d6841e3992660adc0e9b11a9c59" +} \ No newline at end of file diff --git a/app/controlplane/pkg/auditor/events/testdata/workflowcontracts/workflow_contract_scope_changed_to_organization_by_api_token.json b/app/controlplane/pkg/auditor/events/testdata/workflowcontracts/workflow_contract_scope_changed_to_organization_by_api_token.json new file mode 100644 index 000000000..6c7022509 --- /dev/null +++ b/app/controlplane/pkg/auditor/events/testdata/workflowcontracts/workflow_contract_scope_changed_to_organization_by_api_token.json @@ -0,0 +1,24 @@ +{ + "ActionType": "WorkflowContractScopeChanged", + "TargetType": "WorkflowContract", + "TargetID": "1089bb36-e27b-428b-8009-d015c8737c54", + "ActorType": "API_TOKEN", + "ActorID": "2089bb36-e27b-428b-8009-d015c8737c55", + "ActorEmail": "", + "ActorName": "test-token", + "OrgID": "1089bb36-e27b-428b-8009-d015c8737c54", + "Description": "test-token has moved the workflow contract test-contract from the project contract-project to the organization level", + "Info": { + "workflow_contract_id": "1089bb36-e27b-428b-8009-d015c8737c54", + "workflow_contract_name": "test-contract", + "old_scope": { + "type": "project", + "project_id": "3089bb36-e27b-428b-8009-d015c8737c56", + "project_name": "contract-project" + }, + "new_scope": { + "type": "organization" + } + }, + "Digest": "sha256:cbe2c824f2bb803698faa713f703e3308fa05335df93eff7c0443ee21ac8f438" +} \ No newline at end of file diff --git a/app/controlplane/pkg/auditor/events/testdata/workflowcontracts/workflow_contract_scope_changed_to_project.json b/app/controlplane/pkg/auditor/events/testdata/workflowcontracts/workflow_contract_scope_changed_to_project.json new file mode 100644 index 000000000..fea5c5f8e --- /dev/null +++ b/app/controlplane/pkg/auditor/events/testdata/workflowcontracts/workflow_contract_scope_changed_to_project.json @@ -0,0 +1,24 @@ +{ + "ActionType": "WorkflowContractScopeChanged", + "TargetType": "WorkflowContract", + "TargetID": "1089bb36-e27b-428b-8009-d015c8737c54", + "ActorType": "USER", + "ActorID": "1089bb36-e27b-428b-8009-d015c8737c54", + "ActorEmail": "john@cyberdyne.io", + "ActorName": "John Connor", + "OrgID": "1089bb36-e27b-428b-8009-d015c8737c54", + "Description": "John Connor has moved the workflow contract test-contract from the organization level to the project contract-project", + "Info": { + "workflow_contract_id": "1089bb36-e27b-428b-8009-d015c8737c54", + "workflow_contract_name": "test-contract", + "old_scope": { + "type": "organization" + }, + "new_scope": { + "type": "project", + "project_id": "3089bb36-e27b-428b-8009-d015c8737c56", + "project_name": "contract-project" + } + }, + "Digest": "sha256:a88e2cbaa7315757778ddd3b2a729bc6ef8703bf054b5ae6eafe24fd909fd814" +} \ No newline at end of file diff --git a/app/controlplane/pkg/auditor/events/testdata/workflowcontracts/workflow_contract_scope_changed_to_project_by_api_token.json b/app/controlplane/pkg/auditor/events/testdata/workflowcontracts/workflow_contract_scope_changed_to_project_by_api_token.json new file mode 100644 index 000000000..00ec27325 --- /dev/null +++ b/app/controlplane/pkg/auditor/events/testdata/workflowcontracts/workflow_contract_scope_changed_to_project_by_api_token.json @@ -0,0 +1,24 @@ +{ + "ActionType": "WorkflowContractScopeChanged", + "TargetType": "WorkflowContract", + "TargetID": "1089bb36-e27b-428b-8009-d015c8737c54", + "ActorType": "API_TOKEN", + "ActorID": "2089bb36-e27b-428b-8009-d015c8737c55", + "ActorEmail": "", + "ActorName": "test-token", + "OrgID": "1089bb36-e27b-428b-8009-d015c8737c54", + "Description": "test-token has moved the workflow contract test-contract from the organization level to the project contract-project", + "Info": { + "workflow_contract_id": "1089bb36-e27b-428b-8009-d015c8737c54", + "workflow_contract_name": "test-contract", + "old_scope": { + "type": "organization" + }, + "new_scope": { + "type": "project", + "project_id": "3089bb36-e27b-428b-8009-d015c8737c56", + "project_name": "contract-project" + } + }, + "Digest": "sha256:af0fe73d99d2c0082938e5fc6ebb7e30fb7c3b9b9fd927c5f4b69efea9932af3" +} \ No newline at end of file diff --git a/app/controlplane/pkg/auditor/events/workflowcontract.go b/app/controlplane/pkg/auditor/events/workflowcontract.go index 39b63dc76..f5fedf7c5 100644 --- a/app/controlplane/pkg/auditor/events/workflowcontract.go +++ b/app/controlplane/pkg/auditor/events/workflowcontract.go @@ -1,5 +1,5 @@ // -// Copyright 2024 The Chainloop Authors. +// Copyright 2024-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. @@ -31,6 +31,7 @@ var ( _ auditor.LogEntry = (*WorkflowContractDeleted)(nil) _ auditor.LogEntry = (*WorkflowContractAttached)(nil) _ auditor.LogEntry = (*WorkflowContractDetached)(nil) + _ auditor.LogEntry = (*WorkflowContractScopeChanged)(nil) ) const ( @@ -40,6 +41,12 @@ const ( WorkflowContractDeletedActionType string = "WorkflowContractDeleted" WorkflowContractContractAttachedActionType string = "WorkflowContractContractAttached" WorkflowContractContractDetachedActionType string = "WorkflowContractContractDetached" + WorkflowContractScopeChangedActionType string = "WorkflowContractScopeChanged" +) + +const ( + WorkflowContractScopeOrganization = "organization" + WorkflowContractScopeProject = "project" ) // WorkflowContractBase is the base struct for workflow contract events @@ -181,3 +188,43 @@ func (w *WorkflowContractDetached) ActionInfo() (json.RawMessage, error) { func (w *WorkflowContractDetached) Description() string { return fmt.Sprintf("%s has detached the workflow %s from the workflow contract %s", auditor.GetActorIdentifier(), w.WorkflowName, w.WorkflowContractName) } + +// WorkflowContractScope is the level of a contract: the organization, or a project. +type WorkflowContractScope struct { + // Type is WorkflowContractScopeOrganization or WorkflowContractScopeProject + Type string `json:"type"` + ProjectID *uuid.UUID `json:"project_id,omitempty"` + ProjectName string `json:"project_name,omitempty"` +} + +func (s *WorkflowContractScope) String() string { + if s.Type == WorkflowContractScopeProject { + return fmt.Sprintf("the project %s", s.ProjectName) + } + + return "the organization level" +} + +// WorkflowContractScopeChanged records the conversion of a contract between the organization +// level and a project level. +type WorkflowContractScopeChanged struct { + *WorkflowContractBase + OldScope *WorkflowContractScope `json:"old_scope"` + NewScope *WorkflowContractScope `json:"new_scope"` +} + +func (w *WorkflowContractScopeChanged) ActionType() string { + return WorkflowContractScopeChangedActionType +} + +func (w *WorkflowContractScopeChanged) ActionInfo() (json.RawMessage, error) { + if w.WorkflowContractID == nil || w.WorkflowContractName == "" || w.OldScope == nil || w.NewScope == nil { + return nil, errors.New("workflow contract id and name, old and new scope are required") + } + + return json.Marshal(&w) +} + +func (w *WorkflowContractScopeChanged) Description() string { + return fmt.Sprintf("%s has moved the workflow contract %s from %s to %s", auditor.GetActorIdentifier(), w.WorkflowContractName, w.OldScope, w.NewScope) +} diff --git a/app/controlplane/pkg/auditor/events/workflowcontract_test.go b/app/controlplane/pkg/auditor/events/workflowcontract_test.go index 92b31f2ea..7fe1f5397 100644 --- a/app/controlplane/pkg/auditor/events/workflowcontract_test.go +++ b/app/controlplane/pkg/auditor/events/workflowcontract_test.go @@ -1,5 +1,5 @@ // -// Copyright 2024-2025 The Chainloop Authors. +// Copyright 2024-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. @@ -46,6 +46,11 @@ func TestWorkflowContractEvents(t *testing.T) { wfUUID, err := uuid.Parse("1089bb36-e27b-428b-8009-d015c8737c54") require.NoError(t, err) wfName := "test-workflow" + projectUUID, err := uuid.Parse("3089bb36-e27b-428b-8009-d015c8737c56") + require.NoError(t, err) + orgScope := &events.WorkflowContractScope{Type: events.WorkflowContractScopeOrganization} + projectScope := &events.WorkflowContractScope{Type: events.WorkflowContractScopeProject, ProjectID: &projectUUID, ProjectName: "contract-project"} + contractBase := &events.WorkflowContractBase{WorkflowContractID: uuidPtr(wfContractUUID), WorkflowContractName: wfContractName} tests := []struct { name string @@ -188,6 +193,34 @@ func TestWorkflowContractEvents(t *testing.T) { actor: auditor.ActorTypeAPIToken, actorID: apiTokenUUID, }, + { + name: "Workflow contract converted from organization to project by user", + event: &events.WorkflowContractScopeChanged{WorkflowContractBase: contractBase, OldScope: orgScope, NewScope: projectScope}, + expected: "testdata/workflowcontracts/workflow_contract_scope_changed_to_project.json", + actor: auditor.ActorTypeUser, + actorID: userUUID, + }, + { + name: "Workflow contract converted from organization to project by API token", + event: &events.WorkflowContractScopeChanged{WorkflowContractBase: contractBase, OldScope: orgScope, NewScope: projectScope}, + expected: "testdata/workflowcontracts/workflow_contract_scope_changed_to_project_by_api_token.json", + actor: auditor.ActorTypeAPIToken, + actorID: apiTokenUUID, + }, + { + name: "Workflow contract converted from project to organization by user", + event: &events.WorkflowContractScopeChanged{WorkflowContractBase: contractBase, OldScope: projectScope, NewScope: orgScope}, + expected: "testdata/workflowcontracts/workflow_contract_scope_changed_to_organization.json", + actor: auditor.ActorTypeUser, + actorID: userUUID, + }, + { + name: "Workflow contract converted from project to organization by API token", + event: &events.WorkflowContractScopeChanged{WorkflowContractBase: contractBase, OldScope: projectScope, NewScope: orgScope}, + expected: "testdata/workflowcontracts/workflow_contract_scope_changed_to_organization_by_api_token.json", + actor: auditor.ActorTypeAPIToken, + actorID: apiTokenUUID, + }, } for _, tt := range tests { diff --git a/app/controlplane/pkg/biz/workflow_integration_test.go b/app/controlplane/pkg/biz/workflow_integration_test.go index b2ce76de2..7d789f271 100644 --- a/app/controlplane/pkg/biz/workflow_integration_test.go +++ b/app/controlplane/pkg/biz/workflow_integration_test.go @@ -309,6 +309,23 @@ func (s *workflowIntegrationTestSuite) TestCreateWithProjectScopedContract() { s.ErrorContains(err, "scoped to a different project") }) + s.Run("fails when the default contract of the workflow is scoped to a different project (spec issue-3644 R-010)", func() { + // The default contract of workflow "default-wf" in project "other-project" is "other-project-default-wf" + _, err := s.WorkflowContract.Create(ctx, &biz.WorkflowContractCreateOpts{ + OrgID: s.org.ID, + Name: "other-project-default-wf", + ProjectID: &wf.ProjectID, + }) + s.Require().NoError(err) + + _, err = s.Workflow.Create(ctx, &biz.WorkflowCreateOpts{ + OrgID: s.org.ID, + Name: "default-wf", + Project: "other-project", + }) + s.ErrorContains(err, "scoped to a different project") + }) + s.Run("succeeds after the original project is soft-deleted and a new one with the same name is created", func() { // Simulate the bug: soft-delete the original project so the next workflow creation // creates a new project with the same name but a different UUID. @@ -329,6 +346,58 @@ func (s *workflowIntegrationTestSuite) TestCreateWithProjectScopedContract() { }) } +// Spec issue-3644 R-010: a workflow update cannot attach a contract of a different project. +func (s *workflowIntegrationTestSuite) TestUpdateWithProjectScopedContract() { + ctx := context.Background() + + wfA, err := s.Workflow.Create(ctx, &biz.WorkflowCreateOpts{OrgID: s.org.ID, Name: "wf-a", Project: "project-a"}) + s.Require().NoError(err) + wfB, err := s.Workflow.Create(ctx, &biz.WorkflowCreateOpts{OrgID: s.org.ID, Name: "wf-b", Project: "project-b"}) + s.Require().NoError(err) + + contractA, err := s.WorkflowContract.Create(ctx, &biz.WorkflowContractCreateOpts{OrgID: s.org.ID, Name: "contract-a", ProjectID: &wfA.ProjectID}) + s.Require().NoError(err) + orgContract, err := s.WorkflowContract.Create(ctx, &biz.WorkflowContractCreateOpts{OrgID: s.org.ID, Name: "org-contract"}) + s.Require().NoError(err) + + testCases := []struct { + name string + workflow *biz.Workflow + contract *biz.WorkflowContract + wantErrMsg string + }{ + { + name: "a contract of the same project", + workflow: wfA, + contract: contractA, + }, + { + name: "an organization-level contract", + workflow: wfB, + contract: orgContract, + }, + { + name: "a contract of a different project", + workflow: wfB, + contract: contractA, + wantErrMsg: "scoped to a different project", + }, + } + + for _, tc := range testCases { + s.Run(tc.name, func() { + got, err := s.Workflow.Update(ctx, s.org.ID, tc.workflow.ID.String(), &biz.WorkflowUpdateOpts{ContractID: toPtrS(tc.contract.ID.String())}) + if tc.wantErrMsg != "" { + s.ErrorContains(err, tc.wantErrMsg) + return + } + + s.Require().NoError(err) + s.Equal(tc.contract.ID, got.ContractID) + }) + } +} + func (s *workflowIntegrationTestSuite) TestUpdate() { ctx := context.Background() const ( @@ -678,6 +747,9 @@ func (s *workflowListIntegrationTestSuite) TearDownSubTest() { _, _ = s.Data.DB.Project.Delete().Exec(context.Background()) _, _ = s.Data.DB.WorkflowRun.Delete().Exec(context.Background()) _, _ = s.Data.DB.CASBackend.Delete().Exec(context.Background()) + // The default contracts of the deleted workflows are scoped to the deleted projects + _, _ = s.Data.DB.WorkflowContractVersion.Delete().Exec(context.Background()) + _, _ = s.Data.DB.WorkflowContract.Delete().Exec(context.Background()) } func toPtrS(s string) *string { diff --git a/app/controlplane/pkg/biz/workflowcontract.go b/app/controlplane/pkg/biz/workflowcontract.go index 3c72aa154..9a6d406c2 100644 --- a/app/controlplane/pkg/biz/workflowcontract.go +++ b/app/controlplane/pkg/biz/workflowcontract.go @@ -140,6 +140,8 @@ type ContractUpdateOpts struct { Description *string // raw representation of the contract in whatever original format it was (json, yaml, ...) Contract *Contract + // Scope converts the contract to the organization level or to a project level + Scope *ContractScopeChange } type WorkflowContractUseCase struct { @@ -405,6 +407,16 @@ func (uc *WorkflowContractUseCase) FindVersionByID(ctx context.Context, versionI type WorkflowContractUpdateOpts struct { RawSchema []byte Description *string + // Scope converts the contract to the organization level or to a project level. + // When nil, the level of the contract does not change. + Scope *ContractScopeChange +} + +// ContractScopeChange is the level that a contract converts to. +type ContractScopeChange struct { + // ProjectID is the project that the contract converts to. + // When nil, the contract converts to the organization level. + ProjectID *uuid.UUID } func (uc *WorkflowContractUseCase) Update(ctx context.Context, orgID, name string, opts *WorkflowContractUpdateOpts) (*WorkflowContractWithVersion, error) { @@ -435,7 +447,7 @@ func (uc *WorkflowContractUseCase) Update(ctx context.Context, orgID, name strin return nil, fmt.Errorf("failed to find contract %s in org %s: %w", name, orgUUID, err) } - args := &ContractUpdateOpts{Description: opts.Description, Contract: contract} + args := &ContractUpdateOpts{Description: opts.Description, Contract: contract, Scope: opts.Scope} c, err := uc.repo.Update(ctx, orgUUID, name, args) if err != nil { return nil, fmt.Errorf("failed to update contract: %w", err) @@ -461,11 +473,42 @@ func (uc *WorkflowContractUseCase) Update(ctx context.Context, orgID, name strin uc.auditorUC.Dispatch(ctx, eventPayload, &orgUUID) + // A conversion between the organization level and a project level gets its own event + if !sameContractScope(wfContractPreUpdate, c.Contract) { + uc.auditorUC.Dispatch(ctx, &events.WorkflowContractScopeChanged{ + WorkflowContractBase: eventPayload.WorkflowContractBase, + OldScope: contractScopeForEvent(wfContractPreUpdate), + NewScope: contractScopeForEvent(c.Contract), + }, &orgUUID) + } + c.Changed = changed return c, nil } +// sameContractScope reports whether both contracts are at the same level. +func sameContractScope(a, b *WorkflowContract) bool { + if a.IsProjectScoped() != b.IsProjectScoped() { + return false + } + + return !a.IsProjectScoped() || a.ScopedEntity.ID == b.ScopedEntity.ID +} + +// contractScopeForEvent returns the level of the contract, as the audit events show it. +func contractScopeForEvent(c *WorkflowContract) *events.WorkflowContractScope { + if !c.IsProjectScoped() { + return &events.WorkflowContractScope{Type: events.WorkflowContractScopeOrganization} + } + + return &events.WorkflowContractScope{ + Type: events.WorkflowContractScopeProject, + ProjectID: &c.ScopedEntity.ID, + ProjectName: c.ScopedEntity.Name, + } +} + // RevisionWouldChange reports whether applying rawSchema to the contract // identified by contractID would create a new revision, without persisting // anything. It mirrors the change detection performed by the data layer on diff --git a/app/controlplane/pkg/biz/workflowcontract_audit_test.go b/app/controlplane/pkg/biz/workflowcontract_audit_test.go new file mode 100644 index 000000000..fb15cd8f0 --- /dev/null +++ b/app/controlplane/pkg/biz/workflowcontract_audit_test.go @@ -0,0 +1,136 @@ +// +// 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" + "encoding/json" + "io" + "testing" + + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/auditor/events" + "github.com/go-kratos/kratos/v2/log" + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// stubWorkflowContractRepo returns the contract before and after an update. +// Only FindByNameInOrg and Update are exercised; any other call panics on the +// nil embedded interface. +type stubWorkflowContractRepo struct { + WorkflowContractRepo + before, after *WorkflowContract +} + +func (s *stubWorkflowContractRepo) FindByNameInOrg(_ context.Context, _ uuid.UUID, _ string) (*WorkflowContract, error) { + return s.before, nil +} + +func (s *stubWorkflowContractRepo) Update(_ context.Context, _ uuid.UUID, _ string, _ *ContractUpdateOpts) (*WorkflowContractWithVersion, error) { + return &WorkflowContractWithVersion{ + Contract: s.after, + Version: &WorkflowContractVersion{ID: uuid.New(), Revision: s.after.LatestRevision}, + }, nil +} + +// Spec issue-3644 R-008: each conversion writes an audit event with the old and the new level. +func TestWorkflowContractUpdateDispatchesScopeChanged(t *testing.T) { + project := &ScopedEntity{Type: string(ContractScopeProject), ID: uuid.New(), Name: "my-project"} + orgScope := &events.WorkflowContractScope{Type: events.WorkflowContractScopeOrganization} + projectScope := &events.WorkflowContractScope{Type: events.WorkflowContractScopeProject, ProjectID: &project.ID, ProjectName: project.Name} + + testCases := []struct { + name string + before, after *ScopedEntity + scope *ContractScopeChange + // nil means no scope event is dispatched + wantOld, wantNew *events.WorkflowContractScope + }{ + { + name: "organization to project", + after: project, + scope: &ContractScopeChange{ProjectID: &project.ID}, + wantOld: orgScope, + wantNew: projectScope, + }, + { + name: "project to organization", + before: project, + scope: &ContractScopeChange{}, + wantOld: projectScope, + wantNew: orgScope, + }, + { + name: "same level", + before: project, + after: project, + scope: &ContractScopeChange{ProjectID: &project.ID}, + }, + { + name: "no level in the request", + before: project, + after: project, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + auditorUC, publisher := newRecordingAuditor() + contractID := uuid.New() + repo := &stubWorkflowContractRepo{ + before: &WorkflowContract{ID: contractID, Name: "my-contract", LatestRevision: 1, ScopedEntity: cloneScope(tc.before)}, + after: &WorkflowContract{ID: contractID, Name: "my-contract", LatestRevision: 1, ScopedEntity: cloneScope(tc.after)}, + } + uc := NewWorkflowContractUseCase(repo, nil, auditorUC, log.NewStdLogger(io.Discard)) + + _, err := uc.Update(ctxWithAPITokenActor(context.Background()), uuid.NewString(), "my-contract", &WorkflowContractUpdateOpts{Scope: tc.scope}) + require.NoError(t, err) + + var scopeEvents []json.RawMessage + for _, p := range publisher.published { + if p.Data.ActionType == events.WorkflowContractScopeChangedActionType { + assert.Equal(t, &contractID, p.Data.TargetID) + scopeEvents = append(scopeEvents, p.Data.Info) + } + } + + if tc.wantNew == nil { + assert.Empty(t, scopeEvents) + return + } + + require.Len(t, scopeEvents, 1) + var info struct { + OldScope *events.WorkflowContractScope `json:"old_scope"` + NewScope *events.WorkflowContractScope `json:"new_scope"` + } + require.NoError(t, json.Unmarshal(scopeEvents[0], &info)) + assert.Equal(t, tc.wantOld, info.OldScope) + assert.Equal(t, tc.wantNew, info.NewScope) + }) + } +} + +// cloneScope returns a copy, as the repository returns a new object on each call. +func cloneScope(s *ScopedEntity) *ScopedEntity { + if s == nil { + return nil + } + + c := *s + return &c +} diff --git a/app/controlplane/pkg/biz/workflowcontract_integration_test.go b/app/controlplane/pkg/biz/workflowcontract_integration_test.go index 5370c5619..6ec40ac8b 100644 --- a/app/controlplane/pkg/biz/workflowcontract_integration_test.go +++ b/app/controlplane/pkg/biz/workflowcontract_integration_test.go @@ -141,6 +141,165 @@ func (s *workflowContractIntegrationTestSuite) TestUpdate() { } } +// Spec issue-3644: a contract converts between the organization level and a project level, +// and keeps its identity, revisions and workflows. +func (s *workflowContractIntegrationTestSuite) TestUpdateScope() { + ctx := context.Background() + + toOrg := &biz.ContractScopeChange{} + toProject := func(p *biz.Project) *biz.ContractScopeChange { + return &biz.ContractScopeChange{ProjectID: &p.ID} + } + + newContract := func(name string, projectID *uuid.UUID) *biz.WorkflowContract { + c, err := s.WorkflowContract.Create(ctx, &biz.WorkflowContractCreateOpts{OrgID: s.org.ID, Name: name, ProjectID: projectID}) + s.Require().NoError(err) + return c + } + + attachWorkflow := func(contract *biz.WorkflowContract, project, name string) { + _, err := s.Workflow.Create(ctx, &biz.WorkflowCreateOpts{OrgID: s.org.ID, Name: name, Project: project, ContractName: contract.Name}) + s.Require().NoError(err) + } + + testCases := []struct { + name string + // setup returns the contract to update + setup func() *biz.WorkflowContract + scope *biz.ContractScopeChange + rawSchema []byte + wantErrMsg []string + wantProjectID *uuid.UUID + wantRevision int + wantWorkflows int + }{ + { + name: "organization to project (R-001)", + setup: func() *biz.WorkflowContract { return newContract("org-to-project", nil) }, + scope: toProject(s.p1), + wantProjectID: &s.p1.ID, + wantRevision: 1, + }, + { + name: "project to organization (R-002)", + setup: func() *biz.WorkflowContract { return newContract("project-to-org", &s.p1.ID) }, + scope: toOrg, + wantRevision: 1, + }, + { + name: "organization to project keeps the workflows of that project (R-003)", + setup: func() *biz.WorkflowContract { + c := newContract("org-to-project-with-workflows", nil) + attachWorkflow(c, s.p1.Name, "wf-in-p1") + return c + }, + scope: toProject(s.p1), + wantProjectID: &s.p1.ID, + wantRevision: 1, + wantWorkflows: 1, + }, + { + name: "project to organization keeps the workflows (R-003)", + setup: func() *biz.WorkflowContract { + c := newContract("project-to-org-with-workflows", &s.p1.ID) + attachWorkflow(c, s.p1.Name, "wf-in-p1-2") + return c + }, + scope: toOrg, + wantRevision: 1, + wantWorkflows: 1, + }, + { + name: "organization to project fails when workflows of other projects use it (R-005)", + setup: func() *biz.WorkflowContract { + c := newContract("used-across-projects", nil) + attachWorkflow(c, s.p1.Name, "wf-a") + attachWorkflow(c, s.p2.Name, "wf-b") + return c + }, + scope: toProject(s.p1), + wantErrMsg: []string{"a-valid-project-2/wf-b"}, + }, + { + name: "project to a different project fails (R-006)", + setup: func() *biz.WorkflowContract { return newContract("project-to-project", &s.p1.ID) }, + scope: toProject(s.p2), + wantErrMsg: []string{"different project"}, + }, + { + name: "project to the same project changes nothing (R-006)", + setup: func() *biz.WorkflowContract { return newContract("project-to-same-project", &s.p1.ID) }, + scope: toProject(s.p1), + wantProjectID: &s.p1.ID, + wantRevision: 1, + }, + { + name: "organization to organization changes nothing (R-006)", + setup: func() *biz.WorkflowContract { return newContract("org-to-org", nil) }, + scope: toOrg, + wantRevision: 1, + }, + { + name: "a new body in the same request creates a revision (R-007)", + setup: func() *biz.WorkflowContract { return newContract("scope-and-body", nil) }, + scope: toProject(s.p1), + rawSchema: []byte(`schemaVersion: v1`), + wantProjectID: &s.p1.ID, + wantRevision: 2, + }, + { + name: "no scope keeps the scope (R-009)", + setup: func() *biz.WorkflowContract { return newContract("no-scope", &s.p1.ID) }, + rawSchema: []byte(`schemaVersion: v1`), + wantProjectID: &s.p1.ID, + wantRevision: 2, + }, + } + + for _, tc := range testCases { + s.Run(tc.name, func() { + contract := tc.setup() + + got, err := s.WorkflowContract.Update(ctx, s.org.ID, contract.Name, &biz.WorkflowContractUpdateOpts{ + RawSchema: tc.rawSchema, + Scope: tc.scope, + }) + if len(tc.wantErrMsg) > 0 { + s.Require().Error(err) + s.True(biz.IsErrValidation(err)) + for _, msg := range tc.wantErrMsg { + s.ErrorContains(err, msg) + } + + // The contract keeps its level + after, err := s.WorkflowContract.FindByIDInOrg(ctx, s.org.ID, contract.ID.String()) + s.Require().NoError(err) + s.Equal(contract.ScopedEntity, after.ScopedEntity) + return + } + s.Require().NoError(err) + + s.Equal(contract.ID, got.Contract.ID) + s.Equal(contract.Name, got.Contract.Name) + s.Equal(tc.wantRevision, got.Version.Revision) + s.Len(got.Contract.WorkflowRefs, tc.wantWorkflows) + + // Read it back to make sure the change was persisted + stored, err := s.WorkflowContract.FindByIDInOrg(ctx, s.org.ID, contract.ID.String()) + s.Require().NoError(err) + for _, c := range []*biz.WorkflowContract{got.Contract, stored} { + if tc.wantProjectID == nil { + s.True(c.IsGlobalScoped()) + continue + } + + s.Require().True(c.IsProjectScoped()) + s.Equal(*tc.wantProjectID, c.ScopedEntity.ID) + } + }) + } +} + func (s *workflowContractIntegrationTestSuite) TestRevisionWouldChange() { ctx := context.Background() @@ -411,7 +570,7 @@ func TestWorkflowContractUseCase(t *testing.T) { type workflowContractIntegrationTestSuite struct { testhelpers.UseCasesEachTestSuite org, org2 *biz.Organization - p1 *biz.Project + p1, p2 *biz.Project contractOrg1 *biz.WorkflowContract contractScopedToProject *biz.WorkflowContract @@ -430,7 +589,7 @@ func (s *workflowContractIntegrationTestSuite) SetupTest() { s.p1, err = s.Project.Create(ctx, s.org.ID, "a-valid-project") s.NoError(err) - p2, err := s.Project.Create(ctx, s.org.ID, "a-valid-project-2") + s.p2, err = s.Project.Create(ctx, s.org.ID, "a-valid-project-2") s.NoError(err) s.contractOrg1, err = s.WorkflowContract.Create(ctx, &biz.WorkflowContractCreateOpts{OrgID: s.org.ID, Name: "a-valid-contract"}) @@ -439,7 +598,7 @@ func (s *workflowContractIntegrationTestSuite) SetupTest() { s.contractScopedToProject, err = s.WorkflowContract.Create(ctx, &biz.WorkflowContractCreateOpts{OrgID: s.org.ID, Name: "a-valid-contract-scoped-to-project", ProjectID: &s.p1.ID}) s.NoError(err) - _, err = s.WorkflowContract.Create(ctx, &biz.WorkflowContractCreateOpts{OrgID: s.org.ID, Name: "a-valid-contract-scoped-to-project-2", ProjectID: &p2.ID}) + _, err = s.WorkflowContract.Create(ctx, &biz.WorkflowContractCreateOpts{OrgID: s.org.ID, Name: "a-valid-contract-scoped-to-project-2", ProjectID: &s.p2.ID}) s.Require().NoError(err) } diff --git a/app/controlplane/pkg/data/workflow.go b/app/controlplane/pkg/data/workflow.go index 31918e88d..82927b8ed 100644 --- a/app/controlplane/pkg/data/workflow.go +++ b/app/controlplane/pkg/data/workflow.go @@ -33,6 +33,7 @@ import ( "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/integrationattachment" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/project" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflow" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowcontract" "github.com/go-kratos/kratos/v2/log" "github.com/google/uuid" ) @@ -174,29 +175,21 @@ func (r *WorkflowRepo) Create(ctx context.Context, opts *biz.WorkflowCreateOpts) } else { return fmt.Errorf("failed to find contract: %w", err) } + } else if err := checkContractProject(ctx, tx, contract.ID, opts.Project); err != nil { + // An existing contract with the default name must be usable from this project + return err } } contractUUID = contract.ID } else { // We want to use an existing contract, let's make sure it's scoped to the project or org - existingContract, err := contractInOrg(ctx, r.data.DB, orgUUID, &contractUUID, nil) - if err != nil { + if _, err := contractInOrg(ctx, r.data.DB, orgUUID, &contractUUID, nil, biz.WithoutReferences()); err != nil { return err } - // Fail if it's scoped to a different project. - // We resolve the scoped project by UUID (including soft-deleted ones) to read its name, - // then compare that name against the target project. This handles the case where the - // original project was soft-deleted and recreated with the same name but a new UUID — - // the contract is still valid for a project with that name. - if existingContract.ScopedResourceID != uuid.Nil && existingContract.ScopedResourceType == biz.ContractScopeProject { - scopedProject, err := tx.Project.Query(). - Where(project.ID(existingContract.ScopedResourceID)). - Only(ctx) - if err != nil || scopedProject.Name != opts.Project { - return biz.NewErrUnauthorizedStr(fmt.Sprintf("contract %q is scoped to a different project", opts.ContractName)) - } + if err := checkContractProject(ctx, tx, contractUUID, opts.Project); err != nil { + return err } } @@ -233,34 +226,76 @@ func (r *WorkflowRepo) Update(ctx context.Context, id uuid.UUID, opts *biz.Workf opts = &biz.WorkflowUpdateOpts{} } - req := r.data.DB.Workflow.UpdateOneID(id). - SetNillableTeam(opts.Team). - SetNillableDescription(opts.Description). - SetUpdatedAt(time.Now()) + var wf *ent.Workflow + if err := WithTx(ctx, r.data.DB, func(tx *ent.Tx) error { + req := tx.Workflow.UpdateOneID(id). + SetNillableTeam(opts.Team). + SetNillableDescription(opts.Description). + SetUpdatedAt(time.Now()) - // Update the contract if provided - if opts.ContractID != nil { - contractUUID, err := uuid.Parse(*opts.ContractID) - if err != nil { - return nil, err + // Update the contract if provided + if opts.ContractID != nil { + contractUUID, err := uuid.Parse(*opts.ContractID) + if err != nil { + return err + } + + current, err := tx.Workflow.Query().Where(workflow.ID(id)).WithProject().Only(ctx) + if err != nil { + return fmt.Errorf("failed to find workflow: %w", err) + } + + if err := checkContractProject(ctx, tx, contractUUID, current.Edges.Project.Name); err != nil { + return err + } + + req = req.SetContractID(contractUUID) } - req = req.SetContractID(contractUUID) - } - wf, err := req.Save(ctx) + var err error + if wf, err = req.Save(ctx); err != nil { + if ent.IsConstraintError(err) { + return biz.NewErrAlreadyExists(err) + } - if err != nil { - if ent.IsConstraintError(err) { - return nil, biz.NewErrAlreadyExists(err) + return fmt.Errorf("failed to update workflow: %w", err) } - return nil, fmt.Errorf("failed to update workflow: %w", err) + return nil + }); err != nil { + return nil, err } // Reload the object to include the relations return r.FindByID(ctx, wf.ID) } +// checkContractProject fails when the contract is scoped to a project other than projectName. +// It locks the contract for share, so a conversion of the same contract waits until the +// workflow change completes, and the other way around (spec issue-3644, R-010 and D-008). +// +// We resolve the scoped project by UUID (including soft-deleted ones) to read its name, then +// compare that name against the target project. This handles the case where the original +// project was soft-deleted and recreated with the same name but a new UUID: the contract is +// still valid for a project with that name. +func checkContractProject(ctx context.Context, tx *ent.Tx, contractID uuid.UUID, projectName string) error { + contract, err := tx.WorkflowContract.Query().Where(workflowcontract.ID(contractID)).ForShare().Only(ctx) + if err != nil { + return fmt.Errorf("locking the contract: %w", err) + } + + if contract.ScopedResourceID == uuid.Nil || contract.ScopedResourceType != biz.ContractScopeProject { + return nil + } + + scopedProject, err := tx.Project.Query().Where(project.ID(contract.ScopedResourceID)).Only(ctx) + if err != nil || scopedProject.Name != projectName { + return biz.NewErrUnauthorizedStr(fmt.Sprintf("contract %q is scoped to a different project", contract.Name)) + } + + return nil +} + func (r *WorkflowRepo) List(ctx context.Context, orgID uuid.UUID, filter *biz.WorkflowListOpts, pagination *pagination.OffsetPaginationOpts) ([]*biz.Workflow, int, error) { ctx, span := otelx.Start(ctx, workflowRepoTracer, "WorkflowRepo.List") defer span.End() diff --git a/app/controlplane/pkg/data/workflowcontract.go b/app/controlplane/pkg/data/workflowcontract.go index 65687d771..d8848108e 100644 --- a/app/controlplane/pkg/data/workflowcontract.go +++ b/app/controlplane/pkg/data/workflowcontract.go @@ -19,6 +19,8 @@ import ( "bytes" "context" "fmt" + "slices" + "strings" "time" schemav1 "github.com/chainloop-dev/chainloop/app/controlplane/api/workflowcontract/v1" @@ -254,7 +256,13 @@ func (r *WorkflowContractRepo) Update(ctx context.Context, orgID uuid.UUID, name ) if err = WithTx(ctx, r.data.DB, func(tx *ent.Tx) error { - contract, err = contract.Update().SetNillableDescription(opts.Description).SetUpdatedAt(time.Now()).Save(ctx) + if opts.Scope != nil { + if err := changeContractScope(ctx, tx, orgID, contract.ID, opts.Scope); err != nil { + return err + } + } + + contract, err = tx.WorkflowContract.UpdateOne(contract).SetNillableDescription(opts.Description).SetUpdatedAt(time.Now()).Save(ctx) if err != nil { return handleError(err) } @@ -304,6 +312,72 @@ func (r *WorkflowContractRepo) Update(ctx context.Context, orgID uuid.UUID, name }, nil } +// changeContractScope converts the contract to the organization level or to a project level. +// It locks the contract first, so a workflow change on the same contract waits until the +// conversion completes, and the other way around (spec issue-3644, D-008). +func changeContractScope(ctx context.Context, tx *ent.Tx, orgID, contractID uuid.UUID, scope *biz.ContractScopeChange) error { + current, err := tx.WorkflowContract.Query().Where(workflowcontract.ID(contractID)).ForUpdate().Only(ctx) + if err != nil { + return fmt.Errorf("locking the contract: %w", err) + } + + projectScoped := current.ScopedResourceType == biz.ContractScopeProject && current.ScopedResourceID != uuid.Nil + + // To the organization level + if scope.ProjectID == nil { + if !projectScoped { + return nil + } + + return tx.WorkflowContract.UpdateOneID(contractID).ClearScopedResourceType().ClearScopedResourceID().Exec(ctx) + } + + // To a project level + targetID := *scope.ProjectID + if projectScoped { + if current.ScopedResourceID == targetID { + return nil + } + + return biz.NewErrValidationStr("a project-level contract can not be moved to a different project") + } + + exists, err := tx.Project.Query().Where(project.ID(targetID), project.OrganizationID(orgID), project.DeletedAtIsNil()).Exist(ctx) + if err != nil { + return fmt.Errorf("finding the project: %w", err) + } else if !exists { + return biz.NewErrNotFound("project") + } + + // Workflows of other projects can not use a project-level contract + others, err := tx.Workflow.Query(). + Where( + workflow.HasContractWith(workflowcontract.ID(contractID)), + workflow.DeletedAtIsNil(), + workflow.ProjectIDNEQ(targetID), + ). + WithProject(). + All(ctx) + if err != nil { + return fmt.Errorf("finding the workflows of the contract: %w", err) + } + + if len(others) > 0 { + refs := make([]string, 0, len(others)) + for _, wf := range others { + refs = append(refs, fmt.Sprintf("%s/%s", wf.Edges.Project.Name, wf.Name)) + } + slices.Sort(refs) + + return biz.NewErrValidationStr(fmt.Sprintf("the contract is used by workflows of other projects, attach a different contract to them first: %s", strings.Join(refs, ", "))) + } + + return tx.WorkflowContract.UpdateOneID(contractID). + SetScopedResourceType(biz.ContractScopeProject). + SetScopedResourceID(targetID). + Exec(ctx) +} + func (r *WorkflowContractRepo) FindByIDInOrg(ctx context.Context, orgID, contractID uuid.UUID) (*biz.WorkflowContract, error) { ctx, span := otelx.Start(ctx, workflowContractRepoTracer, "WorkflowContractRepo.FindByIDInOrg") defer span.End() From 187612f675e699030be70a81c712f2cc468cec47 Mon Sep 17 00:00:00 2001 From: Jose Ignacio Paris Prieto Date: Fri, 6 Nov 2026 13:55:33 +0100 Subject: [PATCH 2/3] fix(contracts): address review of the contract level conversion - Rename the CLI flag --org to --org-level. The local --org hid the global --org flag that selects the organization. Add a test that no command flag hides a global flag. - Take the old level of the audit event from the conversion, which reads it under the contract lock, and write the event only when the level changed. - Add validation tests for the level field of the update request. - Spec issue-3644: D-009 supersedes D-003, R-011 supersedes R-002, add D-010. Refs #3644 Assisted-by: Claude Code Signed-off-by: Jose Ignacio Paris Prieto Chainloop-Trace-Sessions: bc6fbb4d-3bf8-4fd0-b81e-10aa03bf1e58 --- app/cli/cmd/root_test.go | 39 +++++++++ app/cli/cmd/workflow_contract_update.go | 8 +- app/cli/documentation/cli-reference.md | 7 +- .../controlplane/v1/workflow_contract_test.go | 76 +++++++++++++++++ app/controlplane/pkg/biz/workflowcontract.go | 34 ++++---- .../pkg/biz/workflowcontract_audit_test.go | 82 ++++++++++--------- .../biz/workflowcontract_integration_test.go | 46 +++++++---- app/controlplane/pkg/data/workflowcontract.go | 75 +++++++++++------ .../issue-3644-contract-scope-conversion.md | 41 +++++++--- 9 files changed, 294 insertions(+), 114 deletions(-) create mode 100644 app/controlplane/api/controlplane/v1/workflow_contract_test.go diff --git a/app/cli/cmd/root_test.go b/app/cli/cmd/root_test.go index d345e2ca1..a26066f69 100644 --- a/app/cli/cmd/root_test.go +++ b/app/cli/cmd/root_test.go @@ -21,6 +21,7 @@ import ( "github.com/rs/zerolog" "github.com/spf13/cobra" + "github.com/spf13/pflag" "github.com/spf13/viper" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -141,3 +142,41 @@ func TestNewRootCmdInitializesLogger(t *testing.T) { rootLogger.Error().Msg("boom") assert.Contains(t, out.String(), "boom") } + +// A command flag with the name or the shorthand of a global flag hides the global flag on that +// command. For example, a local --org hides the global --org that selects the organization. +func TestNoCommandShadowsAGlobalFlag(t *testing.T) { + root := NewRootCmd(zerolog.Nop()) + + globalNames := map[string]bool{} + globalShorthands := map[string]bool{} + root.PersistentFlags().VisitAll(func(f *pflag.Flag) { + globalNames[f.Name] = true + if f.Shorthand != "" { + globalShorthands[f.Shorthand] = true + } + }) + + // Flags that hid a global flag before this test existed. Do not add to this list. + known := map[string]bool{ + "chainloop artifact download --output": true, + "chainloop trace uninstall --yes": true, + "chainloop trace uninstall -y": true, + } + + var walk func(c *cobra.Command) + walk = func(c *cobra.Command) { + for _, sub := range c.Commands() { + sub.LocalFlags().VisitAll(func(f *pflag.Flag) { + if name := sub.CommandPath() + " --" + f.Name; globalNames[f.Name] && !known[name] { + assert.Failf(t, "global flag hidden", "%q defines --%s, which hides the global flag", sub.CommandPath(), f.Name) + } + if name := sub.CommandPath() + " -" + f.Shorthand; f.Shorthand != "" && globalShorthands[f.Shorthand] && !known[name] { + assert.Failf(t, "global flag hidden", "%q defines -%s, which hides the global flag", sub.CommandPath(), f.Shorthand) + } + }) + walk(sub) + } + } + walk(root) +} diff --git a/app/cli/cmd/workflow_contract_update.go b/app/cli/cmd/workflow_contract_update.go index d4785b326..7edc8b62a 100644 --- a/app/cli/cmd/workflow_contract_update.go +++ b/app/cli/cmd/workflow_contract_update.go @@ -31,7 +31,7 @@ func newWorkflowContractUpdateCmd() *cobra.Command { Short: "Update an existing contract", Long: `Update an existing contract. -Use --project to move an organization-level contract to a project, or --org to move a +Use --project to move an organization-level contract to a project, or --org-level to move a project-level contract to the organization. Only organization administrators and organization-level API tokens can move a contract.`, Example: ` # Update the contract content @@ -41,7 +41,7 @@ organization-level API tokens can move a contract.`, chainloop workflow contract update --name my-contract --project my-project # Move a project-level contract to the organization - chainloop workflow contract update --name my-contract --org`, + chainloop workflow contract update --name my-contract --org-level`, PreRunE: func(_ *cobra.Command, _ []string) error { // Validate and extract the contract name var err error @@ -72,8 +72,8 @@ organization-level API tokens can move a contract.`, cmd.Flags().StringVarP(&contractPath, "contract", "f", "", "path or URL to the contract schema") cmd.Flags().StringVar(&description, "description", "", "description of the contract") cmd.Flags().StringVar(&scope.ProjectName, "project", "", "move the contract to this project, the contract must be at the organization level") - cmd.Flags().BoolVar(&scope.Organization, "org", false, "move the contract to the organization level") - cmd.MarkFlagsMutuallyExclusive("project", "org") + cmd.Flags().BoolVar(&scope.Organization, "org-level", false, "move the contract to the organization level") + cmd.MarkFlagsMutuallyExclusive("project", "org-level") return cmd } diff --git a/app/cli/documentation/cli-reference.md b/app/cli/documentation/cli-reference.md index a5f18d0dc..7dc01808e 100644 --- a/app/cli/documentation/cli-reference.md +++ b/app/cli/documentation/cli-reference.md @@ -3748,7 +3748,7 @@ Synopsis Update an existing contract. -Use --project to move an organization-level contract to a project, or --org to move a +Use --project to move an organization-level contract to a project, or --org-level to move a project-level contract to the organization. Only organization administrators and organization-level API tokens can move a contract. @@ -3766,7 +3766,7 @@ Move an organization-level contract to a project chainloop workflow contract update --name my-contract --project my-project Move a project-level contract to the organization -chainloop workflow contract update --name my-contract --org +chainloop workflow contract update --name my-contract --org-level ``` Options @@ -3776,7 +3776,7 @@ Options --description string description of the contract -h, --help help for update --name string contract name ---org move the contract to the organization level +--org-level move the contract to the organization level --project string move the contract to this project, the contract must be at the organization level ``` @@ -3791,6 +3791,7 @@ Options inherited from parent commands --debug Enable debug/verbose logging mode -i, --insecure Skip TLS transport during connection to the control plane ($CHAINLOOP_API_INSECURE) --max-recv-msg-size int Max size in bytes for incoming gRPC messages (0 = default 33554432) ($CHAINLOOP_API_MAX_RECV_MSG_SIZE) +-n, --org string organization name -o, --output string Output format, valid options are json and table (default "table") -t, --token string API token. NOTE: Alternatively use the env variable CHAINLOOP_TOKEN -y, --yes Skip confirmation diff --git a/app/controlplane/api/controlplane/v1/workflow_contract_test.go b/app/controlplane/api/controlplane/v1/workflow_contract_test.go new file mode 100644 index 000000000..542d3bc50 --- /dev/null +++ b/app/controlplane/api/controlplane/v1/workflow_contract_test.go @@ -0,0 +1,76 @@ +// +// 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 ( + "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" +) + +// Spec issue-3644: the level of an update request is optional. When it is set, it is a project +// reference or an organization level that must be true. +func TestWorkflowContractServiceUpdateRequestScope(t *testing.T) { + const contractName = "my-contract" + projectName := "my-project" + + testCases := []struct { + desc string + req *v1.WorkflowContractServiceUpdateRequest + wantErr string + }{ + { + desc: "no scope keeps the level of the contract", + req: &v1.WorkflowContractServiceUpdateRequest{Name: contractName}, + }, + { + desc: "organization scoped set to true", + req: &v1.WorkflowContractServiceUpdateRequest{Name: contractName, Scope: &v1.WorkflowContractServiceUpdateRequest_OrganizationScoped{OrganizationScoped: true}}, + }, + { + desc: "organization scoped set to false is rejected", + req: &v1.WorkflowContractServiceUpdateRequest{Name: contractName, Scope: &v1.WorkflowContractServiceUpdateRequest_OrganizationScoped{OrganizationScoped: false}}, + wantErr: "organization_scoped", + }, + { + desc: "a project reference", + req: &v1.WorkflowContractServiceUpdateRequest{Name: contractName, Scope: &v1.WorkflowContractServiceUpdateRequest_ProjectReference{ProjectReference: &v1.IdentityReference{Name: &projectName}}}, + }, + { + desc: "an empty project reference is rejected", + req: &v1.WorkflowContractServiceUpdateRequest{Name: contractName, Scope: &v1.WorkflowContractServiceUpdateRequest_ProjectReference{ProjectReference: &v1.IdentityReference{}}}, + wantErr: "project_reference", + }, + } + + validator, err := protovalidate.New() + require.NoError(t, err) + + for _, tc := range testCases { + t.Run(tc.desc, func(t *testing.T) { + err := validator.Validate(tc.req) + if tc.wantErr != "" { + assert.ErrorContains(t, err, tc.wantErr) + return + } + + assert.NoError(t, err) + }) + } +} diff --git a/app/controlplane/pkg/biz/workflowcontract.go b/app/controlplane/pkg/biz/workflowcontract.go index 9a6d406c2..2af562972 100644 --- a/app/controlplane/pkg/biz/workflowcontract.go +++ b/app/controlplane/pkg/biz/workflowcontract.go @@ -99,6 +99,11 @@ type WorkflowContractWithVersion struct { Contract *WorkflowContract Version *WorkflowContractVersion Changed bool + // ScopeChanged reports whether the update changed the level of the contract + ScopeChanged bool + // PreviousScopedEntity is the level of the contract before an update that changed it, + // read under the contract lock. Nil means the organization level. + PreviousScopedEntity *ScopedEntity } type WorkflowContractRepo interface { @@ -473,12 +478,13 @@ func (uc *WorkflowContractUseCase) Update(ctx context.Context, orgID, name strin uc.auditorUC.Dispatch(ctx, eventPayload, &orgUUID) - // A conversion between the organization level and a project level gets its own event - if !sameContractScope(wfContractPreUpdate, c.Contract) { + // A conversion between the organization level and a project level gets its own event. + // The old level comes from the repository, which read it under the contract lock. + if c.ScopeChanged { uc.auditorUC.Dispatch(ctx, &events.WorkflowContractScopeChanged{ WorkflowContractBase: eventPayload.WorkflowContractBase, - OldScope: contractScopeForEvent(wfContractPreUpdate), - NewScope: contractScopeForEvent(c.Contract), + OldScope: contractScopeForEvent(c.PreviousScopedEntity), + NewScope: contractScopeForEvent(c.Contract.ScopedEntity), }, &orgUUID) } @@ -487,25 +493,17 @@ func (uc *WorkflowContractUseCase) Update(ctx context.Context, orgID, name strin return c, nil } -// sameContractScope reports whether both contracts are at the same level. -func sameContractScope(a, b *WorkflowContract) bool { - if a.IsProjectScoped() != b.IsProjectScoped() { - return false - } - - return !a.IsProjectScoped() || a.ScopedEntity.ID == b.ScopedEntity.ID -} - -// contractScopeForEvent returns the level of the contract, as the audit events show it. -func contractScopeForEvent(c *WorkflowContract) *events.WorkflowContractScope { - if !c.IsProjectScoped() { +// contractScopeForEvent returns a level of a contract, as the audit events show it. +// A nil scoped entity is the organization level. +func contractScopeForEvent(s *ScopedEntity) *events.WorkflowContractScope { + if s == nil || s.Type != string(ContractScopeProject) { return &events.WorkflowContractScope{Type: events.WorkflowContractScopeOrganization} } return &events.WorkflowContractScope{ Type: events.WorkflowContractScopeProject, - ProjectID: &c.ScopedEntity.ID, - ProjectName: c.ScopedEntity.Name, + ProjectID: &s.ID, + ProjectName: s.Name, } } diff --git a/app/controlplane/pkg/biz/workflowcontract_audit_test.go b/app/controlplane/pkg/biz/workflowcontract_audit_test.go index fb15cd8f0..dccd61434 100644 --- a/app/controlplane/pkg/biz/workflowcontract_audit_test.go +++ b/app/controlplane/pkg/biz/workflowcontract_audit_test.go @@ -28,62 +28,73 @@ import ( "github.com/stretchr/testify/require" ) -// stubWorkflowContractRepo returns the contract before and after an update. -// Only FindByNameInOrg and Update are exercised; any other call panics on the -// nil embedded interface. +// stubWorkflowContractRepo returns the contract that the use case reads before the update, +// and the result of the update. Only FindByNameInOrg and Update are exercised; any other +// call panics on the nil embedded interface. type stubWorkflowContractRepo struct { WorkflowContractRepo - before, after *WorkflowContract + preRead *WorkflowContract + result *WorkflowContractWithVersion } func (s *stubWorkflowContractRepo) FindByNameInOrg(_ context.Context, _ uuid.UUID, _ string) (*WorkflowContract, error) { - return s.before, nil + return s.preRead, nil } func (s *stubWorkflowContractRepo) Update(_ context.Context, _ uuid.UUID, _ string, _ *ContractUpdateOpts) (*WorkflowContractWithVersion, error) { - return &WorkflowContractWithVersion{ - Contract: s.after, - Version: &WorkflowContractVersion{ID: uuid.New(), Revision: s.after.LatestRevision}, - }, nil + return s.result, nil } // Spec issue-3644 R-008: each conversion writes an audit event with the old and the new level. +// The old level is the one that the repository saw under the contract lock, not the one read +// before the update, which a concurrent conversion can make stale. func TestWorkflowContractUpdateDispatchesScopeChanged(t *testing.T) { project := &ScopedEntity{Type: string(ContractScopeProject), ID: uuid.New(), Name: "my-project"} + otherProject := &ScopedEntity{Type: string(ContractScopeProject), ID: uuid.New(), Name: "other-project"} orgScope := &events.WorkflowContractScope{Type: events.WorkflowContractScopeOrganization} projectScope := &events.WorkflowContractScope{Type: events.WorkflowContractScopeProject, ProjectID: &project.ID, ProjectName: project.Name} + otherProjectScope := &events.WorkflowContractScope{Type: events.WorkflowContractScopeProject, ProjectID: &otherProject.ID, ProjectName: otherProject.Name} testCases := []struct { - name string - before, after *ScopedEntity - scope *ContractScopeChange + name string + // preRead is the level that the use case reads before the update + preRead *ScopedEntity + // changed, previous and after are what the repository reports + changed bool + previous, after *ScopedEntity // nil means no scope event is dispatched wantOld, wantNew *events.WorkflowContractScope }{ { name: "organization to project", + changed: true, after: project, - scope: &ContractScopeChange{ProjectID: &project.ID}, wantOld: orgScope, wantNew: projectScope, }, { - name: "project to organization", - before: project, - scope: &ContractScopeChange{}, - wantOld: projectScope, - wantNew: orgScope, + name: "project to organization", + preRead: project, + changed: true, + previous: project, + wantOld: projectScope, + wantNew: orgScope, }, { - name: "same level", - before: project, - after: project, - scope: &ContractScopeChange{ProjectID: &project.ID}, + name: "the repository did not change the level", + preRead: project, + after: project, + }, + { + name: "the old level is the one the repository saw, not the stale pre-read", + changed: true, + previous: otherProject, + wantOld: otherProjectScope, + wantNew: orgScope, }, { - name: "no level in the request", - before: project, - after: project, + name: "no event when a concurrent conversion already set the level", + after: project, }, } @@ -92,12 +103,17 @@ func TestWorkflowContractUpdateDispatchesScopeChanged(t *testing.T) { auditorUC, publisher := newRecordingAuditor() contractID := uuid.New() repo := &stubWorkflowContractRepo{ - before: &WorkflowContract{ID: contractID, Name: "my-contract", LatestRevision: 1, ScopedEntity: cloneScope(tc.before)}, - after: &WorkflowContract{ID: contractID, Name: "my-contract", LatestRevision: 1, ScopedEntity: cloneScope(tc.after)}, + preRead: &WorkflowContract{ID: contractID, Name: "my-contract", LatestRevision: 1, ScopedEntity: tc.preRead}, + result: &WorkflowContractWithVersion{ + Contract: &WorkflowContract{ID: contractID, Name: "my-contract", LatestRevision: 1, ScopedEntity: tc.after}, + Version: &WorkflowContractVersion{ID: uuid.New(), Revision: 1}, + ScopeChanged: tc.changed, + PreviousScopedEntity: tc.previous, + }, } uc := NewWorkflowContractUseCase(repo, nil, auditorUC, log.NewStdLogger(io.Discard)) - _, err := uc.Update(ctxWithAPITokenActor(context.Background()), uuid.NewString(), "my-contract", &WorkflowContractUpdateOpts{Scope: tc.scope}) + _, err := uc.Update(ctxWithAPITokenActor(context.Background()), uuid.NewString(), "my-contract", &WorkflowContractUpdateOpts{Scope: &ContractScopeChange{}}) require.NoError(t, err) var scopeEvents []json.RawMessage @@ -124,13 +140,3 @@ func TestWorkflowContractUpdateDispatchesScopeChanged(t *testing.T) { }) } } - -// cloneScope returns a copy, as the repository returns a new object on each call. -func cloneScope(s *ScopedEntity) *ScopedEntity { - if s == nil { - return nil - } - - c := *s - return &c -} diff --git a/app/controlplane/pkg/biz/workflowcontract_integration_test.go b/app/controlplane/pkg/biz/workflowcontract_integration_test.go index 6ec40ac8b..67c82919b 100644 --- a/app/controlplane/pkg/biz/workflowcontract_integration_test.go +++ b/app/controlplane/pkg/biz/workflowcontract_integration_test.go @@ -172,22 +172,27 @@ func (s *workflowContractIntegrationTestSuite) TestUpdateScope() { wantProjectID *uuid.UUID wantRevision int wantWorkflows int + // the repository reports a change of level, with the level before it + wantScopeChanged bool }{ { - name: "organization to project (R-001)", - setup: func() *biz.WorkflowContract { return newContract("org-to-project", nil) }, - scope: toProject(s.p1), - wantProjectID: &s.p1.ID, - wantRevision: 1, + name: "organization to project (R-001)", + wantScopeChanged: true, + setup: func() *biz.WorkflowContract { return newContract("org-to-project", nil) }, + scope: toProject(s.p1), + wantProjectID: &s.p1.ID, + wantRevision: 1, }, { - name: "project to organization (R-002)", - setup: func() *biz.WorkflowContract { return newContract("project-to-org", &s.p1.ID) }, - scope: toOrg, - wantRevision: 1, + name: "project to organization (R-002)", + wantScopeChanged: true, + setup: func() *biz.WorkflowContract { return newContract("project-to-org", &s.p1.ID) }, + scope: toOrg, + wantRevision: 1, }, { - name: "organization to project keeps the workflows of that project (R-003)", + name: "organization to project keeps the workflows of that project (R-003)", + wantScopeChanged: true, setup: func() *biz.WorkflowContract { c := newContract("org-to-project-with-workflows", nil) attachWorkflow(c, s.p1.Name, "wf-in-p1") @@ -199,7 +204,8 @@ func (s *workflowContractIntegrationTestSuite) TestUpdateScope() { wantWorkflows: 1, }, { - name: "project to organization keeps the workflows (R-003)", + name: "project to organization keeps the workflows (R-003)", + wantScopeChanged: true, setup: func() *biz.WorkflowContract { c := newContract("project-to-org-with-workflows", &s.p1.ID) attachWorkflow(c, s.p1.Name, "wf-in-p1-2") @@ -240,12 +246,13 @@ func (s *workflowContractIntegrationTestSuite) TestUpdateScope() { wantRevision: 1, }, { - name: "a new body in the same request creates a revision (R-007)", - setup: func() *biz.WorkflowContract { return newContract("scope-and-body", nil) }, - scope: toProject(s.p1), - rawSchema: []byte(`schemaVersion: v1`), - wantProjectID: &s.p1.ID, - wantRevision: 2, + name: "a new body in the same request creates a revision (R-007)", + wantScopeChanged: true, + setup: func() *biz.WorkflowContract { return newContract("scope-and-body", nil) }, + scope: toProject(s.p1), + rawSchema: []byte(`schemaVersion: v1`), + wantProjectID: &s.p1.ID, + wantRevision: 2, }, { name: "no scope keeps the scope (R-009)", @@ -279,6 +286,11 @@ func (s *workflowContractIntegrationTestSuite) TestUpdateScope() { } s.Require().NoError(err) + s.Equal(tc.wantScopeChanged, got.ScopeChanged) + if tc.wantScopeChanged { + s.Equal(contract.ScopedEntity, got.PreviousScopedEntity) + } + s.Equal(contract.ID, got.Contract.ID) s.Equal(contract.Name, got.Contract.Name) s.Equal(tc.wantRevision, got.Version.Revision) diff --git a/app/controlplane/pkg/data/workflowcontract.go b/app/controlplane/pkg/data/workflowcontract.go index d8848108e..d2d59a6bc 100644 --- a/app/controlplane/pkg/data/workflowcontract.go +++ b/app/controlplane/pkg/data/workflowcontract.go @@ -253,11 +253,13 @@ func (r *WorkflowContractRepo) Update(ctx context.Context, orgID uuid.UUID, name var ( lv *ent.WorkflowContractVersion workflowReferences []*biz.WorkflowRef + // the contract as it was under the lock, when the update changed its level + previous *ent.WorkflowContract ) if err = WithTx(ctx, r.data.DB, func(tx *ent.Tx) error { if opts.Scope != nil { - if err := changeContractScope(ctx, tx, orgID, contract.ID, opts.Scope); err != nil { + if previous, err = changeContractScope(ctx, tx, orgID, contract.ID, opts.Scope); err != nil { return err } } @@ -306,19 +308,28 @@ func (r *WorkflowContractRepo) Update(ctx context.Context, orgID uuid.UUID, name return nil, err } - return &biz.WorkflowContractWithVersion{ + result := &biz.WorkflowContractWithVersion{ Contract: r.entContractToBizContract(ctx, contract, lv, workflowReferences), Version: v, - }, nil + } + + if previous != nil { + result.ScopeChanged = true + result.PreviousScopedEntity = r.scopedEntity(ctx, previous) + } + + return result, nil } // changeContractScope converts the contract to the organization level or to a project level. // It locks the contract first, so a workflow change on the same contract waits until the // conversion completes, and the other way around (spec issue-3644, D-008). -func changeContractScope(ctx context.Context, tx *ent.Tx, orgID, contractID uuid.UUID, scope *biz.ContractScopeChange) error { +// When it changes the level, it returns the contract as it was under the lock. When the +// contract is already at the requested level, it returns nil. +func changeContractScope(ctx context.Context, tx *ent.Tx, orgID, contractID uuid.UUID, scope *biz.ContractScopeChange) (*ent.WorkflowContract, error) { current, err := tx.WorkflowContract.Query().Where(workflowcontract.ID(contractID)).ForUpdate().Only(ctx) if err != nil { - return fmt.Errorf("locking the contract: %w", err) + return nil, fmt.Errorf("locking the contract: %w", err) } projectScoped := current.ScopedResourceType == biz.ContractScopeProject && current.ScopedResourceID != uuid.Nil @@ -326,27 +337,31 @@ func changeContractScope(ctx context.Context, tx *ent.Tx, orgID, contractID uuid // To the organization level if scope.ProjectID == nil { if !projectScoped { - return nil + return nil, nil } - return tx.WorkflowContract.UpdateOneID(contractID).ClearScopedResourceType().ClearScopedResourceID().Exec(ctx) + if err := tx.WorkflowContract.UpdateOneID(contractID).ClearScopedResourceType().ClearScopedResourceID().Exec(ctx); err != nil { + return nil, fmt.Errorf("converting the contract to the organization level: %w", err) + } + + return current, nil } // To a project level targetID := *scope.ProjectID if projectScoped { if current.ScopedResourceID == targetID { - return nil + return nil, nil } - return biz.NewErrValidationStr("a project-level contract can not be moved to a different project") + return nil, biz.NewErrValidationStr("a project-level contract can not be moved to a different project") } exists, err := tx.Project.Query().Where(project.ID(targetID), project.OrganizationID(orgID), project.DeletedAtIsNil()).Exist(ctx) if err != nil { - return fmt.Errorf("finding the project: %w", err) + return nil, fmt.Errorf("finding the project: %w", err) } else if !exists { - return biz.NewErrNotFound("project") + return nil, biz.NewErrNotFound("project") } // Workflows of other projects can not use a project-level contract @@ -359,7 +374,7 @@ func changeContractScope(ctx context.Context, tx *ent.Tx, orgID, contractID uuid WithProject(). All(ctx) if err != nil { - return fmt.Errorf("finding the workflows of the contract: %w", err) + return nil, fmt.Errorf("finding the workflows of the contract: %w", err) } if len(others) > 0 { @@ -369,13 +384,17 @@ func changeContractScope(ctx context.Context, tx *ent.Tx, orgID, contractID uuid } slices.Sort(refs) - return biz.NewErrValidationStr(fmt.Sprintf("the contract is used by workflows of other projects, attach a different contract to them first: %s", strings.Join(refs, ", "))) + return nil, biz.NewErrValidationStr(fmt.Sprintf("the contract is used by workflows of other projects, attach a different contract to them first: %s", strings.Join(refs, ", "))) } - return tx.WorkflowContract.UpdateOneID(contractID). + if err := tx.WorkflowContract.UpdateOneID(contractID). SetScopedResourceType(biz.ContractScopeProject). SetScopedResourceID(targetID). - Exec(ctx) + Exec(ctx); err != nil { + return nil, fmt.Errorf("converting the contract to a project level: %w", err) + } + + return current, nil } func (r *WorkflowContractRepo) FindByIDInOrg(ctx context.Context, orgID, contractID uuid.UUID) (*biz.WorkflowContract, error) { @@ -543,13 +562,22 @@ func (r *WorkflowContractRepo) entContractToBizContract(ctx context.Context, w * LatestRevisionCreatedAt: toTimePtr(version.CreatedAt), WorkflowRefs: workflowReferences, Description: w.Description, + ScopedEntity: r.scopedEntity(ctx, w), + LatestRevision: version.Revision, } - if w.ScopedResourceID != uuid.Nil { - c.ScopedEntity = &biz.ScopedEntity{ - Type: string(w.ScopedResourceType), - ID: w.ScopedResourceID, - } + return c +} + +// scopedEntity returns the level of the contract. Nil means the organization level. +func (r *WorkflowContractRepo) scopedEntity(ctx context.Context, w *ent.WorkflowContract) *biz.ScopedEntity { + if w.ScopedResourceID == uuid.Nil { + return nil + } + + s := &biz.ScopedEntity{ + Type: string(w.ScopedResourceType), + ID: w.ScopedResourceID, } // preload the project name if the contract is scoped to a project @@ -557,13 +585,12 @@ func (r *WorkflowContractRepo) entContractToBizContract(ctx context.Context, w * project, err := r.data.DB.Project.Get(ctx, w.ScopedResourceID) if err != nil { r.log.Errorf("failed to get project: %w", err) - return c + return s } - c.ScopedEntity.Name = project.Name + s.Name = project.Name } - c.LatestRevision = version.Revision - return c + return s } // getWorkflowReferences get the list of workflows associated with a given contract diff --git a/docs/specs/issue-3644-contract-scope-conversion.md b/docs/specs/issue-3644-contract-scope-conversion.md index af002dd33..b7093892a 100644 --- a/docs/specs/issue-3644-contract-scope-conversion.md +++ b/docs/specs/issue-3644-contract-scope-conversion.md @@ -48,9 +48,15 @@ A workflow contract gets its level when someone creates it, and the level cannot The system MUST let an authorized caller convert an organization-level contract into a project-level contract of a project that exists in the same organization. - Done when: `chainloop wf contract update --name foo --project my-proj` succeeds, and `chainloop wf contract describe --name foo` shows the contract in project `my-proj`. -### R-002: Convert a project-level contract to organization level -The system MUST let an authorized caller convert a project-level contract into an organization-level contract. -- Done when: `chainloop wf contract update --name foo --org` succeeds, and the contract shows no project. +### ~~R-002: Convert a project-level contract to organization level~~ +Superseded by R-011. + +~~The system MUST let an authorized caller convert a project-level contract into an organization-level contract.~~ +- ~~Done when: `chainloop wf contract update --name foo --org` succeeds, and the contract shows no project.~~ + +### R-011: Convert a project-level contract to organization level +Supersedes R-002. The system MUST let an authorized caller convert a project-level contract into an organization-level contract. +- Done when: `chainloop wf contract update --name foo --org-level` succeeds, and the contract shows no project. ### R-003: Keep the contract identity A conversion MUST keep the contract ID, its name, all its revisions, and the links to all its workflows. @@ -146,13 +152,15 @@ The field is either not set (no change), a project reference, or "organization". - An optional project field, where an empty value means the organization: easy to misuse, and not clear to a reader. - Source: drafting -### D-003: CLI flags `--project` and `--org` -The update command gets `--project ` and `--org`, and the user can give only one of them. -- Why: `--project` matches the create command. `--org` matches the words that users see, "organization-level contract". -- Alternatives considered: - - `--global` in place of `--org`: "global" is a word of the code, not of the product. - - `--scope org|project` with `--project`: adds a rule ("`--project` is necessary when the scope is project") and gives nothing more with only two levels. -- Source: drafting +### ~~D-003: CLI flags `--project` and `--org`~~ +Superseded by D-009. + +~~The update command gets `--project ` and `--org`, and the user can give only one of them.~~ +- ~~Why: `--project` matches the create command. `--org` matches the words that users see, "organization-level contract".~~ +- ~~Alternatives considered:~~ + - ~~`--global` in place of `--org`: "global" is a word of the code, not of the product.~~ + - ~~`--scope org|project` with `--project`: adds a rule ("`--project` is necessary when the scope is project") and gives nothing more with only two levels.~~ +- ~~Source: drafting~~ ### D-004: The same callers that manage organization-level contracts can convert Organization owners, organization admins, and organization-level API tokens can convert. Project-level callers cannot convert, in either direction. @@ -189,6 +197,19 @@ A conversion and each workflow change that sets a contract lock the contract, an - Accept the race: conversions are rare and admin-only, but the result is a workflow that cannot get its contract. - Source: [PR #3789 review](https://github.com/chainloop-dev/chainloop/pull/3789#discussion_r4490911182) +### D-009: CLI flags `--project` and `--org-level` +Supersedes D-003. The update command gets `--project ` and `--org-level`, and the user can give only one of them. +- Why: all commands of the CLI already have a global `--org` flag that selects the organization. A local `--org` on the update command hides that flag. +- Alternatives considered: + - `--organization-scoped`: matches the API field, but it is long. + - `--global`: "global" is a word of the code, not of the product. +- Source: [PR #3794 review](https://github.com/chainloop-dev/chainloop/pull/3794#discussion_r4492196064) + +### D-010: The audit event uses the level read under the lock +The old level in the audit event is the level that the conversion read after it locked the contract. The system writes the event only when the conversion changed the level. +- Why: a level read before the lock can be old when two conversions run at the same time. Then the event shows a wrong old level, or it records a change that did not occur. +- Source: [PR #3794 review](https://github.com/chainloop-dev/chainloop/pull/3794#discussion_r4492196071) + ## Open Questions None. From c83d5b82e7314849829efdf7513bb2d778887596 Mon Sep 17 00:00:00 2001 From: Jose Ignacio Paris Prieto Date: Sat, 7 Nov 2026 00:43:14 +0100 Subject: [PATCH 3/3] fix(contracts): read both levels of the scope audit event under the lock The repository now reports the level before and after a conversion, both read while the conversion holds the contract lock, so a later conversion can not change the new level that the audit event records. Refs #3644 Assisted-by: Claude Code Signed-off-by: Jose Ignacio Paris Prieto Chainloop-Trace-Sessions: bc6fbb4d-3bf8-4fd0-b81e-10aa03bf1e58 --- app/controlplane/pkg/biz/workflowcontract.go | 21 ++++---- .../pkg/biz/workflowcontract_audit_test.go | 47 +++++++++-------- .../biz/workflowcontract_integration_test.go | 9 ++-- app/controlplane/pkg/data/workflowcontract.go | 50 ++++++++++--------- .../issue-3644-contract-scope-conversion.md | 8 +-- 5 files changed, 75 insertions(+), 60 deletions(-) diff --git a/app/controlplane/pkg/biz/workflowcontract.go b/app/controlplane/pkg/biz/workflowcontract.go index 2af562972..b4e66b51e 100644 --- a/app/controlplane/pkg/biz/workflowcontract.go +++ b/app/controlplane/pkg/biz/workflowcontract.go @@ -99,11 +99,14 @@ type WorkflowContractWithVersion struct { Contract *WorkflowContract Version *WorkflowContractVersion Changed bool - // ScopeChanged reports whether the update changed the level of the contract - ScopeChanged bool - // PreviousScopedEntity is the level of the contract before an update that changed it, - // read under the contract lock. Nil means the organization level. - PreviousScopedEntity *ScopedEntity + // ScopeChange is the change of level that the update made, nil when it did not change it + ScopeChange *ContractScopeTransition +} + +// ContractScopeTransition is a change of the level of a contract. The repository reads both +// levels under the contract lock. A nil scoped entity is the organization level. +type ContractScopeTransition struct { + From, To *ScopedEntity } type WorkflowContractRepo interface { @@ -479,12 +482,12 @@ func (uc *WorkflowContractUseCase) Update(ctx context.Context, orgID, name strin uc.auditorUC.Dispatch(ctx, eventPayload, &orgUUID) // A conversion between the organization level and a project level gets its own event. - // The old level comes from the repository, which read it under the contract lock. - if c.ScopeChanged { + // Both levels come from the repository, which read them under the contract lock. + if c.ScopeChange != nil { uc.auditorUC.Dispatch(ctx, &events.WorkflowContractScopeChanged{ WorkflowContractBase: eventPayload.WorkflowContractBase, - OldScope: contractScopeForEvent(c.PreviousScopedEntity), - NewScope: contractScopeForEvent(c.Contract.ScopedEntity), + OldScope: contractScopeForEvent(c.ScopeChange.From), + NewScope: contractScopeForEvent(c.ScopeChange.To), }, &orgUUID) } diff --git a/app/controlplane/pkg/biz/workflowcontract_audit_test.go b/app/controlplane/pkg/biz/workflowcontract_audit_test.go index dccd61434..aab892f76 100644 --- a/app/controlplane/pkg/biz/workflowcontract_audit_test.go +++ b/app/controlplane/pkg/biz/workflowcontract_audit_test.go @@ -46,8 +46,8 @@ func (s *stubWorkflowContractRepo) Update(_ context.Context, _ uuid.UUID, _ stri } // Spec issue-3644 R-008: each conversion writes an audit event with the old and the new level. -// The old level is the one that the repository saw under the contract lock, not the one read -// before the update, which a concurrent conversion can make stale. +// Both levels are the ones that the repository saw under the contract lock, not the one read +// before the update or the one read after the commit, which a concurrent conversion can make stale. func TestWorkflowContractUpdateDispatchesScopeChanged(t *testing.T) { project := &ScopedEntity{Type: string(ContractScopeProject), ID: uuid.New(), Name: "my-project"} otherProject := &ScopedEntity{Type: string(ContractScopeProject), ID: uuid.New(), Name: "other-project"} @@ -59,26 +59,26 @@ func TestWorkflowContractUpdateDispatchesScopeChanged(t *testing.T) { name string // preRead is the level that the use case reads before the update preRead *ScopedEntity - // changed, previous and after are what the repository reports - changed bool - previous, after *ScopedEntity + // after is the level of the returned contract, read after the commit + after *ScopedEntity + // change is the change of level that the repository reports + change *ContractScopeTransition // nil means no scope event is dispatched wantOld, wantNew *events.WorkflowContractScope }{ { name: "organization to project", - changed: true, after: project, + change: &ContractScopeTransition{To: project}, wantOld: orgScope, wantNew: projectScope, }, { - name: "project to organization", - preRead: project, - changed: true, - previous: project, - wantOld: projectScope, - wantNew: orgScope, + name: "project to organization", + preRead: project, + change: &ContractScopeTransition{From: project}, + wantOld: projectScope, + wantNew: orgScope, }, { name: "the repository did not change the level", @@ -86,11 +86,17 @@ func TestWorkflowContractUpdateDispatchesScopeChanged(t *testing.T) { after: project, }, { - name: "the old level is the one the repository saw, not the stale pre-read", - changed: true, - previous: otherProject, - wantOld: otherProjectScope, - wantNew: orgScope, + name: "the old level is the one the repository saw, not the stale pre-read", + change: &ContractScopeTransition{From: otherProject}, + wantOld: otherProjectScope, + wantNew: orgScope, + }, + { + name: "the new level is the one the repository set, not the read after the commit", + after: otherProject, + change: &ContractScopeTransition{To: project}, + wantOld: orgScope, + wantNew: projectScope, }, { name: "no event when a concurrent conversion already set the level", @@ -105,10 +111,9 @@ func TestWorkflowContractUpdateDispatchesScopeChanged(t *testing.T) { repo := &stubWorkflowContractRepo{ preRead: &WorkflowContract{ID: contractID, Name: "my-contract", LatestRevision: 1, ScopedEntity: tc.preRead}, result: &WorkflowContractWithVersion{ - Contract: &WorkflowContract{ID: contractID, Name: "my-contract", LatestRevision: 1, ScopedEntity: tc.after}, - Version: &WorkflowContractVersion{ID: uuid.New(), Revision: 1}, - ScopeChanged: tc.changed, - PreviousScopedEntity: tc.previous, + Contract: &WorkflowContract{ID: contractID, Name: "my-contract", LatestRevision: 1, ScopedEntity: tc.after}, + Version: &WorkflowContractVersion{ID: uuid.New(), Revision: 1}, + ScopeChange: tc.change, }, } uc := NewWorkflowContractUseCase(repo, nil, auditorUC, log.NewStdLogger(io.Discard)) diff --git a/app/controlplane/pkg/biz/workflowcontract_integration_test.go b/app/controlplane/pkg/biz/workflowcontract_integration_test.go index 67c82919b..d29eb1973 100644 --- a/app/controlplane/pkg/biz/workflowcontract_integration_test.go +++ b/app/controlplane/pkg/biz/workflowcontract_integration_test.go @@ -172,7 +172,7 @@ func (s *workflowContractIntegrationTestSuite) TestUpdateScope() { wantProjectID *uuid.UUID wantRevision int wantWorkflows int - // the repository reports a change of level, with the level before it + // the repository reports a change of level, with the levels before and after it wantScopeChanged bool }{ { @@ -286,9 +286,12 @@ func (s *workflowContractIntegrationTestSuite) TestUpdateScope() { } s.Require().NoError(err) - s.Equal(tc.wantScopeChanged, got.ScopeChanged) if tc.wantScopeChanged { - s.Equal(contract.ScopedEntity, got.PreviousScopedEntity) + s.Require().NotNil(got.ScopeChange) + s.Equal(contract.ScopedEntity, got.ScopeChange.From) + s.Equal(got.Contract.ScopedEntity, got.ScopeChange.To) + } else { + s.Nil(got.ScopeChange) } s.Equal(contract.ID, got.Contract.ID) diff --git a/app/controlplane/pkg/data/workflowcontract.go b/app/controlplane/pkg/data/workflowcontract.go index d2d59a6bc..cb25cfc77 100644 --- a/app/controlplane/pkg/data/workflowcontract.go +++ b/app/controlplane/pkg/data/workflowcontract.go @@ -253,13 +253,13 @@ func (r *WorkflowContractRepo) Update(ctx context.Context, orgID uuid.UUID, name var ( lv *ent.WorkflowContractVersion workflowReferences []*biz.WorkflowRef - // the contract as it was under the lock, when the update changed its level - previous *ent.WorkflowContract + // the contract before and after the change of level, read under the lock + previous, converted *ent.WorkflowContract ) if err = WithTx(ctx, r.data.DB, func(tx *ent.Tx) error { if opts.Scope != nil { - if previous, err = changeContractScope(ctx, tx, orgID, contract.ID, opts.Scope); err != nil { + if previous, converted, err = changeContractScope(ctx, tx, orgID, contract.ID, opts.Scope); err != nil { return err } } @@ -314,8 +314,10 @@ func (r *WorkflowContractRepo) Update(ctx context.Context, orgID uuid.UUID, name } if previous != nil { - result.ScopeChanged = true - result.PreviousScopedEntity = r.scopedEntity(ctx, previous) + result.ScopeChange = &biz.ContractScopeTransition{ + From: r.scopedEntity(ctx, previous), + To: r.scopedEntity(ctx, converted), + } } return result, nil @@ -324,12 +326,12 @@ func (r *WorkflowContractRepo) Update(ctx context.Context, orgID uuid.UUID, name // changeContractScope converts the contract to the organization level or to a project level. // It locks the contract first, so a workflow change on the same contract waits until the // conversion completes, and the other way around (spec issue-3644, D-008). -// When it changes the level, it returns the contract as it was under the lock. When the -// contract is already at the requested level, it returns nil. -func changeContractScope(ctx context.Context, tx *ent.Tx, orgID, contractID uuid.UUID, scope *biz.ContractScopeChange) (*ent.WorkflowContract, error) { +// When it changes the level, it returns the contract before and after the change, both read +// under the lock. When the contract is already at the requested level, it returns nil for both. +func changeContractScope(ctx context.Context, tx *ent.Tx, orgID, contractID uuid.UUID, scope *biz.ContractScopeChange) (previous, converted *ent.WorkflowContract, err error) { current, err := tx.WorkflowContract.Query().Where(workflowcontract.ID(contractID)).ForUpdate().Only(ctx) if err != nil { - return nil, fmt.Errorf("locking the contract: %w", err) + return nil, nil, fmt.Errorf("locking the contract: %w", err) } projectScoped := current.ScopedResourceType == biz.ContractScopeProject && current.ScopedResourceID != uuid.Nil @@ -337,31 +339,32 @@ func changeContractScope(ctx context.Context, tx *ent.Tx, orgID, contractID uuid // To the organization level if scope.ProjectID == nil { if !projectScoped { - return nil, nil + return nil, nil, nil } - if err := tx.WorkflowContract.UpdateOneID(contractID).ClearScopedResourceType().ClearScopedResourceID().Exec(ctx); err != nil { - return nil, fmt.Errorf("converting the contract to the organization level: %w", err) + converted, err = tx.WorkflowContract.UpdateOneID(contractID).ClearScopedResourceType().ClearScopedResourceID().Save(ctx) + if err != nil { + return nil, nil, fmt.Errorf("converting the contract to the organization level: %w", err) } - return current, nil + return current, converted, nil } // To a project level targetID := *scope.ProjectID if projectScoped { if current.ScopedResourceID == targetID { - return nil, nil + return nil, nil, nil } - return nil, biz.NewErrValidationStr("a project-level contract can not be moved to a different project") + return nil, nil, biz.NewErrValidationStr("a project-level contract can not be moved to a different project") } exists, err := tx.Project.Query().Where(project.ID(targetID), project.OrganizationID(orgID), project.DeletedAtIsNil()).Exist(ctx) if err != nil { - return nil, fmt.Errorf("finding the project: %w", err) + return nil, nil, fmt.Errorf("finding the project: %w", err) } else if !exists { - return nil, biz.NewErrNotFound("project") + return nil, nil, biz.NewErrNotFound("project") } // Workflows of other projects can not use a project-level contract @@ -374,7 +377,7 @@ func changeContractScope(ctx context.Context, tx *ent.Tx, orgID, contractID uuid WithProject(). All(ctx) if err != nil { - return nil, fmt.Errorf("finding the workflows of the contract: %w", err) + return nil, nil, fmt.Errorf("finding the workflows of the contract: %w", err) } if len(others) > 0 { @@ -384,17 +387,18 @@ func changeContractScope(ctx context.Context, tx *ent.Tx, orgID, contractID uuid } slices.Sort(refs) - return nil, biz.NewErrValidationStr(fmt.Sprintf("the contract is used by workflows of other projects, attach a different contract to them first: %s", strings.Join(refs, ", "))) + return nil, nil, biz.NewErrValidationStr(fmt.Sprintf("the contract is used by workflows of other projects, attach a different contract to them first: %s", strings.Join(refs, ", "))) } - if err := tx.WorkflowContract.UpdateOneID(contractID). + converted, err = tx.WorkflowContract.UpdateOneID(contractID). SetScopedResourceType(biz.ContractScopeProject). SetScopedResourceID(targetID). - Exec(ctx); err != nil { - return nil, fmt.Errorf("converting the contract to a project level: %w", err) + Save(ctx) + if err != nil { + return nil, nil, fmt.Errorf("converting the contract to a project level: %w", err) } - return current, nil + return current, converted, nil } func (r *WorkflowContractRepo) FindByIDInOrg(ctx context.Context, orgID, contractID uuid.UUID) (*biz.WorkflowContract, error) { diff --git a/docs/specs/issue-3644-contract-scope-conversion.md b/docs/specs/issue-3644-contract-scope-conversion.md index b7093892a..d8c6da47a 100644 --- a/docs/specs/issue-3644-contract-scope-conversion.md +++ b/docs/specs/issue-3644-contract-scope-conversion.md @@ -205,10 +205,10 @@ Supersedes D-003. The update command gets `--project ` and `--org-level`, - `--global`: "global" is a word of the code, not of the product. - Source: [PR #3794 review](https://github.com/chainloop-dev/chainloop/pull/3794#discussion_r4492196064) -### D-010: The audit event uses the level read under the lock -The old level in the audit event is the level that the conversion read after it locked the contract. The system writes the event only when the conversion changed the level. -- Why: a level read before the lock can be old when two conversions run at the same time. Then the event shows a wrong old level, or it records a change that did not occur. -- Source: [PR #3794 review](https://github.com/chainloop-dev/chainloop/pull/3794#discussion_r4492196071) +### D-010: The audit event uses the levels read under the lock +The old level and the new level in the audit event are the levels that the conversion read and set while it held the lock on the contract. The system writes the event only when the conversion changed the level. +- Why: a level read before the lock or after the commit can be wrong when two conversions run at the same time. Then the event shows a wrong level, or it records a change that did not occur. +- Source: [PR #3794 review](https://github.com/chainloop-dev/chainloop/pull/3794#discussion_r4492196071), [PR #3794 review](https://github.com/chainloop-dev/chainloop/pull/3794#discussion_r4492659279) ## Open Questions