Skip to content

Commit

Permalink
add well-known attestation specs support to the attest command (#504)
Browse files Browse the repository at this point in the history
* add well-known attestation specs support to the attest command

Fixes #472

Signed-off-by: Batuhan Apaydın <batuhan.apaydin@trendyol.com>

* fix lint issues, fix required json tag logic

Signed-off-by: Batuhan Apaydın <batuhan.apaydin@trendyol.com>

* fix e2e test and license problems

Signed-off-by: Batuhan Apaydın <batuhan.apaydin@trendyol.com>
  • Loading branch information
developer-guy authored Jul 29, 2021
1 parent 53f7cd4 commit 7e9cdfb
Show file tree
Hide file tree
Showing 3 changed files with 183 additions and 30 deletions.
41 changes: 12 additions & 29 deletions cmd/cosign/cli/attest.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,13 @@ import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"os"
"path/filepath"

"github.com/google/go-containerregistry/pkg/name"
ggcrV1 "github.com/google/go-containerregistry/pkg/v1"
"github.com/in-toto/in-toto-golang/in_toto"
"github.com/peterbourgon/ff/v3/ffcli"
"github.com/pkg/errors"
"github.com/sigstore/cosign/pkg/cosign/attestation"

"github.com/sigstore/cosign/pkg/cosign"
cremote "github.com/sigstore/cosign/pkg/cosign/remote"
Expand All @@ -52,6 +50,7 @@ func Attest() *ffcli.Command {
predicatePath = flagset.String("predicate", "", "path to the predicate file.")
force = flagset.Bool("f", false, "skip warnings and confirmations")
idToken = flagset.String("identity-token", "", "[EXPERIMENTAL] identity token to use for certificate from fulcio")
predicateType = flagset.String("type", "custom", "specify predicate type (default: custom) (provenance|link|spdx)")
)
return &ffcli.Command{
Name: "attest",
Expand Down Expand Up @@ -95,7 +94,7 @@ EXAMPLES
IDToken: *idToken,
}
for _, img := range args {
if err := AttestCmd(ctx, ko, img, *cert, *upload, *predicatePath, *force); err != nil {
if err := AttestCmd(ctx, ko, img, *cert, *upload, *predicatePath, *force, *predicateType); err != nil {
return errors.Wrapf(err, "signing %s", img)
}
}
Expand All @@ -107,7 +106,7 @@ EXAMPLES
const intotoPayloadType = "application/vnd.in-toto+json"

func AttestCmd(ctx context.Context, ko KeyOpts, imageRef string, certPath string,
upload bool, predicatePath string, force bool) error {
upload bool, predicatePath string, force bool, predicateType string) error {

// A key file or token is required unless we're in experimental mode!
if EnableExperimental() {
Expand Down Expand Up @@ -140,27 +139,15 @@ func AttestCmd(ctx context.Context, ko KeyOpts, imageRef string, certPath string
wrapped := dsse.WrapSigner(sv, intotoPayloadType)

fmt.Fprintln(os.Stderr, "Using payload from:", predicatePath)
rawPayload, err := ioutil.ReadFile(filepath.Clean(predicatePath))
if err != nil {
return errors.Wrap(err, "payload from file")
}

sh := in_toto.Statement{
StatementHeader: in_toto.StatementHeader{
Type: "https://in-toto.io/Statement/v0.1",
PredicateType: "cosign.sigstore.dev/attestation/v1",
Subject: []in_toto.Subject{
{
Name: repo.String(),
Digest: map[string]string{
"sha256": h.Hex,
},
},
},
},
Predicate: CosignAttestation{
Data: string(rawPayload),
},
sh, err := attestation.GenerateStatement(attestation.GenerateOpts{
Path: predicatePath,
Type: predicateType,
Digest: h.Hex,
Repo: repo.String(),
})
if err != nil {
return err
}

payload, err := json.Marshal(sh)
Expand Down Expand Up @@ -233,7 +220,3 @@ func AttestCmd(ctx context.Context, ko KeyOpts, imageRef string, certPath string

return nil
}

type CosignAttestation struct {
Data string
}
170 changes: 170 additions & 0 deletions pkg/cosign/attestation/attestation.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
//
// Copyright 2021 The Sigstore 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 attestation

import (
"encoding/json"
"fmt"
"io/ioutil"
"path/filepath"
"reflect"
"strings"

"github.com/in-toto/in-toto-golang/in_toto"
"github.com/pkg/errors"
)

const (
// CosignCustomProvenanceV01 specifies the type of the Predicate.
CosignCustomProvenanceV01 = "cosign.sigstore.dev/attestation/v1"
)

// CosignAttestation specifies the format of the Custom Predicate.
type CosignAttestation struct {
Data string
}

// GenerateOpts specifies the options of the Statement generator.
type GenerateOpts struct {
// Path is the given path to the predicate file.
Path string
// Type is the pre-defined enums (provenance|link|spdx).
// default: custom
Type string
// Digest of the Image reference.
Digest string
// Repo context of the reference.
Repo string
}

// GenerateStatement returns corresponding Predicate (custom|provenance|spdx|link)
// based on the type you specified.
func GenerateStatement(opts GenerateOpts) (interface{}, error) {
rawPayload, err := readPayload(opts.Path)
if err != nil {
return nil, err
}
switch opts.Type {
case "custom":
return generateCustomStatement(rawPayload, opts.Digest, opts.Repo)
case "provenance":
return generateProvenanceStatement(rawPayload, opts.Digest, opts.Repo)
case "spdx":
return generateSPDXStatement(rawPayload, opts.Digest, opts.Repo)
case "link":
return generateLinkStatement(rawPayload, opts.Digest, opts.Repo)
default:
return nil, errors.New(fmt.Sprintf("we don't know this predicate type: '%s'", opts.Type))
}
}

func generateStatementHeader(digest, repo, predicateType string) in_toto.StatementHeader {
return in_toto.StatementHeader{
Type: in_toto.StatementInTotoV01,
PredicateType: predicateType,
Subject: []in_toto.Subject{
{
Name: repo,
Digest: map[string]string{
"sha256": digest,
},
},
},
}
}

//
func generateCustomStatement(rawPayload []byte, digest, repo string) (interface{}, error) {
return in_toto.Statement{
StatementHeader: generateStatementHeader(digest, repo, CosignCustomProvenanceV01),
Predicate: CosignAttestation{
Data: string(rawPayload),
},
}, nil
}

func generateProvenanceStatement(rawPayload []byte, digest string, repo string) (interface{}, error) {
var predicate in_toto.ProvenancePredicate
err := checkRequiredJSONFields(rawPayload, reflect.TypeOf(predicate))
if err != nil {
return nil, fmt.Errorf("provenance predicate: %v", err)
}
err = json.Unmarshal(rawPayload, &predicate)
if err != nil {
return "", errors.Wrap(err, "unmarshal Provenance predicate")
}
return in_toto.ProvenanceStatement{
StatementHeader: generateStatementHeader(digest, repo, in_toto.PredicateProvenanceV01),
Predicate: predicate,
}, nil
}

func generateLinkStatement(rawPayload []byte, digest string, repo string) (interface{}, error) {
var link in_toto.Link
err := checkRequiredJSONFields(rawPayload, reflect.TypeOf(link))
if err != nil {
return nil, fmt.Errorf("link statement: %v", err)
}
err = json.Unmarshal(rawPayload, &link)
if err != nil {
return "", errors.Wrap(err, "unmarshal Link statement")
}
return in_toto.LinkStatement{
StatementHeader: generateStatementHeader(digest, repo, in_toto.PredicateLinkV1),
Predicate: link,
}, nil
}

func generateSPDXStatement(rawPayload []byte, digest string, repo string) (interface{}, error) {
return in_toto.SPDXStatement{
StatementHeader: generateStatementHeader(digest, repo, in_toto.PredicateSPDX),
Predicate: CosignAttestation{
Data: string(rawPayload),
},
}, nil
}

func readPayload(predicatePath string) ([]byte, error) {
rawPayload, err := ioutil.ReadFile(filepath.Clean(predicatePath))
if err != nil {
return nil, errors.Wrap(err, "payload from file")
}
return rawPayload, nil
}

func checkRequiredJSONFields(rawPayload []byte, typ reflect.Type) error {
var tmp map[string]interface{}
if err := json.Unmarshal(rawPayload, &tmp); err != nil {
return err
}
// Create list of json tags, e.g. `json:"_type"`
attributeCount := typ.NumField()
allFields := make([]string, 0)
for i := 0; i < attributeCount; i++ {
jsonTagFields := strings.SplitN(typ.Field(i).Tag.Get("json"), ",", 2)
if len(jsonTagFields) < 2 {
allFields = append(allFields, jsonTagFields[0])
}
}

// Assert that there's a key in the passed map for each tag
for _, field := range allFields {
if _, ok := tmp[field]; !ok {
return fmt.Errorf("required field %s missing", field)
}
}
return nil
}
2 changes: 1 addition & 1 deletion test/e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ func TestAttestVerify(t *testing.T) {

// Now attest the image
ko := cli.KeyOpts{KeyRef: privKeyPath, PassFunc: passFunc}
must(cli.AttestCmd(ctx, ko, imgName, "", true, ap, false), t)
must(cli.AttestCmd(ctx, ko, imgName, "", true, ap, false, "custom"), t)

// Now verify and download should work!
must(verifyAttestation.Exec(ctx, []string{imgName}), t)
Expand Down

0 comments on commit 7e9cdfb

Please sign in to comment.