| 1 |
package internal_test |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"context" |
| 6 |
"encoding/base64" |
| 7 |
"reflect" |
| 8 |
"testing" |
| 9 |
|
| 10 |
"github.com/containerd/containerd/namespaces" |
| 11 |
"github.com/google/go-tpm-tools/proto/attest" |
| 12 |
"github.com/google/go-tpm-tools/verifier" |
| 13 |
"github.com/google/go-tpm-tools/verifier/util" |
| 14 |
"golang.org/x/oauth2" |
| 15 |
"golang.org/x/oauth2/google" |
| 16 |
) |
| 17 |
|
| 18 |
func TestNewRESTClient(t *testing.T) { |
| 19 |
ctx := namespaces.WithNamespace(context.Background(), namespaces.Default) |
| 20 |
|
| 21 |
mockOauth2Server, err := util.NewMockOauth2Server() |
| 22 |
if err != nil { |
| 23 |
t.Error(err) |
| 24 |
} |
| 25 |
defer mockOauth2Server.Stop() |
| 26 |
|
| 27 |
// Endpoint is Google's OAuth 2.0 default endpoint. Change to mock server. |
| 28 |
google.Endpoint = oauth2.Endpoint{ |
| 29 |
AuthURL: mockOauth2Server.Server.URL + "/o/oauth2/auth", |
| 30 |
TokenURL: mockOauth2Server.Server.URL + "/token", |
| 31 |
AuthStyle: oauth2.AuthStyleInParams, |
| 32 |
} |
| 33 |
|
| 34 |
mockAttestationServer, err := util.NewMockAttestationServer() |
| 35 |
if err != nil { |
| 36 |
t.Error(err) |
| 37 |
} |
| 38 |
defer mockAttestationServer.Stop() |
| 39 |
|
| 40 |
restClient, err := util.NewRESTClient(ctx, mockAttestationServer.Server.URL, "test-project", "us-central") |
| 41 |
if err != nil { |
| 42 |
t.Errorf("Failed to create rest client %s", err) |
| 43 |
} |
| 44 |
gotChallenge, err := restClient.CreateChallenge(ctx) |
| 45 |
if err != nil { |
| 46 |
t.Errorf("Failed to call CreateChallenge %s", err) |
| 47 |
} |
| 48 |
gotTokenResponse, err := restClient.VerifyAttestation(ctx, verifier.VerifyAttestationRequest{ |
| 49 |
Challenge: gotChallenge, |
| 50 |
Attestation: &attest.Attestation{}, |
| 51 |
}) |
| 52 |
if err != nil { |
| 53 |
t.Errorf("Failed to call VerifyAttestation %s", err) |
| 54 |
} |
| 55 |
|
| 56 |
wantNonce, _ := base64.StdEncoding.DecodeString(util.FakeTpmNonce) |
| 57 |
wantChallenge := &verifier.Challenge{ |
| 58 |
Name: "projects/test-project/locations/us-central-1/challenges/" + util.FakeChallengeUUID, |
| 59 |
Nonce: []byte(wantNonce), |
| 60 |
ConnID: ""} |
| 61 |
wantToken := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJ0ZXN0IiwiaWF0IjoxNzA5NzUyNTI1LCJleHAiOjE5MTk3NTI1MjV9.EBLA2zX3c-Fu0l--J9Gey6LIXMO1TFRCoe3bzuPGc1k" |
| 62 |
if !reflect.DeepEqual(gotChallenge, wantChallenge) { |
| 63 |
t.Error("Challenge Mismatch") |
| 64 |
} |
| 65 |
if !bytes.Equal(gotTokenResponse.ClaimsToken, []byte(wantToken)) { |
| 66 |
t.Error("Token Mismatch") |
| 67 |
} |
| 68 |
|
| 69 |
} |