|
| 1 | +/* |
| 2 | +Copyright 2023 Chainguard, Inc. |
| 3 | +SPDX-License-Identifier: Apache-2.0 |
| 4 | +*/ |
| 5 | + |
| 6 | +package kms |
| 7 | + |
| 8 | +import ( |
| 9 | + "context" |
| 10 | + "net" |
| 11 | + "testing" |
| 12 | + |
| 13 | + kms "cloud.google.com/go/kms/apiv1" |
| 14 | + "cloud.google.com/go/kms/apiv1/kmspb" |
| 15 | + "github.com/golang-jwt/jwt/v4" |
| 16 | + "google.golang.org/api/option" |
| 17 | + "google.golang.org/grpc" |
| 18 | + "google.golang.org/grpc/credentials/insecure" |
| 19 | +) |
| 20 | + |
| 21 | +type fakeGCPKMS struct { |
| 22 | + kmspb.UnimplementedKeyManagementServiceServer |
| 23 | +} |
| 24 | + |
| 25 | +func (fakeGCPKMS) AsymmetricSign(context.Context, *kmspb.AsymmetricSignRequest) (*kmspb.AsymmetricSignResponse, error) { |
| 26 | + return &kmspb.AsymmetricSignResponse{ |
| 27 | + Signature: []byte("fake"), |
| 28 | + }, nil |
| 29 | +} |
| 30 | + |
| 31 | +func TestGCP(t *testing.T) { |
| 32 | + ctx := context.Background() |
| 33 | + |
| 34 | + // Setup the fake server. |
| 35 | + impl := &fakeGCPKMS{} |
| 36 | + l, err := net.Listen("tcp", "localhost:0") |
| 37 | + if err != nil { |
| 38 | + t.Fatal(err) |
| 39 | + } |
| 40 | + gsrv := grpc.NewServer() |
| 41 | + kmspb.RegisterKeyManagementServiceServer(gsrv, impl) |
| 42 | + fakeServerAddr := l.Addr().String() |
| 43 | + go func() { |
| 44 | + if err := gsrv.Serve(l); err != nil { |
| 45 | + panic(err) |
| 46 | + } |
| 47 | + }() |
| 48 | + |
| 49 | + // Create a client. |
| 50 | + client, err := kms.NewKeyManagementClient(ctx, |
| 51 | + option.WithEndpoint(fakeServerAddr), |
| 52 | + option.WithoutAuthentication(), |
| 53 | + option.WithGRPCDialOption(grpc.WithTransportCredentials(insecure.NewCredentials())), |
| 54 | + ) |
| 55 | + if err != nil { |
| 56 | + t.Fatal(err) |
| 57 | + } |
| 58 | + |
| 59 | + signer, err := NewGCP(ctx, client, "foo") |
| 60 | + if err != nil { |
| 61 | + t.Fatal(err) |
| 62 | + } |
| 63 | + |
| 64 | + if _, err := signer.Sign(jwt.RegisteredClaims{ |
| 65 | + Subject: "foo", |
| 66 | + Issuer: "bar", |
| 67 | + }); err != nil { |
| 68 | + t.Fatal(err) |
| 69 | + } |
| 70 | +} |
0 commit comments