Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make error when getting certificates more transparent for user #70

Merged
merged 5 commits into from
Aug 12, 2023
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
58 changes: 52 additions & 6 deletions testing/mocks.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"encoding/hex"
"fmt"
"syscall"
"testing"

"github.com/google/go-sev-guest/abi"
labi "github.com/google/go-sev-guest/client/linuxabi"
Expand Down Expand Up @@ -150,16 +151,61 @@ func (d *Device) Product() *spb.SevProduct {
return d.SevProduct
}

// Getter represents a static server for request/respond url -> body contents.
// GetResponse controls how often (Occurrences) a certain response should be
// provided.
type GetResponse struct {
Occurrences uint
Body []byte
Error error
}

// Getter is a mock for HTTPSGetter interface that sequentially
// returns the configured responses for the provided URL. Responses are returned
// as a queue, i.e., always serving from index 0.
type Getter struct {
Responses map[string][]byte
Responses map[string][]GetResponse
}

// SimpleGetter constructs a static server from url -> body responses.
// For more elaborate tests, construct a custom Getter.
func SimpleGetter(responses map[string][]byte) *Getter {
getter := &Getter{
Responses: make(map[string][]GetResponse),
}
for key, value := range responses {
getter.Responses[key] = []GetResponse{
{
Occurrences: ^uint(0),
Body: value,
Error: nil,
},
}
}
return getter
}

// Get returns a registered response for a given URL.
// Get the next response body and error. The response is also removed,
// if it has been requested the configured number of times.
func (g *Getter) Get(url string) ([]byte, error) {
v, ok := g.Responses[url]
if !ok {
resp, ok := g.Responses[url]
if !ok || len(resp) == 0 {
return nil, fmt.Errorf("404: %s", url)
}
return v, nil
body := resp[0].Body
err := resp[0].Error
resp[0].Occurrences--
if resp[0].Occurrences == 0 {
g.Responses[url] = resp[1:]
}
return body, err
}

// Done checks that all configured responses have been consumed, and errors
// otherwise.
func (g *Getter) Done(t testing.TB) {
for key := range g.Responses {
if len(g.Responses[key]) != 0 {
t.Errorf("Prepared response for '%s' not retrieved.", key)
}
}
}
12 changes: 7 additions & 5 deletions validate/validate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -235,12 +235,12 @@ func TestValidateSnpAttestation(t *testing.T) {
if err != nil {
t.Fatal(err)
}
getter := &test.Getter{
Responses: map[string][]byte{
getter := test.SimpleGetter(
map[string][]byte{
"https://kdsintf.amd.com/vcek/v1/Milan/cert_chain": rootBytes,
"https://kdsintf.amd.com/vcek/v1/Milan/0a0b0c0d0e0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010203040506?blSPL=31&teeSPL=127&snpSPL=112&ucodeSPL=146": sign.Vcek.Raw,
},
}
)
attestationFn := func(nonce [64]byte) *spb.Attestation {
report, err := sg.GetReport(device, nonce)
if err != nil {
Expand Down Expand Up @@ -271,12 +271,14 @@ func TestValidateSnpAttestation(t *testing.T) {
if err != nil {
t.Fatal(err)
}
return &spb.Attestation{Report: report,
return &spb.Attestation{
Report: report,
CertificateChain: &spb.CertificateChain{
AskCert: sign0.Ask.Raw,
ArkCert: sign0.Ark.Raw,
VcekCert: sign0.Vcek.Raw,
}}
},
}
}(),
opts: &Options{ReportData: nonce0s1[:], GuestPolicy: abi.SnpPolicy{Debug: true}},
},
Expand Down
7 changes: 5 additions & 2 deletions verify/trust/trust.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import (
"github.com/google/go-sev-guest/abi"
"github.com/google/go-sev-guest/kds"
"github.com/google/logger"
"go.uber.org/multierr"
)

var (
Expand Down Expand Up @@ -103,7 +104,7 @@ func (n *SimpleHTTPSGetter) Get(url string) ([]byte, error) {
if err != nil {
return nil, err
} else if resp.StatusCode >= 300 {
return nil, fmt.Errorf("failed to retrieve %s", url)
return nil, fmt.Errorf("failed to retrieve '%s' status %d", url, resp.StatusCode)
}

body, err := io.ReadAll(resp.Body)
Expand All @@ -128,20 +129,22 @@ type RetryHTTPSGetter struct {
func (n *RetryHTTPSGetter) Get(url string) ([]byte, error) {
delay := initialDelay
ctx, cancel := context.WithTimeout(context.Background(), n.Timeout)
var returnedError error
for {
body, err := n.Getter.Get(url)
if err == nil {
cancel()
return body, nil
}
returnedError = multierr.Append(returnedError, err)
delay = delay + delay
if delay > n.MaxRetryDelay {
delay = n.MaxRetryDelay
}
select {
case <-ctx.Done():
cancel()
return nil, fmt.Errorf("timeout") // context cancelled
return nil, multierr.Append(returnedError, fmt.Errorf("timeout")) // context cancelled
case <-time.After(delay): // wait to retry
}
}
Expand Down
136 changes: 136 additions & 0 deletions verify/trust/trust_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
// Copyright 2022 Google LLC
//
// 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 trust_test

import (
"bytes"
"errors"
"testing"
"time"

test "github.com/google/go-sev-guest/testing"
"github.com/google/go-sev-guest/verify/trust"
)

func TestRetryHTTPSGetter(t *testing.T) {
testCases := map[string]struct {
getter *test.Getter
timeout time.Duration
maxRetryDelay time.Duration
}{
"immediate success": {
getter: &test.Getter{
Responses: map[string][]test.GetResponse{
"https://fetch.me": {
{
Occurrences: 1,
Body: []byte("content"),
Error: nil,
},
},
},
},
timeout: time.Second,
maxRetryDelay: time.Millisecond,
},
"second success": {
getter: &test.Getter{
Responses: map[string][]test.GetResponse{
"https://fetch.me": {
{
Occurrences: 1,
Body: []byte(""),
Error: errors.New("fail"),
},
{
Occurrences: 1,
Body: []byte("content"),
Error: nil,
},
},
},
},
timeout: time.Second,
maxRetryDelay: time.Millisecond,
},
"third success": {
getter: &test.Getter{
Responses: map[string][]test.GetResponse{
"https://fetch.me": {
{
Occurrences: 2,
Body: []byte(""),
Error: errors.New("fail"),
},
{
Occurrences: 1,
Body: []byte("content"),
Error: nil,
},
},
},
},
timeout: time.Second,
maxRetryDelay: time.Millisecond,
},
}

for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
r := &trust.RetryHTTPSGetter{
Timeout: tc.timeout,
MaxRetryDelay: tc.maxRetryDelay,
Getter: tc.getter,
}

body, err := r.Get("https://fetch.me")
if !bytes.Equal(body, []byte("content")) {
t.Errorf("expected '%s' but got '%s'", "content", body)
}
if err != nil {
t.Errorf("expected no error, but got %s", err.Error())
}
tc.getter.Done(t)
})
}
}

func TestRetryHTTPSGetterAllFail(t *testing.T) {
testGetter := &test.Getter{
Responses: map[string][]test.GetResponse{
"https://fetch.me": {
{
Occurrences: 1,
Body: []byte(""),
Error: errors.New("fail"),
},
},
},
}
r := &trust.RetryHTTPSGetter{
Timeout: 1 * time.Millisecond,
MaxRetryDelay: 1 * time.Millisecond,
Getter: testGetter,
}

body, err := r.Get("https://fetch.me")
if !bytes.Equal(body, []byte("")) {
t.Errorf("expected '%s' but got '%s'", "content", body)
}
if err == nil {
t.Errorf("expected error, but got none")
}
testGetter.Done(t)
}
37 changes: 20 additions & 17 deletions verify/verify_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,10 @@ import (

const product = "Milan"

var signMu sync.Once
var signer *test.AmdSigner
var (
signMu sync.Once
signer *test.AmdSigner
)

func initSigner() {
newSigner, err := test.DefaultCertChain(product, time.Now())
Expand Down Expand Up @@ -296,15 +298,16 @@ func TestKdsMetadataLogic(t *testing.T) {
}
// Trust the test-generated root if the test should pass. Otherwise, other root logic
// won't get tested.
options := &Options{TrustedRoots: map[string][]*trust.AMDRootCerts{
"Milan": {&trust.AMDRootCerts{
Product: "Milan",
ProductCerts: &trust.ProductCerts{
Ark: newSigner.Ark,
Ask: newSigner.Ask,
},
}},
},
options := &Options{
TrustedRoots: map[string][]*trust.AMDRootCerts{
"Milan": {&trust.AMDRootCerts{
Product: "Milan",
ProductCerts: &trust.ProductCerts{
Ark: newSigner.Ark,
Ask: newSigner.Ask,
},
}},
},
Now: time.Date(1, time.January, 5, 0, 0, 0, 0, time.UTC),
}
if tc.wantErr != "" {
Expand Down Expand Up @@ -374,11 +377,11 @@ func TestCRLRootValidity(t *testing.T) {
if err != nil {
t.Fatal(err)
}
g2 := &test.Getter{
Responses: map[string][]byte{
g2 := test.SimpleGetter(
map[string][]byte{
"https://kdsintf.amd.com/vcek/v1/Milan/crl": crl,
},
}
)
wantErr := "CRL is not signed by ARK"
if err := VcekNotRevoked(root, signer2.Vcek, &Options{Getter: g2}); !test.Match(err, wantErr) {
t.Errorf("Bad Root: VcekNotRevoked(%v) did not error as expected. Got %v, want %v", signer.Vcek, err, wantErr)
Expand Down Expand Up @@ -452,13 +455,13 @@ func TestRealAttestationVerification(t *testing.T) {
trust.ClearProductCertCache()
var nonce [64]byte
copy(nonce[:], []byte{1, 2, 3, 4, 5})
getter := &test.Getter{
Responses: map[string][]byte{
getter := test.SimpleGetter(
map[string][]byte{
"https://kdsintf.amd.com/vcek/v1/Milan/cert_chain": testdata.MilanBytes,
// Use the VCEK's hwID and known TCB values to specify the URL its VCEK cert would be fetched from.
"https://kdsintf.amd.com/vcek/v1/Milan/3ac3fe21e13fb0990eb28a802e3fb6a29483a6b0753590c951bdd3b8e53786184ca39e359669a2b76a1936776b564ea464cdce40c05f63c9b610c5068b006b5d?blSPL=2&teeSPL=0&snpSPL=5&ucodeSPL=68": testdata.VcekBytes,
},
}
)
if err := RawSnpReport(testdata.AttestationBytes, &Options{Getter: getter}); err != nil {
t.Error(err)
}
Expand Down
Loading