From a5119b9362f3ee085fa30a2f3b5587e5f4d27223 Mon Sep 17 00:00:00 2001 From: Javier Rodriguez Date: Wed, 18 Nov 2026 09:27:15 +0000 Subject: [PATCH] fix(controlplane): rewrite stored contracts with a null spec to `spec: {}` Since protoyaml v0.8.0 (v1.135.3), a message field set to null in YAML stays unset. A stored YAML contract with a null top-level spec then fails validation each time the control plane reads it, and in the CLI attestation init. Add a migration that rewrites the value to `spec: {}`, which keeps the meaning that the text had before. New contracts with a null spec stay invalid, as in protojson. The migration uses E'' strings, so that it gives the same result when standard_conforming_strings is off. Also use `spec: {}` in the empty contract example of the docs. Assisted-by: Claude Code Signed-off-by: Javier Rodriguez Chainloop-Trace-Sessions: b247aa60-56f4-4d40-a70a-63bdfe94f9eb --- ...ct_null_spec_migration_integration_test.go | 137 ++++++++++++++++++ .../ent/migrate/migrations/20261117162118.sql | 35 +++++ .../pkg/data/ent/migrate/migrations/atlas.sum | 3 +- docs/examples/contracts/empty/generic.yaml | 2 +- 4 files changed, 175 insertions(+), 2 deletions(-) create mode 100644 app/controlplane/pkg/data/contract_null_spec_migration_integration_test.go create mode 100644 app/controlplane/pkg/data/ent/migrate/migrations/20261117162118.sql diff --git a/app/controlplane/pkg/data/contract_null_spec_migration_integration_test.go b/app/controlplane/pkg/data/contract_null_spec_migration_integration_test.go new file mode 100644 index 000000000..47b049d4e --- /dev/null +++ b/app/controlplane/pkg/data/contract_null_spec_migration_integration_test.go @@ -0,0 +1,137 @@ +// +// Copyright 2026 The Chainloop Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package data_test + +import ( + "context" + "os" + "testing" + + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/biz" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/biz/testhelpers" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/unmarshal" + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const contractNullSpecMigration = "ent/migrate/migrations/20261117162118.sql" + +// Since protoyaml v0.8.0, a YAML contract with a null top-level spec fails validation on read. +// The migration rewrites the stored value to `spec: {}`, which is what the text meant before. +func TestContractNullSpecMigration(t *testing.T) { + if !testhelpers.IntegrationTestsEnabled() { + t.Skip() + } + + tu := testhelpers.NewTestingUseCases(t) + defer tu.DB.Close(t) + ctx := context.Background() + + const header = "apiVersion: chainloop.dev/v1\nkind: Contract\nmetadata:\n name: c\n" + testCases := []struct { + name string + format unmarshal.RawFormat + body string + // want is the body after the migration. Empty means no change. + want string + }{ + { + name: "comment line and no newline at the end", + body: "# This is the default empty contract\n" + header + "spec:", + want: "# This is the default empty contract\n" + header + "spec: {}", + }, + { + name: "empty contract of the docs example", + body: header + "spec:\n", + want: header + "spec: {}\n", + }, + {name: "explicit null", body: header + "spec: null\n", want: header + "spec: {}\n"}, + {name: "tilde with a comment", body: header + "spec: ~ # nothing\n", want: header + "spec: {} # nothing\n"}, + {name: "comment only", body: header + "spec: # nothing\n", want: header + "spec: {} # nothing\n"}, + {name: "trailing spaces", body: header + "spec: \n", want: header + "spec: {}\n"}, + { + name: "CRLF line endings", + body: "apiVersion: chainloop.dev/v1\r\nkind: Contract\r\nmetadata:\r\n name: c\r\nspec:\r\n", + want: "apiVersion: chainloop.dev/v1\r\nkind: Contract\r\nmetadata:\r\n name: c\r\nspec: {}\r\n", + }, + {name: "top-level comment after it", body: header + "spec:\n\n# end\n", want: header + "spec: {}\n\n# end\n"}, + { + name: "indented comment and nothing else after it", + body: header + "spec:\n # no materials yet\n", + want: header + "spec: {}\n # no materials yet\n", + }, + { + name: "before another top-level key", + body: "apiVersion: chainloop.dev/v1\nkind: Contract\nspec:\nmetadata:\n name: c\n", + want: "apiVersion: chainloop.dev/v1\nkind: Contract\nspec: {}\nmetadata:\n name: c\n", + }, + {name: "spec with fields", body: header + "spec:\n materials:\n - name: a\n type: ARTIFACT\n"}, + {name: "spec with a comment before its fields", body: header + "spec:\n # materials\n materials: []\n"}, + {name: "empty spec", body: header + "spec: {}\n"}, + {name: "nested spec key", body: "apiVersion: chainloop.dev/v1\nkind: Contract\nmetadata:\n name: c\n spec:\nspec: {}\n"}, + {name: "v1 contract", body: "schemaVersion: v1\nrunner:\n type: GITHUB_ACTION\n"}, + { + name: "JSON is not changed", + format: unmarshal.RawFormatJSON, + body: `{"apiVersion":"chainloop.dev/v1","kind":"Contract","metadata":{"name":"c"},"spec":null}`, + }, + {name: "not valid UTF-8 is skipped", body: header + "spec:\n# \xff\n"}, + } + + ids := make([]uuid.UUID, len(testCases)) + for i, tc := range testCases { + format := tc.format + if format == "" { + format = unmarshal.RawFormatYAML + } + row, err := tu.Data.DB.WorkflowContractVersion.Create().SetRawBody([]byte(tc.body)).SetRawBodyFormat(format).Save(ctx) + require.NoError(t, err) + ids[i] = row.ID + } + + migration, err := os.ReadFile(contractNullSpecMigration) + require.NoError(t, err) + // The first run uses the legacy string syntax, where a backslash in '...' is an escape. + // The second run uses the default syntax, and it must change nothing. + conn, err := tu.Data.SQLDB.Conn(ctx) + require.NoError(t, err) + defer conn.Close() + for _, conforming := range []string{"off", "on"} { + _, err = conn.ExecContext(ctx, "SET standard_conforming_strings = "+conforming) + require.NoError(t, err) + _, err = conn.ExecContext(ctx, string(migration)) + require.NoError(t, err) + } + + for i, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + row, err := tu.Data.DB.WorkflowContractVersion.Get(ctx, ids[i]) + require.NoError(t, err) + + if tc.want == "" { + assert.Equal(t, tc.body, string(row.RawBody)) + return + } + + assert.Equal(t, tc.want, string(row.RawBody)) + _, err = biz.UnmarshalAndValidateRawContract([]byte(tc.body), unmarshal.RawFormatYAML) + require.Error(t, err, "the stored text must fail before the migration") + _, err = biz.UnmarshalAndValidateRawContract(row.RawBody, unmarshal.RawFormatYAML) + require.NoError(t, err, "the migrated text must be a valid contract") + }) + } +} diff --git a/app/controlplane/pkg/data/ent/migrate/migrations/20261117162118.sql b/app/controlplane/pkg/data/ent/migrate/migrations/20261117162118.sql new file mode 100644 index 000000000..f3be2d392 --- /dev/null +++ b/app/controlplane/pkg/data/ent/migrate/migrations/20261117162118.sql @@ -0,0 +1,35 @@ +-- Since protoyaml v0.8.0 (Chainloop v1.135.3), a message field set to null in YAML stays unset. +-- A stored YAML contract with a null top-level spec (`spec:`, `spec: null` or `spec: ~`) then fails +-- validation each time the control plane reads it. Before v1.135.3, the same text gave an empty spec. +-- This rewrites the value to `spec: {}`, which keeps that meaning. Rows that are not UTF-8 stay as they are. +DO $$ +DECLARE + r record; + doc text; + fixed text; +BEGIN + FOR r IN + SELECT "id", "raw_body" FROM "workflow_contract_versions" + WHERE "raw_body_format" = 'yaml' AND position('spec:'::bytea IN "raw_body") > 0 + LOOP + BEGIN + doc := convert_from(r.raw_body, 'UTF8'); + EXCEPTION WHEN character_not_in_repertoire OR untranslatable_character THEN + CONTINUE; + END; + + -- E'' strings keep the backslashes when standard_conforming_strings is off. + -- `spec: null` or `spec: ~`, with an optional comment + fixed := regexp_replace(doc, + E'^spec:[ \\t]+(?:null|Null|NULL|~)([ \\t]+#[^\\r\\n]*)?[ \\t]*(\\r?)$', + E'spec: {}\\1\\2', 'n'); + -- `spec:` with no indented content line after it + fixed := regexp_replace(fixed, + E'^spec:([ \\t]+#[^\\r\\n]*)?[ \\t]*(\\r?)$(?!\\n(?:[ \\t]*(?:#[^\\r\\n]*)?\\r?\\n)*[ \\t]+[^ \\t\\r\\n#])', + E'spec: {}\\1\\2', 'n'); + + IF fixed <> doc THEN + UPDATE "workflow_contract_versions" SET "raw_body" = convert_to(fixed, 'UTF8') WHERE "id" = r.id; + END IF; + END LOOP; +END $$; diff --git a/app/controlplane/pkg/data/ent/migrate/migrations/atlas.sum b/app/controlplane/pkg/data/ent/migrate/migrations/atlas.sum index d66088c29..a7e2c006b 100644 --- a/app/controlplane/pkg/data/ent/migrate/migrations/atlas.sum +++ b/app/controlplane/pkg/data/ent/migrate/migrations/atlas.sum @@ -1,4 +1,4 @@ -h1:hWv3uPoEHIMT147AEfHNRFZ7uMnYVlKAVQACoFjPAoE= +h1:4KMWUuBSeBXXhOyu1wmPspCWeaT/kyYJdwYewEOc6JU= 20230706165452_init-schema.sql h1:VvqbNFEQnCvUVyj2iDYVQQxDM0+sSXqocpt/5H64k8M= 20230710111950-cas-backend.sql h1:A8iBuSzZIEbdsv9ipBtscZQuaBp3V5/VMw7eZH6GX+g= 20230712094107-cas-backends-workflow-runs.sql h1:a5rzxpVGyd56nLRSsKrmCFc9sebg65RWzLghKHh5xvI= @@ -146,3 +146,4 @@ h1:hWv3uPoEHIMT147AEfHNRFZ7uMnYVlKAVQACoFjPAoE= 20261015173225.sql h1:s5wTFJqcXx+cGUPpzyY93wP/IuizLaQ/9rP/VqtamRE= 20261116124542.sql h1:PNFvP+qcO1URsP9QsKGpAwaAL9m7yP7bzi/8SHk6yNs= 20261116124543.sql h1:r+8IOuLFQ3iMrQjYN8hPGxItVJu/bidc0/yeEUe6RFQ= +20261117162118.sql h1:kihy12JzE5ELo0Jy79LjMs8X4BBgmCjsh8Q1kpFp60c= diff --git a/docs/examples/contracts/empty/generic.yaml b/docs/examples/contracts/empty/generic.yaml index 34df99394..5f099fa17 100644 --- a/docs/examples/contracts/empty/generic.yaml +++ b/docs/examples/contracts/empty/generic.yaml @@ -4,4 +4,4 @@ kind: Contract metadata: name: generic description: Empty Chainloop contract valid for any runner type -spec: +spec: {}