Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 20 additions & 4 deletions cmd/kosli/attestCustom.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,19 @@ type CustomAttestationPayload struct {

type attestCustomOptions struct {
*CommonAttestationOptions
attestationDataFile string
payload CustomAttestationPayload
attestationDataFile string
attestationDataAsList bool
payload CustomAttestationPayload
}

const attestCustomShortDesc = `Report a custom attestation to an artifact or a trail in a Kosli flow. `

const attestCustomLongDesc = attestCustomShortDesc + `
The name of the custom attestation type is specified using the ^--type^ flag.
The path to the JSON file the custom type will evaluate is specified using the ^--attestation-data^ flag.
The path to the JSON or YAML file the custom type will evaluate is specified using the ^--attestation-data^ flag.
A ^.yaml^ or ^.yml^ file is converted to JSON before it is sent: dates and timestamps stay strings exactly as written,
^yes^, ^no^, ^on^ and ^off^ stay strings, and aliases and merge keys are resolved. Duplicate keys are an error.
A YAML file with several documents needs ^--attestation-data-as-list^, which sends the documents as a JSON list.
` + attestationBindingDesc + `

` + kosliIgnoreDesc + `
Expand Down Expand Up @@ -84,6 +88,17 @@ kosli attest custom \
--attachments yourAttachmentPathName \
--api-token yourAPIToken \
--org yourOrgName

# report a custom attestation about a trail from a multi-document YAML file (sent as a JSON list, one item per document):
kosli attest custom \
--type customTypeName \
--name yourAttestationName \
--attestation-data yourYamlFilePath \
--attestation-data-as-list \
--flow yourFlowName \
--trail yourTrailName \
--api-token yourAPIToken \
--org yourOrgName
`

func newAttestCustomCmd(out io.Writer) *cobra.Command {
Expand Down Expand Up @@ -141,6 +156,7 @@ func newAttestCustomCmd(out io.Writer) *cobra.Command {
addAttestationFlags(cmd, o.CommonAttestationOptions, o.payload.CommonAttestationPayload, ci)
cmd.Flags().StringVar(&o.payload.TypeName, "type", "", attestationCustomTypeNameFlag)
cmd.Flags().StringVar(&o.attestationDataFile, "attestation-data", "", attestationCustomDataFileFlag)
cmd.Flags().BoolVar(&o.attestationDataAsList, "attestation-data-as-list", false, attestationCustomDataAsListFlag)

err := RequireFlags(cmd, []string{"type", "attestation-data", "flow", "trail", "name"})
if err != nil {
Expand All @@ -156,7 +172,7 @@ func (o *attestCustomOptions) run(args []string) error {
return err
}

o.payload.AttestationData, err = LoadJsonData(o.attestationDataFile)
o.payload.AttestationData, err = LoadAttestationData(o.attestationDataFile, o.attestationDataAsList)
if err != nil {
return fmt.Errorf("failed to load attestation data. %s", err)
}
Expand Down
31 changes: 31 additions & 0 deletions cmd/kosli/attestCustom_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,37 @@ func (suite *AttestCustomCommandTestSuite) TestAttestCustomCmd() {
cmd: fmt.Sprintf("attest custom --name bar --annotate foo.baz=bar %s", suite.defaultKosliArguments),
golden: "Error: --annotate flag should be in the format key=value. Invalid key: 'foo.baz'. Key can only contain [A-Za-z0-9_]\n",
},
{
name: "can attest custom with YAML attestation data",
cmd: fmt.Sprintf("attest custom --name bar %s --attestation-data testdata/person-type-data-example.yaml", suite.defaultKosliArguments),
golden: "custom:person attestation 'bar' is reported to trail: test-321\n",
},
{
name: "dry-run prints YAML attestation data as the converted JSON",
cmd: fmt.Sprintf("attest custom --name bar %s --attestation-data testdata/person-type-data-example.yaml --dry-run", suite.defaultKosliArguments),
goldenRegex: `(?s)"attestation_data": \{\s+"age": 34,\s+"born": "1990-05-17",\s+"name": "Jane"\s+\}`,
},
{
wantError: true,
name: "fails when a YAML file has several documents and --attestation-data-as-list is not set",
cmd: fmt.Sprintf("attest custom --name bar %s --attestation-data testdata/backstage-catalog-info.yaml", suite.defaultKosliArguments),
golden: "Error: failed to load attestation data. testdata/backstage-catalog-info.yaml contains 4 YAML documents. Use --attestation-data-as-list to send them as a list\n",
},
{
name: "can attest custom with a multi-document YAML file as a list",
cmd: fmt.Sprintf("attest custom --name bar %s --attestation-data testdata/backstage-catalog-info.yaml --attestation-data-as-list", suite.defaultKosliArguments),
golden: "custom:person attestation 'bar' is reported to trail: test-321\n",
},
{
name: "dry-run prints a multi-document YAML file as a root-level list",
cmd: fmt.Sprintf("attest custom --name bar %s --attestation-data testdata/backstage-catalog-info.yaml --attestation-data-as-list --dry-run", suite.defaultKosliArguments),
goldenRegex: `(?s)"attestation_data": \[\s+\{\s+"apiVersion": "backstage.io/v1alpha1",\s+"kind": "System",.*"kind": "Component",.*"kind": "Component",.*"kind": "Group",`,
},
{
name: "dry-run wraps JSON attestation data in a list with --attestation-data-as-list",
cmd: fmt.Sprintf("attest custom --name bar --attestation-data-as-list --dry-run %s", suite.defaultKosliArguments),
goldenRegex: `(?s)"attestation_data": \[\s+\{\s+"age": 34,\s+"name": "Jane"\s+\}\s+\]`,
},
{
wantError: true,
name: "fails when --name has invalid dot format",
Expand Down
198 changes: 198 additions & 0 deletions cmd/kosli/attestationData_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
package main

import (
"bytes"
"encoding/json"
"os"
"path/filepath"
"testing"

"github.com/stretchr/testify/require"
)

func writeAttestationDataFile(t *testing.T, name, content string) string {
t.Helper()
path := filepath.Join(t.TempDir(), name)
require.NoError(t, os.WriteFile(path, []byte(content), 0o600))
return path
}

func TestLoadAttestationData(t *testing.T) {
for _, tc := range []struct {
name string
filename string
content string
asList bool
wantJSON string
wantErr string
}{
{
name: "a .yaml file with one document is sent as that document",
filename: "data.yaml",
content: "name: Jane\nborn: 1990-05-17\n",
wantJSON: `{"born":"1990-05-17","name":"Jane"}`,
},
{
name: "a .yml file is YAML too",
filename: "data.yml",
content: "- a\n- b\n",
wantJSON: `["a","b"]`,
},
{
name: "the extension is matched case-insensitively",
filename: "DATA.YAML",
content: "name: Jane\n",
wantJSON: `{"name":"Jane"}`,
},
{
name: "a .json file takes the JSON path",
filename: "data.json",
content: `{"name": "Jane", "age": 34}`,
wantJSON: `{"age":34,"name":"Jane"}`,
},
{
name: "a file with no extension takes the JSON path",
filename: "data",
content: `[1, 2]`,
wantJSON: `[1,2]`,
},
{
name: "YAML in a file without a YAML extension is not converted",
filename: "data.txt",
content: "name: Jane\n",
wantErr: "data.txt does not contain a valid JSON",
},
{
name: "several YAML documents is an error that names the flag",
filename: "data.yaml",
content: "a: 1\n---\nb: 2\n",
wantErr: "data.yaml contains 2 YAML documents. Use --attestation-data-as-list to send them as a list",
},
{
name: "empty documents are not counted",
filename: "data.yaml",
content: "---\n---\na: 1\n---\n~\n",
wantJSON: `{"a":1}`,
},
{
name: "an empty YAML file is an error",
filename: "data.yaml",
content: "",
wantErr: "data.yaml contains no YAML documents. Use --attestation-data-as-list to send an empty list",
},
{
name: "invalid YAML names the file",
filename: "data.yaml",
content: "a: 1\na: 2\n",
wantErr: "data.yaml does not contain valid YAML: ",
},
{
name: "as a list, one YAML document is a list of one",
filename: "data.yaml",
content: "a: 1\n",
asList: true,
wantJSON: `[{"a":1}]`,
},
{
name: "as a list, several YAML documents are one item each, in file order",
filename: "data.yaml",
content: "b: 2\n---\na: 1\n---\n- x\n",
asList: true,
wantJSON: `[{"b":2},{"a":1},["x"]]`,
},
{
name: "as a list, empty documents between real ones are dropped",
filename: "data.yaml",
content: "---\n# Source: chart/templates/a.yaml\n---\na: 1\n---\n---\nnull\n---\nb: 2\n---\n",
asList: true,
wantJSON: `[{"a":1},{"b":2}]`,
},
{
name: "as a list, an empty YAML file is an empty list",
filename: "data.yaml",
content: "",
asList: true,
wantJSON: `[]`,
},
{
name: "as a list, a top-level YAML sequence is one document and is not unpacked",
filename: "data.yaml",
content: "- a\n- b\n",
asList: true,
wantJSON: `[["a","b"]]`,
},
{
name: "as a list, a JSON object is wrapped in a list of one",
filename: "data.json",
content: `{"name": "Jane"}`,
asList: true,
wantJSON: `[{"name":"Jane"}]`,
},
{
name: "as a list, a top-level JSON array is one document and is not unpacked",
filename: "data.json",
content: `[1, 2]`,
asList: true,
wantJSON: `[[1,2]]`,
},
{
name: "as a list, an empty JSON file is still invalid JSON",
filename: "data.json",
content: "",
asList: true,
wantErr: "data.json does not contain a valid JSON",
},
} {
t.Run(tc.name, func(t *testing.T) {
path := writeAttestationDataFile(t, tc.filename, tc.content)
data, err := LoadAttestationData(path, tc.asList)
if tc.wantErr != "" {
require.ErrorContains(t, err, tc.wantErr)
return
}
require.NoError(t, err)
got, err := json.Marshal(data)
require.NoError(t, err)
require.Equal(t, tc.wantJSON, string(got))
})
}
}

func TestLoadAttestationDataMissingFile(t *testing.T) {
for _, name := range []string{"missing.yaml", "missing.json"} {
_, err := LoadAttestationData(filepath.Join(t.TempDir(), name), false)
require.ErrorIs(t, err, os.ErrNotExist)
}
}

// A published policy reads this exact shape: the documents of the catalog file
// as a root-level list, in file order.
func TestLoadAttestationDataBackstageCatalogAsList(t *testing.T) {
data, err := LoadAttestationData("testdata/backstage-catalog-info.yaml", true)
require.NoError(t, err)
got, err := json.Marshal(data)
require.NoError(t, err)

want, err := os.ReadFile("testdata/backstage-catalog-info.expected.json")
require.NoError(t, err)
var compact bytes.Buffer
require.NoError(t, json.Compact(&compact, want))

// Compared as bytes rather than with JSONEq so that item order, and
// anything wrapped around the list, fails the test.
require.Equal(t, sortedKeysJSON(t, compact.Bytes()), string(got))
require.Equal(t, byte('['), got[0])
}

// sortedKeysJSON re-encodes raw the way encoding/json encodes a decoded
// value: object keys sorted, array order kept.
func sortedKeysJSON(t *testing.T, raw []byte) string {
t.Helper()
var value any
decoder := json.NewDecoder(bytes.NewReader(raw))
decoder.UseNumber()
require.NoError(t, decoder.Decode(&value))
out, err := json.Marshal(value)
require.NoError(t, err)
return string(out)
}
43 changes: 43 additions & 0 deletions cmd/kosli/cli_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"io"
urlPackage "net/url"
"os"
"path/filepath"
"reflect"
"slices"
"strconv"
Expand Down Expand Up @@ -464,6 +465,48 @@ func LoadOptionalJsonData(filepath string) (any, error) {
return LoadJsonData(filepath)
}

// LoadAttestationData loads the data of a custom attestation from a JSON or
// YAML file. The extension picks the format, and YAML is converted to the
// JSON value it describes.
//
// A file holds a stream of documents: any number in YAML, exactly one in
// JSON. With asList the data is the list of those documents, otherwise the
// file must hold exactly one document and the data is that document.
func LoadAttestationData(path string, asList bool) (any, error) {
var documents []any
format := "JSON"
switch strings.ToLower(filepath.Ext(path)) {
case ".yaml", ".yml":
format = "YAML"
content, err := os.ReadFile(path)
if err != nil {
return nil, err
}
documents, err = utils.YAMLDocuments(content)
if err != nil {
return nil, fmt.Errorf("%s does not contain valid YAML: %w", path, err)
}
default:
document, err := LoadJsonData(path)
if err != nil {
return nil, err
}
documents = []any{document}
}

if asList {
return documents, nil
}
switch len(documents) {
case 0:
return nil, fmt.Errorf("%s contains no %s documents. Use --attestation-data-as-list to send an empty list", path, format)
case 1:
return documents[0], nil
default:
return nil, fmt.Errorf("%s contains %d %s documents. Use --attestation-data-as-list to send them as a list", path, len(documents), format)
}
}

// ValidateArtifactArg validates the artifact name or path argument
func ValidateArtifactArg(args []string, artifactType, inputSha256 string, alwaysRequireArtifactName bool) error {
if len(args) > 1 {
Expand Down
3 changes: 2 additions & 1 deletion cmd/kosli/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,8 @@ Paths the list already matches stay excluded whatever is later added there, so k
attestationCompliantFlag = "[defaulted] Whether the attestation is compliant or not."
attestationRepoRootFlag = "[defaulted] The directory where the source git repository is available. It must be the repository's top-level directory. Only used if --commit is used or defaulted in CI, see https://docs.kosli.com/integrations/ci_cd/#defaulted-kosli-command-flags-from-ci-variables ."
attestationCustomTypeNameFlag = "The name of the custom attestation type."
attestationCustomDataFileFlag = "The filepath of a JSON file containing the custom attestation data. The maximum JSON payload size is 1MB."
attestationCustomDataFileFlag = "The filepath of a JSON or YAML file containing the custom attestation data. The file extension picks the format: .yaml and .yml files are converted to JSON, any other file is read as JSON. In YAML, a number with a leading zero is read as octal (0644 becomes 420), so quote version-like values and codes (\"1.10\", \"0123\") to keep them as written. The maximum JSON payload size is 1MB, measured after conversion."
attestationCustomDataAsListFlag = "[optional] Send the custom attestation data as a list with one item per document in the file. A YAML file with several documents (separated by ---) needs this flag; empty documents are skipped. A JSON file is one document, so its value is wrapped in a list of one."
uploadJunitResultsFlag = "[defaulted] Whether to upload the provided Junit results directory as an attachment to Kosli or not."
uploadSnykResultsFlag = "[defaulted] Whether to upload the provided Snyk results file as an attachment to Kosli or not."
attestationAssertFlag = "[optional] Exit with non-zero code if the attestation is non-compliant"
Expand Down
Loading
Loading