Debian Codegraph @

launcher/container_runner_test.go

raw
1 package launcher
2
3 import (
4 "bytes"
5 "context"
6 "crypto/rand"
7 "crypto/rsa"
8 "errors"
9 "fmt"
10 "os"
11 "path"
12 "strconv"
13 "strings"
14 "sync"
15 "testing"
16 "time"
17
18 "github.com/cenkalti/backoff/v4"
19 "github.com/containerd/containerd"
20 "github.com/containerd/containerd/defaults"
21 "github.com/containerd/containerd/namespaces"
22 "github.com/containerd/containerd/oci"
23 "github.com/golang-jwt/jwt/v4"
24 "github.com/google/go-cmp/cmp"
25 gecel "github.com/google/go-eventlog/cel"
26 "github.com/google/go-tpm-tools/cel"
27 "github.com/google/go-tpm-tools/launcher/agent"
28 "github.com/google/go-tpm-tools/launcher/internal/gpu"
29 "github.com/google/go-tpm-tools/launcher/internal/logging"
30 "github.com/google/go-tpm-tools/launcher/launcherfile"
31 "github.com/google/go-tpm-tools/launcher/spec"
32 "github.com/google/go-tpm-tools/verifier"
33 "github.com/opencontainers/go-digest"
34 v1 "github.com/opencontainers/image-spec/specs-go/v1"
35 specs "github.com/opencontainers/runtime-spec/specs-go"
36 "golang.org/x/oauth2"
37
38 attestationpb "github.com/GoogleCloudPlatform/confidential-space/server/proto/gen/attestation"
39 )
40
41 const (
42 idTokenEndpoint = "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/%s:generateIdToken"
43 )
44
45 // Fake attestation agent.
46 type fakeAttestationAgent struct {
47 measureEventFunc func(gecel.Content) error
48 attestFunc func(context.Context, agent.AttestAgentOpts) ([]byte, error)
49 sigsCache []string
50 sigsFetcherFunc func(context.Context) []string
51
52 // attMu sits on top of attempts field and protects attempts.
53 attMu sync.Mutex
54 attempts int
55 }
56
57 func (f *fakeAttestationAgent) MeasureEvent(event gecel.Content) error {
58 if f.measureEventFunc != nil {
59 return f.measureEventFunc(event)
60 }
61
62 return fmt.Errorf("unimplemented")
63 }
64
65 func (f *fakeAttestationAgent) Attest(ctx context.Context, _ agent.AttestAgentOpts) ([]byte, error) {
66 if f.attestFunc != nil {
67 return f.attestFunc(ctx, agent.AttestAgentOpts{})
68 }
69
70 return nil, fmt.Errorf("unimplemented")
71 }
72
73 func (f *fakeAttestationAgent) AttestWithClient(_ context.Context, _ agent.AttestAgentOpts, _ verifier.Client) ([]byte, error) {
74 return nil, fmt.Errorf("unimplemented")
75 }
76
77 func (f *fakeAttestationAgent) AttestationEvidence(_ context.Context, _ []byte, _ []byte) (*attestationpb.VmAttestation, error) {
78 return nil, fmt.Errorf("unimplemented")
79 }
80
81 // Refresh simulates the behavior of an actual agent.
82 func (f *fakeAttestationAgent) Refresh(ctx context.Context) error {
83 if f.sigsFetcherFunc != nil {
84 f.sigsCache = f.sigsFetcherFunc(ctx)
85 }
86 return nil
87 }
88
89 func (f *fakeAttestationAgent) Close() error {
90 return nil
91 }
92
93 type fakeGPUAttester struct {
94 attestFunc func(nonce []byte) (any, error)
95 }
96
97 func (f *fakeGPUAttester) Attest(nonce []byte) (any, error) {
98 if f.attestFunc != nil {
99 return f.attestFunc(nonce)
100 }
101 return &attestationpb.NvidiaAttestationReport{}, nil
102 }
103
104 func (f *fakeGPUAttester) EnableReadyState() error {
105 return nil
106 }
107
108 type fakeClaims struct {
109 jwt.RegisteredClaims
110 Signatures []string
111 }
112
113 func createJWT(t *testing.T, ttl time.Duration) []byte {
114 return createJWTWithID(t, "test token", ttl)
115 }
116
117 func createJWTWithID(t *testing.T, id string, ttl time.Duration) []byte {
118 now := jwt.TimeFunc()
119 claims := &jwt.RegisteredClaims{
120 ID: id,
121 IssuedAt: jwt.NewNumericDate(now),
122 NotBefore: jwt.NewNumericDate(now),
123 ExpiresAt: jwt.NewNumericDate(now.Add(ttl)),
124 }
125
126 return createSignedToken(t, claims)
127 }
128
129 func createJWTWithSignatures(t *testing.T, signatures []string) []byte {
130 now := jwt.TimeFunc()
131 ttl := 5 * time.Second
132 id := "signature token"
133 claims := &fakeClaims{
134 RegisteredClaims: jwt.RegisteredClaims{
135 ID: id,
136 IssuedAt: jwt.NewNumericDate(now),
137 NotBefore: jwt.NewNumericDate(now),
138 ExpiresAt: jwt.NewNumericDate(now.Add(ttl)),
139 },
140 Signatures: signatures,
141 }
142 return createSignedToken(t, claims)
143 }
144
145 func createSignedToken(t *testing.T, claims jwt.Claims) []byte {
146 t.Helper()
147
148 privkey, err := rsa.GenerateKey(rand.Reader, 2048)
149 if err != nil {
150 t.Fatalf("Error creating token key: %v", err)
151 }
152
153 token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
154 signed, err := token.SignedString(privkey)
155 if err != nil {
156 t.Fatalf("Error creating signed string: %v", err)
157 }
158
159 return []byte(signed)
160 }
161
162 func extractJWTClaims(t *testing.T, token []byte) *jwt.RegisteredClaims {
163 claims := &jwt.RegisteredClaims{}
164 _, _, err := jwt.NewParser().ParseUnverified(string(token), claims)
165 if err != nil {
166 t.Fatalf("failed to parse JWT: %v", token)
167 }
168 return claims
169 }
170
171 func TestRefreshToken(t *testing.T) {
172 ctx, cancel := context.WithCancel(context.Background())
173 defer cancel()
174
175 ttl := 5 * time.Second
176 expectedToken := createJWT(t, ttl)
177
178 runner := ContainerRunner{
179 attestAgent: &fakeAttestationAgent{
180 attestFunc: func(context.Context, agent.AttestAgentOpts) ([]byte, error) {
181 return expectedToken, nil
182 },
183 },
184 logger: logging.SimpleLogger(),
185 }
186
187 if err := os.MkdirAll(launcherfile.HostTmpPath, 0755); err != nil {
188 t.Fatalf("Error creating host token path directory: %v", err)
189 }
190
191 refreshTime, err := runner.refreshToken(ctx)
192 if err != nil {
193 t.Fatalf("refreshToken returned with error: %v", err)
194 }
195
196 filepath := path.Join(launcherfile.HostTmpPath, launcherfile.AttestationVerifierTokenFilename)
197 data, err := os.ReadFile(filepath)
198 if err != nil {
199 t.Fatalf("Failed to read from %s: %v", filepath, err)
200 }
201
202 if !bytes.Equal(data, expectedToken) {
203 t.Errorf("Initial token written to file does not match expected token: got %v, want %v", data, expectedToken)
204 }
205
206 // Expect refreshTime to be no greater than expectedTTL.
207 if refreshTime >= time.Duration(float64(ttl)) {
208 t.Errorf("Refresh time cannot exceed ttl: got %v, expect no greater than %v", refreshTime, time.Duration(float64(ttl)))
209 }
210 }
211
212 // TestRefreshTokenWithSignedContainerCacheEnabled checks `refreshToken` updates the default token when signatures get updated.
213 func TestRefreshTokenWithSignedContainerCacheEnabled(t *testing.T) {
214 ctx, cancel := context.WithCancel(context.Background())
215 defer cancel()
216
217 oldCache := []string{"old sigs cache"}
218 fakeAgent := &fakeAttestationAgent{
219 sigsFetcherFunc: func(context.Context) []string {
220 return oldCache
221 },
222 }
223 fakeAgent.attestFunc = func(context.Context, agent.AttestAgentOpts) ([]byte, error) {
224 return createJWTWithSignatures(t, fakeAgent.sigsCache), nil
225 }
226
227 runner := ContainerRunner{
228 attestAgent: fakeAgent,
229 logger: logging.SimpleLogger(),
230 }
231
232 if err := os.MkdirAll(launcherfile.HostTmpPath, 0755); err != nil {
233 t.Fatalf("Error creating host token path directory: %v", err)
234 }
235
236 _, err := runner.refreshToken(ctx)
237 if err != nil {
238 t.Fatalf("refreshToken returned with error: %v", err)
239 }
240
241 // Simulate adding signatures.
242 newCache := []string{"old sigs cache", "new sigs cache"}
243 fakeAgent.sigsFetcherFunc = func(context.Context) []string {
244 return newCache
245 }
246
247 // Refresh token again to get the updated token.
248 _, err = runner.refreshToken(ctx)
249 if err != nil {
250 t.Fatalf("refreshToken returned with error: %v", err)
251 }
252
253 // Read the token to check if claims contain the updated signatures.
254 filepath := path.Join(launcherfile.HostTmpPath, launcherfile.AttestationVerifierTokenFilename)
255 token, err := os.ReadFile(filepath)
256 if err != nil {
257 t.Fatalf("Failed to read from %s: %v", filepath, err)
258 }
259
260 gotClaims := &fakeClaims{}
261 _, _, err = jwt.NewParser().ParseUnverified(string(token), gotClaims)
262 if err != nil {
263 t.Fatalf("failed to parse token: %v", err)
264 }
265
266 if gotSignatures, wantSignatures := gotClaims.Signatures, newCache; !cmp.Equal(gotSignatures, wantSignatures) {
267 t.Errorf("Updated token written to file does not contain expected signatures: got %v, want %v", gotSignatures, wantSignatures)
268 }
269 }
270
271 func TestRefreshTokenError(t *testing.T) {
272 if err := os.MkdirAll(launcherfile.HostTmpPath, 0755); err != nil {
273 t.Fatalf("Error creating host token path directory: %v", err)
274 }
275
276 testcases := []struct {
277 name string
278 agent *fakeAttestationAgent
279 }{
280 {
281 name: "Attest fails",
282 agent: &fakeAttestationAgent{
283 attestFunc: func(context.Context, agent.AttestAgentOpts) ([]byte, error) {
284 return nil, errors.New("attest error")
285 },
286 },
287 },
288 {
289 name: "Attest returns expired token",
290 agent: &fakeAttestationAgent{
291 attestFunc: func(context.Context, agent.AttestAgentOpts) ([]byte, error) {
292 return createJWT(t, -5*time.Second), nil
293 },
294 },
295 },
296 }
297
298 for _, tc := range testcases {
299 t.Run(tc.name, func(t *testing.T) {
300 runner := ContainerRunner{
301 attestAgent: tc.agent,
302 logger: logging.SimpleLogger(),
303 }
304
305 if _, err := runner.refreshToken(context.Background()); err == nil {
306 t.Error("refreshToken succeeded, expected error.")
307 }
308
309 })
310 }
311 }
312
313 func TestMeasureGPUAttestationEvidence(t *testing.T) {
314 testCases := []struct {
315 name string
316 gpuAttester gpu.Attester
317 attestAgent *fakeAttestationAgent
318 wantErr bool
319 wantErrStr string
320 }{
321 {
322 name: "Success",
323 gpuAttester: &fakeGPUAttester{},
324 attestAgent: &fakeAttestationAgent{
325 measureEventFunc: func(gecel.Content) error { return nil },
326 },
327 wantErr: false,
328 },
329 {
330 name: "NilGpuAttester",
331 gpuAttester: nil,
332 attestAgent: &fakeAttestationAgent{},
333 wantErr: false,
334 },
335 {
336 name: "AttestError",
337 gpuAttester: &fakeGPUAttester{
338 attestFunc: func(_ []byte) (any, error) {
339 return nil, errors.New("attest failed")
340 },
341 },
342 attestAgent: &fakeAttestationAgent{},
343 wantErr: true,
344 wantErrStr: "failed to collect GPU evidence",
345 },
346 {
347 name: "WrongEvidenceType",
348 gpuAttester: &fakeGPUAttester{
349 attestFunc: func(_ []byte) (any, error) {
350 return "wrong type", nil
351 },
352 },
353 attestAgent: &fakeAttestationAgent{},
354 wantErr: true,
355 wantErrStr: "unexpected evidence type",
356 },
357 {
358 name: "MeasureEventError",
359 gpuAttester: &fakeGPUAttester{},
360 attestAgent: &fakeAttestationAgent{
361 measureEventFunc: func(gecel.Content) error {
362 return errors.New("measure event failed")
363 },
364 },
365 wantErr: true,
366 wantErrStr: "failed to measure GPU attestation",
367 },
368 }
369
370 for _, tc := range testCases {
371 t.Run(tc.name, func(t *testing.T) {
372 r := &ContainerRunner{
373 // The fakeGPUAttester doesn't have EnableReadyState, so we wrap it.
374 gpuAttester: tc.gpuAttester,
375 attestAgent: tc.attestAgent,
376 logger: logging.SimpleLogger(),
377 }
378
379 err := r.measureGPUAttestationEvidence()
380 if (err != nil) != tc.wantErr {
381 t.Errorf("measureGPUAttestationEvidence() error = %v, wantErr %v", err, tc.wantErr)
382 }
383 if tc.wantErr && err != nil && !strings.Contains(err.Error(), tc.wantErrStr) {
384 t.Errorf("measureGPUAttestationEvidence() error = %q, want err containing %q", err, tc.wantErrStr)
385 }
386 })
387 }
388 }
389
390 func TestFetchAndWriteTokenSucceeds(t *testing.T) {
391 ctx, cancel := context.WithCancel(context.Background())
392 defer cancel()
393
394 expectedToken := createJWT(t, 5*time.Second)
395
396 runner := ContainerRunner{
397 attestAgent: &fakeAttestationAgent{
398 attestFunc: func(context.Context, agent.AttestAgentOpts) ([]byte, error) {
399 return expectedToken, nil
400 },
401 },
402 logger: logging.SimpleLogger(),
403 }
404
405 if err := runner.fetchAndWriteToken(ctx); err != nil {
406 t.Fatalf("fetchAndWriteToken failed: %v", err)
407 }
408
409 filepath := path.Join(launcherfile.HostTmpPath, launcherfile.AttestationVerifierTokenFilename)
410 data, err := os.ReadFile(filepath)
411 if err != nil {
412 t.Fatalf("Failed to read from %s: %v", filepath, err)
413 }
414
415 if !bytes.Equal(data, expectedToken) {
416 t.Errorf("Token written to file does not match expected token: got %v, want %v", data, expectedToken)
417 }
418 }
419
420 func TestTokenIsNotChangedIfRefreshFails(t *testing.T) {
421 ctx, cancel := context.WithCancel(context.Background())
422 defer cancel()
423
424 expectedToken := createJWT(t, 5*time.Second)
425 ttl := 5 * time.Second
426
427 attestAgent := &fakeAttestationAgent{}
428 attestAgent.attestFunc = func(context.Context, agent.AttestAgentOpts) ([]byte, error) {
429 attestAgent.attMu.Lock()
430 defer func() {
431 attestAgent.attempts = attestAgent.attempts + 1
432 attestAgent.attMu.Unlock()
433 }()
434 if attestAgent.attempts%2 == 0 {
435 return expectedToken, nil
436 }
437 return nil, errors.New("attest unsuccessful")
438 }
439
440 runner := ContainerRunner{
441 attestAgent: attestAgent,
442 logger: logging.SimpleLogger(),
443 }
444
445 if err := runner.fetchAndWriteToken(ctx); err != nil {
446 t.Fatalf("fetchAndWriteToken failed: %v", err)
447 }
448
449 filepath := path.Join(launcherfile.HostTmpPath, launcherfile.AttestationVerifierTokenFilename)
450 data, err := os.ReadFile(filepath)
451 if err != nil {
452 t.Fatalf("Failed to read from %s: %v", filepath, err)
453 }
454
455 if !bytes.Equal(data, expectedToken) {
456 t.Errorf("Initial token written to file does not match expected token: got %v, want %v", data, expectedToken)
457 }
458
459 time.Sleep(ttl)
460
461 data, err = os.ReadFile(filepath)
462 if err != nil {
463 t.Fatalf("Failed to read from %s: %v", filepath, err)
464 }
465
466 if !bytes.Equal(data, expectedToken) {
467 t.Errorf("Expected token to remain the same after unsuccessful refresh attempt: got %v", data)
468 }
469 }
470
471 // testRetryPolicy tries the operation at the following times:
472 // t=0s, .5s, 1.25s. It is canceled before the fourth try.
473 func testRetryPolicyThreeTimes() *backoff.ExponentialBackOff {
474 expBack := backoff.NewExponentialBackOff()
475 expBack.InitialInterval = 500 * time.Millisecond
476 expBack.RandomizationFactor = 0
477 expBack.Multiplier = 1.5
478 expBack.MaxInterval = 1 * time.Second
479 expBack.MaxElapsedTime = 2249 * time.Millisecond
480 return expBack
481 }
482
483 func TestTokenRefreshRetryPolicyFail(t *testing.T) {
484 testRetryPolicyWithNTries(t, 4 /*numTries*/, false /*expectRefresh*/)
485 }
486
487 func TestTokenRefreshRetryPolicy(t *testing.T) {
488 // Test retry policy tries 3 times.
489 for numTries := 1; numTries <= 3; numTries++ {
490 t.Run("RetryPolicyWith"+strconv.Itoa(numTries)+"Tries",
491 func(t *testing.T) { testRetryPolicyWithNTries(t, numTries /*numTries*/, true /*expectRefresh*/) })
492 }
493 }
494
495 func testRetryPolicyWithNTries(t *testing.T, numTries int, expectRefresh bool) {
496 strNum := strconv.Itoa(numTries)
497 t.Logf("testing with %d tries", numTries)
498 ctx, cancel := context.WithCancel(context.Background())
499 defer cancel()
500
501 expectedInitialToken := createJWTWithID(t, "initial token"+strNum, 5*time.Second)
502 expectedRefreshToken := createJWTWithID(t, "refresh token"+strNum, 100*time.Second)
503 // Wait the initial token's 5s plus a second per retry (MaxInterval).
504 ttl := time.Duration(numTries)*time.Second + 5*time.Second
505 retry := -1
506 attestFunc := func(context.Context, agent.AttestAgentOpts) ([]byte, error) {
507 retry++
508 // Success on the initial fetch (subsequent calls use refresher goroutine).
509 if retry == 0 {
510 return expectedInitialToken, nil
511 }
512 if retry == numTries {
513 return expectedRefreshToken, nil
514 }
515 return nil, errors.New("attest unsuccessful")
516 }
517 runner := ContainerRunner{
518 attestAgent: &fakeAttestationAgent{attestFunc: attestFunc},
519 logger: logging.SimpleLogger(),
520 }
521 if err := runner.fetchAndWriteTokenWithRetry(ctx, testRetryPolicyThreeTimes); err != nil {
522 t.Fatalf("fetchAndWriteTokenWithRetry failed: %v", err)
523 }
524 filepath := path.Join(launcherfile.HostTmpPath, launcherfile.AttestationVerifierTokenFilename)
525 data, err := os.ReadFile(filepath)
526 if err != nil {
527 t.Fatalf("failed to read from %s: %v", filepath, err)
528 }
529
530 if !bytes.Equal(data, expectedInitialToken) {
531 gotClaims := extractJWTClaims(t, data)
532 wantClaims := extractJWTClaims(t, expectedInitialToken)
533 t.Errorf("initial token written to file does not match expected token: got ID %v, want ID %v", gotClaims.ID, wantClaims.ID)
534 }
535 time.Sleep(ttl)
536
537 data, err = os.ReadFile(filepath)
538 if err != nil {
539 t.Fatalf("failed to read from %s: %v", filepath, err)
540 }
541
542 // No refresh: the token should match initial token.
543 if !expectRefresh && !bytes.Equal(data, expectedInitialToken) {
544 gotClaims := extractJWTClaims(t, data)
545 wantClaims := extractJWTClaims(t, expectedInitialToken)
546 t.Errorf("token refresher should fail and received token should be the initial token: got ID %v, want ID %v", gotClaims.ID, wantClaims.ID)
547 }
548
549 // Should Refresh: the token should match refreshed token.
550 if expectRefresh && !bytes.Equal(data, expectedRefreshToken) {
551 gotClaims := extractJWTClaims(t, data)
552 wantClaims := extractJWTClaims(t, expectedRefreshToken)
553 t.Errorf("refreshed token did not match expected token: got ID %v, want ID %v", gotClaims.ID, wantClaims.ID)
554 }
555 }
556
557 func TestFetchAndWriteTokenWithTokenRefresh(t *testing.T) {
558 ctx, cancel := context.WithCancel(context.Background())
559 defer cancel()
560
561 expectedToken := createJWT(t, 5*time.Second)
562 expectedRefreshedToken := createJWT(t, 10*time.Second)
563
564 ttl := 5 * time.Second
565
566 attestAgent := &fakeAttestationAgent{}
567 attestAgent.attestFunc = func(context.Context, agent.AttestAgentOpts) ([]byte, error) {
568 attestAgent.attMu.Lock()
569 defer func() {
570 attestAgent.attempts = attestAgent.attempts + 1
571 attestAgent.attMu.Unlock()
572 }()
573 if attestAgent.attempts%2 == 0 {
574 return expectedToken, nil
575 }
576 return expectedRefreshedToken, nil
577 }
578 runner := ContainerRunner{
579 attestAgent: attestAgent,
580 logger: logging.SimpleLogger(),
581 }
582
583 if err := runner.fetchAndWriteToken(ctx); err != nil {
584 t.Fatalf("fetchAndWriteToken failed: %v", err)
585 }
586
587 filepath := path.Join(launcherfile.HostTmpPath, launcherfile.AttestationVerifierTokenFilename)
588 data, err := os.ReadFile(filepath)
589 if err != nil {
590 t.Fatalf("Failed to read from %s: %v", filepath, err)
591 }
592
593 if !bytes.Equal(data, expectedToken) {
594 t.Errorf("Initial token written to file does not match expected token: got %v, want %v", data, expectedToken)
595 }
596
597 // Check that token has not been refreshed yet.
598 data, err = os.ReadFile(filepath)
599 if err != nil {
600 t.Fatalf("Failed to read from %s: %v", filepath, err)
601 }
602
603 if !bytes.Equal(data, expectedToken) {
604 t.Errorf("Token unexpectedly refreshed: got %v, want %v", data, expectedRefreshedToken)
605 }
606
607 time.Sleep(ttl)
608
609 // Check that token has changed.
610 data, err = os.ReadFile(filepath)
611 if err != nil {
612 t.Fatalf("Failed to read from %s: %v", filepath, err)
613 }
614
615 if !bytes.Equal(data, expectedRefreshedToken) {
616 t.Errorf("Refreshed token written to file does not match expected token: got %v, want %v", data, expectedRefreshedToken)
617 }
618 }
619
620 func TestGetNextRefresh(t *testing.T) {
621 // 0 <= random < 1.
622 for _, randNum := range []float64{0, .1415926, .5, .75, .999999999} {
623 // expiration should always be >0.
624 // 0 or negative expiration means the token has already expired.
625 for _, expInt := range []int64{1, 10, 100, 1000, 10000, 1000000} {
626 expDuration := time.Duration(expInt)
627 next := getNextRefreshFromExpiration(expDuration, randNum)
628 if next >= expDuration {
629 t.Errorf("getNextRefreshFromExpiration(%v, %v) = %v next refresh. expected %v (next refresh) < %v (expiration)",
630 expDuration, randNum, next, next, expDuration)
631 }
632 }
633 }
634 }
635
636 func TestInitImageDockerPublic(t *testing.T) {
637 // testing image fetching using a dummy token and a docker repo url
638 containerdClient, err := containerd.New(defaults.DefaultAddress)
639 if err != nil {
640 t.Skipf("test needs containerd daemon: %v", err)
641 }
642
643 ctx := namespaces.WithNamespace(context.Background(), "test")
644 // This is a "valid" token (formatwise)
645 validToken := oauth2.Token{AccessToken: "000000", Expiry: time.Now().Add(time.Hour)}
646 if _, err := initImage(ctx, containerdClient, spec.LaunchSpec{ImageRef: "docker.io/library/hello-world:latest"}, validToken); err != nil {
647 t.Error(err)
648 } else {
649 if err := containerdClient.ImageService().Delete(ctx, "docker.io/library/hello-world:latest"); err != nil {
650 t.Error(err)
651 }
652 }
653
654 invalidToken := oauth2.Token{}
655 if _, err := initImage(ctx, containerdClient, spec.LaunchSpec{ImageRef: "docker.io/library/hello-world:latest"}, invalidToken); err != nil {
656 t.Error(err)
657 } else {
658 if err := containerdClient.ImageService().Delete(ctx, "docker.io/library/hello-world:latest"); err != nil {
659 t.Error(err)
660 }
661 }
662 }
663
664 func TestMeasureCELEvents(t *testing.T) {
665 ctx := context.Background()
666 fakeContainer := &fakeContainer{
667 image: &fakeImage{
668 name: "fake image name",
669 digest: "fake digest",
670 id: "fake id",
671 },
672 args: []string{"fake args"},
673 env: []string{"fake env"},
674 }
675
676 testCases := []struct {
677 name string
678 wantCELEvents []cel.CosType
679 launchSpec spec.LaunchSpec
680 }{
681 {
682 name: "measure full container events and launch separator event",
683 wantCELEvents: []cel.CosType{
684 cel.ImageRefType,
685 cel.ImageDigestType,
686 cel.RestartPolicyType,
687 cel.ImageIDType,
688 cel.ArgType,
689 cel.EnvVarType,
690 cel.OverrideEnvType,
691 cel.OverrideArgType,
692 cel.GPUDeviceAttestationBindingType,
693 cel.MemoryMonitorType,
694 cel.LaunchSeparatorType,
695 },
696 launchSpec: spec.LaunchSpec{
697 Envs: []spec.EnvVar{{Name: "hello", Value: "world"}},
698 Cmd: []string{"hello world"},
699 InstallGpuDriver: true,
700 },
701 },
702 {
703 name: "measure partial container events, memory monitoring event, and launch separator event",
704 wantCELEvents: []cel.CosType{
705 cel.ImageRefType,
706 cel.ImageDigestType,
707 cel.RestartPolicyType,
708 cel.ImageIDType,
709 cel.ArgType,
710 cel.EnvVarType,
711 cel.MemoryMonitorType,
712 cel.LaunchSeparatorType,
713 // GPUDeviceAttestationBindingType is NOT here because InstallGpuDriver is false
714 },
715 launchSpec: spec.LaunchSpec{
716 InstallGpuDriver: false,
717 },
718 },
719 }
720
721 for _, tc := range testCases {
722 t.Run(tc.name, func(t *testing.T) {
723 gotEvents := []cel.CosType{}
724
725 fakeAgent := &fakeAttestationAgent{
726 measureEventFunc: func(content gecel.Content) error {
727 got, _ := content.TLV()
728 tlv := &gecel.TLV{}
729 tlv.UnmarshalBinary(got.Value)
730 gotEvents = append(gotEvents, cel.CosType(tlv.Type))
731 return nil
732 },
733 }
734
735 var fakeGpu gpu.Attester
736 if tc.launchSpec.InstallGpuDriver {
737 fakeGpu = &fakeGPUAttester{
738 attestFunc: func(_ []byte) (any, error) {
739 return &attestationpb.NvidiaAttestationReport{}, nil
740 },
741 }
742 }
743
744 r := ContainerRunner{
745 attestAgent: fakeAgent,
746 gpuAttester: fakeGpu,
747 container: fakeContainer,
748 launchSpec: tc.launchSpec,
749 logger: logging.SimpleLogger(),
750 }
751
752 if err := r.measureCELEvents(ctx); err != nil {
753 t.Errorf("failed to measureCELEvents: %v", err)
754 }
755
756 if !cmp.Equal(gotEvents, tc.wantCELEvents) {
757 t.Errorf("failed to measure CEL events, got %v, but want %v", gotEvents, tc.wantCELEvents)
758 }
759 })
760 }
761 }
762
763 func TestPullImageWithRetries(t *testing.T) {
764 testCases := []struct {
765 name string
766 imagePuller func(int) (containerd.Image, error)
767 wantPass bool
768 }{
769 {
770 name: "success with single attempt",
771 imagePuller: func(int) (containerd.Image, error) { return &fakeImage{}, nil },
772 wantPass: true,
773 },
774 {
775 name: "failure then success",
776 imagePuller: func(attempts int) (containerd.Image, error) {
777 if attempts%2 == 1 {
778 return nil, errors.New("fake error")
779 }
780 return &fakeImage{}, nil
781 },
782 wantPass: true,
783 },
784 {
785 name: "failure with attempts exceeded",
786 imagePuller: func(int) (containerd.Image, error) {
787 return nil, errors.New("fake error")
788 },
789 wantPass: false,
790 },
791 }
792
793 for _, tc := range testCases {
794 t.Run(tc.name, func(t *testing.T) {
795 retryPolicy := func() backoff.BackOff {
796 b := backoff.NewExponentialBackOff()
797 return backoff.WithMaxRetries(b, 2)
798 }
799
800 attempts := 0
801 _, err := pullImageWithRetries(
802 func() (containerd.Image, error) {
803 attempts++
804 return tc.imagePuller(attempts)
805 },
806 retryPolicy)
807 if gotPass := (err == nil); gotPass != tc.wantPass {
808 t.Errorf("pullImageWithRetries failed, got %v, but want %v", gotPass, tc.wantPass)
809 }
810 })
811 }
812 }
813
814 // This ensures fakeContainer implements containerd.Container interface.
815 var _ containerd.Container = &fakeContainer{}
816
817 // This ensures fakeImage implements containerd.Image interface.
818 var _ containerd.Image = &fakeImage{}
819
820 type fakeContainer struct {
821 containerd.Container
822 image containerd.Image
823 args []string
824 env []string
825 }
826
827 func (c *fakeContainer) Image(context.Context) (containerd.Image, error) {
828 return c.image, nil
829 }
830
831 func (c *fakeContainer) Spec(context.Context) (*oci.Spec, error) {
832 return &oci.Spec{Process: &specs.Process{Args: c.args, Env: c.env}}, nil
833 }
834
835 type fakeImage struct {
836 containerd.Image
837 name string
838 digest digest.Digest
839 id digest.Digest
840 }
841
842 func (i *fakeImage) Name() string {
843 return i.name
844 }
845
846 func (i *fakeImage) Target() v1.Descriptor {
847 return v1.Descriptor{Digest: i.digest}
848 }
849
850 func (i *fakeImage) Config(_ context.Context) (v1.Descriptor, error) {
851 return v1.Descriptor{Digest: i.id}, nil
852 }