grpc_test.go181 lines, 6.4 KB
| 1 | package wallet_test |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/ed25519" |
| 6 | "log/slog" |
| 7 | "net" |
| 8 | "slices" |
| 9 | "testing" |
| 10 | "time" |
| 11 | |
| 12 | walletv1 "github.com/fiston-user/payments/gen/wallet/v1" |
| 13 | "github.com/fiston-user/payments/internal/auth" |
| 14 | "github.com/fiston-user/payments/internal/platform/authn" |
| 15 | "github.com/fiston-user/payments/internal/platform/grpcx" |
| 16 | "github.com/fiston-user/payments/internal/platform/idempotency" |
| 17 | "github.com/fiston-user/payments/internal/wallet" |
| 18 | "github.com/fiston-user/payments/internal/wallet/walletclient" |
| 19 | "github.com/google/uuid" |
| 20 | "google.golang.org/genproto/googleapis/rpc/errdetails" |
| 21 | "google.golang.org/grpc" |
| 22 | "google.golang.org/grpc/codes" |
| 23 | "google.golang.org/grpc/credentials/insecure" |
| 24 | "google.golang.org/grpc/health" |
| 25 | healthpb "google.golang.org/grpc/health/grpc_health_v1" |
| 26 | "google.golang.org/grpc/metadata" |
| 27 | "google.golang.org/grpc/status" |
| 28 | "google.golang.org/grpc/test/bufconn" |
| 29 | ) |
| 30 | |
| 31 | // grpcEnv is the wallet's gRPC API, served in memory, the way main wires it. |
| 32 | type grpcEnv struct { |
| 33 | svc *wallet.Service |
| 34 | client *walletclient.Client |
| 35 | health healthpb.HealthClient |
| 36 | signer *auth.Signer // issues access tokens the server accepts |
| 37 | } |
| 38 | |
| 39 | func newGRPC(t *testing.T) grpcEnv { |
| 40 | t.Helper() |
| 41 | pool := newPool(t) |
| 42 | svc := wallet.NewService(wallet.NewStore(pool)) |
| 43 | pub, key, _ := ed25519.GenerateKey(nil) |
| 44 | |
| 45 | // The real server, with every interceptor, on a bufconn listener: an |
| 46 | // in-memory network, so no ports and no flaky timing. |
| 47 | srv := grpcx.NewServer(slog.New(slog.DiscardHandler), insecure.NewCredentials(), |
| 48 | authn.NewVerifier(pub).UnaryInterceptor(healthpb.Health_ServiceDesc.ServiceName)) |
| 49 | walletv1.RegisterWalletServiceServer(srv, wallet.NewGRPCServer(svc, idempotency.NewStore(pool, nil))) |
| 50 | healthpb.RegisterHealthServer(srv, health.NewServer()) |
| 51 | lis := bufconn.Listen(1 << 20) |
| 52 | go srv.Serve(lis) |
| 53 | t.Cleanup(srv.Stop) |
| 54 | |
| 55 | // The real client, dialing the listener instead of the network. |
| 56 | dial := grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { |
| 57 | return lis.DialContext(ctx) |
| 58 | }) |
| 59 | client, err := walletclient.New("passthrough:///bufconn", insecure.NewCredentials(), 5*time.Second, dial) |
| 60 | if err != nil { |
| 61 | t.Fatalf("client: %v", err) |
| 62 | } |
| 63 | t.Cleanup(func() { client.Close() }) |
| 64 | // And a bare connection, without a token, the way a load balancer checks. |
| 65 | conn, err := grpc.NewClient("passthrough:///bufconn", dial, |
| 66 | grpc.WithTransportCredentials(insecure.NewCredentials())) |
| 67 | if err != nil { |
| 68 | t.Fatalf("health client: %v", err) |
| 69 | } |
| 70 | t.Cleanup(func() { conn.Close() }) |
| 71 | return grpcEnv{svc, client, healthpb.NewHealthClient(conn), auth.NewSigner(key, time.Minute)} |
| 72 | } |
| 73 | |
| 74 | // as returns a context that sends an access token for the owner of a wallet. |
| 75 | func (e grpcEnv) as(t *testing.T, wallet uuid.UUID) context.Context { |
| 76 | t.Helper() |
| 77 | w, err := e.svc.Wallet(t.Context(), wallet) |
| 78 | if err != nil { |
| 79 | t.Fatalf("wallet: %v", err) |
| 80 | } |
| 81 | token, err := e.signer.Issue(*w.OwnerID, time.Now()) |
| 82 | if err != nil { |
| 83 | t.Fatalf("issue token: %v", err) |
| 84 | } |
| 85 | return authn.WithToken(t.Context(), token) |
| 86 | } |
| 87 | |
| 88 | func TestGRPCAuth(t *testing.T) { |
| 89 | t.Parallel() |
| 90 | env := newGRPC(t) |
| 91 | mine, theirs := newWallet(t, env.svc, 0), newWallet(t, env.svc, 0) |
| 92 | |
| 93 | tests := []struct { |
| 94 | name string |
| 95 | ctx context.Context |
| 96 | code codes.Code |
| 97 | }{ |
| 98 | {"no token", t.Context(), codes.Unauthenticated}, |
| 99 | {"not a token", authn.WithToken(t.Context(), "hello"), codes.Unauthenticated}, |
| 100 | {"valid token", env.as(t, mine), codes.OK}, |
| 101 | {"someone else's wallet", env.as(t, theirs), codes.NotFound}, |
| 102 | } |
| 103 | for _, tt := range tests { |
| 104 | t.Run(tt.name, func(t *testing.T) { |
| 105 | _, err := env.client.GetBalance(tt.ctx, &walletv1.GetBalanceRequest{WalletId: mine.String()}) |
| 106 | if got := status.Code(err); got != tt.code { |
| 107 | t.Errorf("code = %s, want %s (%v)", got, tt.code, err) |
| 108 | } |
| 109 | }) |
| 110 | } |
| 111 | |
| 112 | // Health checks are public: load balancers have no token. |
| 113 | resp, err := env.health.Check(t.Context(), &healthpb.HealthCheckRequest{}) |
| 114 | if err != nil || resp.GetStatus() != healthpb.HealthCheckResponse_SERVING { |
| 115 | t.Errorf("health = %v, %v; want SERVING", resp, err) |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | func TestGRPCErrors(t *testing.T) { |
| 120 | t.Parallel() |
| 121 | env := newGRPC(t) |
| 122 | alice, bob := newWallet(t, env.svc, 1000), newWallet(t, env.svc, 0) |
| 123 | ctx, from, to := env.as(t, alice), alice.String(), bob.String() |
| 124 | transfer := func(key string, amount int64) *walletv1.TransferRequest { |
| 125 | return &walletv1.TransferRequest{IdempotencyKey: key, FromWalletId: from, ToWalletId: to, |
| 126 | Amount: &walletv1.Money{AmountMinor: amount, Currency: "USD"}} |
| 127 | } |
| 128 | |
| 129 | _, err := env.client.GetBalance(ctx, &walletv1.GetBalanceRequest{WalletId: uuid.NewString()}) |
| 130 | expect(t, "unknown wallet", err, codes.NotFound, "") |
| 131 | _, err = env.client.GetBalance(ctx, &walletv1.GetBalanceRequest{WalletId: "42"}) |
| 132 | expect(t, "malformed ID", err, codes.InvalidArgument, "wallet_id") |
| 133 | _, err = env.client.Transfer(ctx, transfer("", 100)) |
| 134 | expect(t, "no idempotency key", err, codes.InvalidArgument, "idempotency_key") |
| 135 | _, err = env.client.Transfer(ctx, transfer(uuid.NewString(), 5000)) |
| 136 | expect(t, "too much", err, codes.FailedPrecondition, "insufficient_funds") |
| 137 | |
| 138 | // A retry with the same key replays the first response, and says so. |
| 139 | key := uuid.NewString() |
| 140 | first, err := env.client.Transfer(ctx, transfer(key, 600)) |
| 141 | if err != nil { |
| 142 | t.Fatalf("transfer: %v", err) |
| 143 | } |
| 144 | var header metadata.MD |
| 145 | again, err := env.client.Transfer(ctx, transfer(key, 600), grpc.Header(&header)) |
| 146 | if err != nil || again.GetTransactionId() != first.GetTransactionId() { |
| 147 | t.Fatalf("retry = %v, %v; want transaction %s", again, err, first.GetTransactionId()) |
| 148 | } |
| 149 | if got := header.Get("idempotent-replayed"); !slices.Equal(got, []string{"true"}) { |
| 150 | t.Errorf("idempotent-replayed = %v, want [true]", got) |
| 151 | } |
| 152 | _, err = env.client.Transfer(ctx, transfer(key, 700)) |
| 153 | expect(t, "key reused", err, codes.FailedPrecondition, "") |
| 154 | } |
| 155 | |
| 156 | // expect checks that err is a status with the code, and with a detail that |
| 157 | // names detail: the field of a BadRequest, or the reason of an ErrorInfo. |
| 158 | func expect(t *testing.T, name string, err error, code codes.Code, detail string) { |
| 159 | t.Helper() |
| 160 | s := status.Convert(err) |
| 161 | if s.Code() != code { |
| 162 | t.Errorf("%s: code = %s, want %s (%v)", name, s.Code(), code, err) |
| 163 | return |
| 164 | } |
| 165 | if detail == "" { |
| 166 | return |
| 167 | } |
| 168 | for _, d := range s.Details() { |
| 169 | switch d := d.(type) { |
| 170 | case *errdetails.BadRequest: |
| 171 | if d.GetFieldViolations()[0].GetField() == detail { |
| 172 | return |
| 173 | } |
| 174 | case *errdetails.ErrorInfo: |
| 175 | if d.GetReason() == detail { |
| 176 | return |
| 177 | } |
| 178 | } |
| 179 | } |
| 180 | t.Errorf("%s: details = %v, want %q", name, s.Details(), detail) |
| 181 | } |