...
1
2
3
4
5
6
7
8 package impersonate
9
10 import (
11 "context"
12 "fmt"
13 "math/rand"
14 "os"
15 "testing"
16 "time"
17
18 "google.golang.org/api/option"
19 "google.golang.org/api/storage/v1"
20 )
21
22 var (
23
24
25 envBaseSACredentialFile = "API_GO_CLIENT_IMPERSONATE_BASE"
26
27
28 envUserCredentialFile = "API_GO_CLIENT_IMPERSONATE_USER"
29
30
31 envReaderCredentialFile = "API_GO_CLIENT_IMPERSONATE_READER"
32
33 envReaderSA = "API_GO_CLIENT_IMPERSONATE_READER_SA"
34
35
36 envWriterSA = "API_GO_CLIENT_IMPERSONATE_WRITER_SA"
37
38 envProjectID = "GOOGLE_CLOUD_PROJECT"
39 )
40
41 func init() {
42 rand.Seed(time.Now().UnixNano())
43 }
44
45 func TestImpersonatedCredentials(t *testing.T) {
46 ctx := context.Background()
47 projID := os.Getenv(envProjectID)
48 writerSA := os.Getenv(envWriterSA)
49 tests := []struct {
50 name string
51 baseSALocation string
52 delgates []string
53 }{
54 {
55 name: "SA -> SA",
56 baseSALocation: os.Getenv(envReaderCredentialFile),
57 delgates: []string{},
58 },
59 {
60 name: "SA -> Delegate -> SA",
61 baseSALocation: os.Getenv(envBaseSACredentialFile),
62 delgates: []string{os.Getenv(envReaderSA)},
63 },
64 {
65 name: "User Credential -> Delegate -> SA",
66 baseSALocation: os.Getenv(envUserCredentialFile),
67 delgates: []string{os.Getenv(envReaderSA)},
68 },
69 }
70
71 for _, tt := range tests {
72 t.Run(tt.name, func(t *testing.T) {
73 svc, err := storage.NewService(ctx,
74 option.WithCredentialsFile(tt.baseSALocation),
75 option.ImpersonateCredentials(writerSA, tt.delgates...),
76 )
77 if err != nil {
78 t.Fatalf("failed to create client: %v", err)
79 }
80 bucketName := fmt.Sprintf("%s-%d", projID, rand.Int63())
81 if _, err := svc.Buckets.Insert(projID, &storage.Bucket{
82 Name: bucketName,
83 }).Do(); err != nil {
84 t.Fatalf("error creating bucket: %v", err)
85 }
86 if err := svc.Buckets.Delete(bucketName).Do(); err != nil {
87 t.Fatalf("unable to cleanup bucket %q: %v", bucketName, err)
88 }
89 })
90 }
91 }
92
View as plain text