Skip to content

Commit

Permalink
terraform-provider: add attestation data source (#2640)
Browse files Browse the repository at this point in the history
Signed-off-by: Daniel Weiße <[email protected]>
Co-authored-by: Daniel Weiße <[email protected]>
  • Loading branch information
elchead and daniel-weisse authored Nov 28, 2023
1 parent 03c5692 commit a2de1d2
Show file tree
Hide file tree
Showing 18 changed files with 871 additions and 177 deletions.
10 changes: 9 additions & 1 deletion bazel/ci/terraform.sh.in
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ check() {
for exclude in "${excludeLockDirs[@]}"; do
for i in "${!terraformLockModules[@]}"; do
if [[ ${terraformLockModules[i]} == "${BUILD_WORKSPACE_DIRECTORY}/${exclude}"* ]]; then
echo " ${terraformLockModules[i]}"
echo "${terraformLockModules[i]}"
unset 'terraformLockModules[i]'
fi
done
Expand Down Expand Up @@ -119,6 +119,14 @@ check() {
${terraform} -chdir="${module}" fmt -recursive > /dev/null
${terraform} -chdir="${module}" validate > /dev/null
rm -rf "${module}/.terraform"
echo "Deleting lock files in the following directories:" # init generates lockfiles which should only be generated in the generate mode.
for dir in "${excludeLockDirs[@]}"; do
if [[ -d ${dir} ]]; then
find "${dir}" -name '*.lock.hcl' -type f -delete
else
echo " Directory ${dir} does not exist, skipping"
fi
done
done
;;

Expand Down
1 change: 0 additions & 1 deletion cli/internal/cmd/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,6 @@ go_test(
"//internal/license",
"//internal/logger",
"//internal/semver",
"//internal/sigstore",
"//internal/state",
"//internal/versions",
"//operators/constellation-node-operator/api/v1alpha1",
Expand Down
76 changes: 21 additions & 55 deletions cli/internal/cmd/configfetchmeasurements.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,13 @@ import (
"github.com/edgelesssys/constellation/v2/internal/api/attestationconfigapi"
"github.com/edgelesssys/constellation/v2/internal/api/versionsapi"
"github.com/edgelesssys/constellation/v2/internal/attestation/measurements"
"github.com/edgelesssys/constellation/v2/internal/attestation/variant"
"github.com/edgelesssys/constellation/v2/internal/cloud/cloudprovider"
"github.com/edgelesssys/constellation/v2/internal/config"
"github.com/edgelesssys/constellation/v2/internal/constants"
"github.com/edgelesssys/constellation/v2/internal/featureset"
"github.com/edgelesssys/constellation/v2/internal/file"
"github.com/edgelesssys/constellation/v2/internal/sigstore"
"github.com/edgelesssys/constellation/v2/internal/sigstore/keyselect"
"github.com/spf13/afero"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
Expand Down Expand Up @@ -73,10 +74,18 @@ func (f *fetchMeasurementsFlags) parse(flags *pflag.FlagSet) error {
return nil
}

type verifyFetcher interface {
FetchAndVerifyMeasurements(ctx context.Context,
image string, csp cloudprovider.Provider, attestationVariant variant.Variant,
noVerify bool,
) (measurements.M, error)
}

type configFetchMeasurementsCmd struct {
flags fetchMeasurementsFlags
canFetchMeasurements bool
log debugLog
verifyFetcher verifyFetcher
}

func runConfigFetchMeasurements(cmd *cobra.Command, _ []string) error {
Expand All @@ -90,19 +99,20 @@ func runConfigFetchMeasurements(cmd *cobra.Command, _ []string) error {
if err != nil {
return fmt.Errorf("constructing Rekor client: %w", err)
}
cfm := &configFetchMeasurementsCmd{log: log, canFetchMeasurements: featureset.CanFetchMeasurements}

verifyFetcher := measurements.NewVerifyFetcher(sigstore.NewCosignVerifier, rekor, http.DefaultClient)
cfm := &configFetchMeasurementsCmd{log: log, canFetchMeasurements: featureset.CanFetchMeasurements, verifyFetcher: verifyFetcher}
if err := cfm.flags.parse(cmd.Flags()); err != nil {
return fmt.Errorf("parsing flags: %w", err)
}
cfm.log.Debugf("Using flags %+v", cfm.flags)

fetcher := attestationconfigapi.NewFetcherWithClient(http.DefaultClient, constants.CDNRepositoryURL)
return cfm.configFetchMeasurements(cmd, sigstore.NewCosignVerifier, rekor, fileHandler, fetcher, http.DefaultClient)
return cfm.configFetchMeasurements(cmd, fileHandler, fetcher)
}

func (cfm *configFetchMeasurementsCmd) configFetchMeasurements(
cmd *cobra.Command, newCosignVerifier cosignVerifierConstructor, rekor rekorVerifier,
fileHandler file.Handler, fetcher attestationconfigapi.Fetcher, client *http.Client,
cmd *cobra.Command, fileHandler file.Handler, fetcher attestationconfigapi.Fetcher,
) error {
if !cfm.canFetchMeasurements {
cmd.PrintErrln("Fetching measurements is not supported in the OSS build of the Constellation CLI. Consult the documentation for instructions on where to download the enterprise version.")
Expand Down Expand Up @@ -132,58 +142,16 @@ func (cfm *configFetchMeasurementsCmd) configFetchMeasurements(
if err := cfm.flags.updateURLs(conf); err != nil {
return err
}

cfm.log.Debugf("Fetching and verifying measurements")
imageVersion, err := versionsapi.NewVersionFromShortPath(conf.Image, versionsapi.VersionKindImage)
fetchedMeasurements, err := cfm.verifyFetcher.FetchAndVerifyMeasurements(ctx, conf.Image, conf.GetProvider(),
conf.GetAttestationConfig().GetVariant(), cfm.flags.insecure)
if err != nil {
return err
}

publicKey, err := keyselect.CosignPublicKeyForVersion(imageVersion)
if err != nil {
return fmt.Errorf("getting public key: %w", err)
}
cosign, err := newCosignVerifier(publicKey)
if err != nil {
return fmt.Errorf("creating cosign verifier: %w", err)
}

var fetchedMeasurements measurements.M
var hash string
if cfm.flags.insecure {
if err := fetchedMeasurements.FetchNoVerify(
ctx,
client,
cfm.flags.measurementsURL,
imageVersion,
conf.GetProvider(),
conf.GetAttestationConfig().GetVariant(),
); err != nil {
return fmt.Errorf("fetching measurements without verification: %w", err)
}

cfm.log.Debugf("Fetched measurements without verification")
} else {
hash, err = fetchedMeasurements.FetchAndVerify(
ctx,
client,
cosign,
cfm.flags.measurementsURL,
cfm.flags.signatureURL,
imageVersion,
conf.GetProvider(),
conf.GetAttestationConfig().GetVariant(),
)
if err != nil {
return fmt.Errorf("fetching and verifying measurements: %w", err)
}
cfm.log.Debugf("Fetched and verified measurements, hash is %s", hash)
if err := sigstore.VerifyWithRekor(cmd.Context(), publicKey, rekor, hash); err != nil {
var rekorErr *measurements.RekorError
if errors.As(err, &rekorErr) {
cmd.PrintErrf("Ignoring Rekor related error: %v\n", err)
cmd.PrintErrln("Make sure the downloaded measurements are trustworthy!")
} else {
return fmt.Errorf("fetching and verifying measurements: %w", err)
}

cfm.log.Debugf("Verified measurements with Rekor")
}
cfm.log.Debugf("Measurements:\n", fetchedMeasurements)

Expand Down Expand Up @@ -234,5 +202,3 @@ type rekorVerifier interface {
SearchByHash(context.Context, string) ([]string, error)
VerifyEntry(context.Context, string, string) error
}

type cosignVerifierConstructor func([]byte) (sigstore.Verifier, error)
127 changes: 18 additions & 109 deletions cli/internal/cmd/configfetchmeasurements_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,20 @@ SPDX-License-Identifier: AGPL-3.0-only
package cmd

import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"net/url"
"testing"

"github.com/edgelesssys/constellation/v2/internal/api/attestationconfigapi"
"github.com/edgelesssys/constellation/v2/internal/api/versionsapi"
"github.com/edgelesssys/constellation/v2/internal/attestation/measurements"
"github.com/edgelesssys/constellation/v2/internal/attestation/variant"
"github.com/edgelesssys/constellation/v2/internal/cloud/cloudprovider"
"github.com/edgelesssys/constellation/v2/internal/config"
"github.com/edgelesssys/constellation/v2/internal/constants"
"github.com/edgelesssys/constellation/v2/internal/file"
"github.com/edgelesssys/constellation/v2/internal/logger"
"github.com/edgelesssys/constellation/v2/internal/sigstore"
"github.com/spf13/afero"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -154,114 +151,17 @@ func newTestClient(fn roundTripFunc) *http.Client {
}

func TestConfigFetchMeasurements(t *testing.T) {
measurements := `{
"version": "v999.999.999",
"ref": "-",
"stream": "stable",
"list": [
{
"csp": "GCP",
"attestationVariant":"gcp-sev-es",
"measurements": {
"0": {
"expected": "0000000000000000000000000000000000000000000000000000000000000000",
"warnOnly":false
},
"1": {
"expected": "1111111111111111111111111111111111111111111111111111111111111111",
"warnOnly":false
},
"2": {
"expected": "2222222222222222222222222222222222222222222222222222222222222222",
"warnOnly":false
},
"3": {
"expected": "3333333333333333333333333333333333333333333333333333333333333333",
"warnOnly":false
},
"4": {
"expected": "4444444444444444444444444444444444444444444444444444444444444444",
"warnOnly":false
},
"5": {
"expected": "5555555555555555555555555555555555555555555555555555555555555555",
"warnOnly":false
},
"6": {
"expected": "6666666666666666666666666666666666666666666666666666666666666666",
"warnOnly":false
}
}
}
]
}
`
signature := "placeholder-signature"

client := newTestClient(func(req *http.Request) *http.Response {
if req.URL.Path == "/constellation/v2/ref/-/stream/stable/v999.999.999/image/measurements.json" {
return &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(measurements)),
Header: make(http.Header),
}
}
if req.URL.Path == "/constellation/v2/ref/-/stream/stable/v999.999.999/image/measurements.json.sig" {
return &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(bytes.NewBufferString(signature)),
Header: make(http.Header),
}
}

fmt.Println("unexpected request", req.URL.String())
return &http.Response{
StatusCode: http.StatusNotFound,
Body: io.NopCloser(bytes.NewBufferString("Not found.")),
Header: make(http.Header),
}
})

testCases := map[string]struct {
cosign cosignVerifierConstructor
rekor rekorVerifier
insecureFlag bool
err error
wantErr bool
}{
"success": {
cosign: newStubCosignVerifier,
rekor: singleUUIDVerifier(),
},
"success without cosign": {
insecureFlag: true,
cosign: func(_ []byte) (sigstore.Verifier, error) {
return &stubCosignVerifier{
verifyError: assert.AnError,
}, nil
},
rekor: singleUUIDVerifier(),
},
"failing search should not result in error": {
cosign: newStubCosignVerifier,
rekor: &stubRekorVerifier{
SearchByHashUUIDs: []string{},
SearchByHashError: assert.AnError,
},
},
"failing verify should not result in error": {
cosign: newStubCosignVerifier,
rekor: &stubRekorVerifier{
SearchByHashUUIDs: []string{"11111111111111111111111111111111111111111111111111111111111111111111111111111111"},
VerifyEntryError: assert.AnError,
},
"no error succeeds": {},
"failing rekor verify should not result in error": {
err: &measurements.RekorError{},
},
"signature verification failure": {
cosign: func(_ []byte) (sigstore.Verifier, error) {
return &stubCosignVerifier{
verifyError: assert.AnError,
}, nil
},
rekor: singleUUIDVerifier(),
"error other than Rekor fails": {
err: assert.AnError,
wantErr: true,
},
}
Expand All @@ -279,11 +179,12 @@ func TestConfigFetchMeasurements(t *testing.T) {

err := fileHandler.WriteYAML(constants.ConfigFilename, gcpConfig, file.OptMkdirAll)
require.NoError(err)
cfm := &configFetchMeasurementsCmd{canFetchMeasurements: true, log: logger.NewTest(t)}
fetcher := stubVerifyFetcher{err: tc.err}
cfm := &configFetchMeasurementsCmd{canFetchMeasurements: true, log: logger.NewTest(t), verifyFetcher: fetcher}
cfm.flags.insecure = tc.insecureFlag
cfm.flags.force = true

err = cfm.configFetchMeasurements(cmd, tc.cosign, tc.rekor, fileHandler, stubAttestationFetcher{}, client)
err = cfm.configFetchMeasurements(cmd, fileHandler, stubAttestationFetcher{})
if tc.wantErr {
assert.Error(err)
return
Expand All @@ -293,6 +194,14 @@ func TestConfigFetchMeasurements(t *testing.T) {
}
}

type stubVerifyFetcher struct {
err error
}

func (f stubVerifyFetcher) FetchAndVerifyMeasurements(_ context.Context, _ string, _ cloudprovider.Provider, _ variant.Variant, _ bool) (measurements.M, error) {
return nil, f.err
}

type stubAttestationFetcher struct{}

func (f stubAttestationFetcher) FetchSEVSNPVersionList(_ context.Context, _ attestationconfigapi.SEVSNPVersionList) (attestationconfigapi.SEVSNPVersionList, error) {
Expand Down
6 changes: 0 additions & 6 deletions cli/internal/cmd/verifier_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ package cmd

import (
"context"

"github.com/edgelesssys/constellation/v2/internal/sigstore"
)

// singleUUIDVerifier constructs a RekorVerifier that returns a single UUID and no errors,
Expand Down Expand Up @@ -43,10 +41,6 @@ type stubCosignVerifier struct {
verifyError error
}

func newStubCosignVerifier(_ []byte) (sigstore.Verifier, error) {
return &stubCosignVerifier{}, nil
}

func (v *stubCosignVerifier) VerifySignature(_, _ []byte) error {
return v.verifyError
}
2 changes: 1 addition & 1 deletion internal/api/attestationconfigapi/fetcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ var ErrNoVersionsFound = errors.New("no versions found")
type Fetcher interface {
FetchSEVSNPVersion(ctx context.Context, version SEVSNPVersionAPI) (SEVSNPVersionAPI, error)
FetchSEVSNPVersionList(ctx context.Context, list SEVSNPVersionList) (SEVSNPVersionList, error)
FetchSEVSNPVersionLatest(ctx context.Context, attesation variant.Variant) (SEVSNPVersionAPI, error)
FetchSEVSNPVersionLatest(ctx context.Context, attestation variant.Variant) (SEVSNPVersionAPI, error)
}

// fetcher fetches AttestationCfg API resources without authentication.
Expand Down
8 changes: 7 additions & 1 deletion internal/attestation/measurements/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ load("//bazel/go:go_test.bzl", "go_test")
go_library(
name = "measurements",
srcs = [
"fetchmeasurements.go",
"measurements.go",
# keep
"measurements_enterprise.go",
Expand All @@ -16,6 +17,8 @@ go_library(
"//internal/api/versionsapi",
"//internal/attestation/variant",
"//internal/cloud/cloudprovider",
"//internal/sigstore",
"//internal/sigstore/keyselect",
"@com_github_google_go_tpm//tpmutil",
"@com_github_siderolabs_talos_pkg_machinery//config/encoder",
"@in_gopkg_yaml_v3//:yaml_v3",
Expand All @@ -24,7 +27,10 @@ go_library(

go_test(
name = "measurements_test",
srcs = ["measurements_test.go"],
srcs = [
"fetchmeasurements_test.go",
"measurements_test.go",
],
embed = [":measurements"],
deps = [
"//internal/api/versionsapi",
Expand Down
Loading

0 comments on commit a2de1d2

Please sign in to comment.