-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathworkflow_client_test.go
More file actions
375 lines (304 loc) · 11.8 KB
/
workflow_client_test.go
File metadata and controls
375 lines (304 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
package billing
import (
"context"
"fmt"
"net"
"os"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/metadata"
"google.golang.org/protobuf/types/known/emptypb"
"github.com/smartcontractkit/chainlink-common/pkg/logger"
"github.com/smartcontractkit/chainlink-common/pkg/nodeauth/jwt/mocks"
pb "github.com/smartcontractkit/chainlink-protos/billing/go"
)
// mockRequest is a simple type that implements fmt.Stringer.
type MockRequest struct {
Field string
}
func (d MockRequest) String() string {
return d.Field
}
// ---------- Test Server Implementation ----------
// testWorkflowServer implements pb.WorkflowServiceServer for testing.
type testWorkflowServer struct {
pb.UnsafeCreditReservationServiceServer
}
func (s *testWorkflowServer) GetOrganizationCreditsByWorkflow(ctx context.Context, req *pb.GetOrganizationCreditsByWorkflowRequest) (*pb.GetOrganizationCreditsByWorkflowResponse, error) {
return &pb.GetOrganizationCreditsByWorkflowResponse{}, nil
}
func (s *testWorkflowServer) GetWorkflowExecutionRates(_ context.Context, _ *pb.GetWorkflowExecutionRatesRequest) (*pb.GetWorkflowExecutionRatesResponse, error) {
return &pb.GetWorkflowExecutionRatesResponse{
RateCards: []*pb.RateCard{
{ResourceType: pb.ResourceType_RESOURCE_TYPE_COMPUTE, MeasurementUnit: pb.MeasurementUnit_MEASUREMENT_UNIT_MILLISECONDS, UnitsPerCredit: "0.00001"},
},
}, nil
}
func (s *testWorkflowServer) ReserveCredits(ctx context.Context, req *pb.ReserveCreditsRequest) (*pb.ReserveCreditsResponse, error) {
return &pb.ReserveCreditsResponse{}, nil
}
func (s *testWorkflowServer) SubmitWorkflowReceipt(ctx context.Context, req *pb.SubmitWorkflowReceiptRequest) (*emptypb.Empty, error) {
return &emptypb.Empty{}, nil
}
// ---------- Test GRPC Dial with TLS Credentials ----------
func TestIntegration_GRPCWithCerts(t *testing.T) {
// Paths to self-signed certificate and key fixtures.
serverCertPath := "./test-fixtures/domain_test.pem"
serverKeyPath := "./test-fixtures/domain_test.key"
// Ensure fixture files exist.
_, err := os.Stat(serverCertPath)
require.NoError(t, err)
_, err = os.Stat(serverKeyPath)
require.NoError(t, err)
// Create server TLS credentials.
serverCreds, err := credentials.NewServerTLSFromFile(serverCertPath, serverKeyPath)
require.NoError(t, err)
// Start a test gRPC server with TLS.
lis, err := net.Listen("tcp", "localhost:0")
require.NoError(t, err)
grpcServer := grpc.NewServer(grpc.Creds(serverCreds))
testSrv := &testWorkflowServer{}
pb.RegisterCreditReservationServiceServer(grpcServer, testSrv)
go func() {
_ = grpcServer.Serve(lis)
}()
defer grpcServer.Stop()
// Create client TLS credentials by loading the server certificate.
clientCreds, err := credentials.NewClientTLSFromFile(serverCertPath, "")
require.NoError(t, err)
certBytes, err := os.ReadFile(serverCertPath)
require.NoError(t, err)
require.NotEmpty(t, certBytes)
addr := lis.Addr().String()
// Create mock JWT manager for testing
mockJWT := mocks.NewJWTGenerator(t)
// Since we're making a real call, expect JWT creation
mockJWT.EXPECT().CreateJWTForRequest(&pb.GetWorkflowExecutionRatesRequest{WorkflowOwner: "test-account", WorkflowRegistryAddress: "0x..", ChainSelector: 1}).Return("test.jwt.token", nil).Once()
lggr := logger.Test(t)
wc, err := NewWorkflowClient(lggr, addr,
WithWorkflowTransportCredentials(clientCreds), // Provided but may be overridden by TLS cert.
WithWorkflowTLSCert(string(certBytes)),
WithJWTGenerator(mockJWT),
WithServerName("localhost"),
)
require.NoError(t, err)
defer func(wc WorkflowClient) {
err2 := wc.Close()
if err2 != nil {
t.Error(err2)
}
}(wc)
// Call a method to verify that the client and server communicate over TLS.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
resp, err := wc.GetWorkflowExecutionRates(ctx, &pb.GetWorkflowExecutionRatesRequest{WorkflowOwner: "test-account", WorkflowRegistryAddress: "0x..", ChainSelector: 1})
require.NoError(t, err)
require.NotNil(t, resp)
assert.Equal(t, pb.ResourceType_RESOURCE_TYPE_COMPUTE, resp.RateCards[0].ResourceType)
assert.Equal(t, pb.MeasurementUnit_MEASUREMENT_UNIT_MILLISECONDS, resp.RateCards[0].MeasurementUnit)
assert.Equal(t, "0.00001", resp.RateCards[0].UnitsPerCredit)
}
func TestIntegration_GRPC_Insecure(t *testing.T) {
// Paths to self-signed certificate and key fixtures.
serverCertPath := "./test-fixtures/domain_test.pem"
serverKeyPath := "./test-fixtures/domain_test.key"
_, err := os.Stat(serverCertPath)
require.NoError(t, err)
_, err = os.Stat(serverKeyPath)
require.NoError(t, err)
serverCreds, err := credentials.NewServerTLSFromFile(serverCertPath, serverKeyPath)
require.NoError(t, err)
lis, err := net.Listen("tcp", "localhost:0")
require.NoError(t, err)
grpcServer := grpc.NewServer(grpc.Creds(serverCreds))
testSrv := &testWorkflowServer{}
pb.RegisterCreditReservationServiceServer(grpcServer, testSrv)
go func() {
_ = grpcServer.Serve(lis)
}()
defer grpcServer.Stop()
addr := lis.Addr().String()
lggr := logger.Test(t)
wc, err := NewWorkflowClient(lggr, addr,
WithWorkflowTransportCredentials(insecure.NewCredentials()),
WithServerName("localhost"),
)
assert.NoError(t, err)
assert.NotNil(t, wc)
_, err = wc.GetWorkflowExecutionRates(context.Background(), nil)
require.Error(t, err)
}
// Test that NewWorkflowClient fails when given an invalid address.
func TestNewWorkflowClient_InvalidAddress(t *testing.T) {
lggr := logger.Test(t)
wc, err := NewWorkflowClient(lggr, "invalid-address",
WithWorkflowTransportCredentials(insecure.NewCredentials()),
WithServerName("localhost"),
)
require.NotNil(t, wc)
require.NoError(t, err)
_, err = wc.GetWorkflowExecutionRates(context.Background(), nil)
require.Error(t, err, "Expected error when dialing an invalid address")
}
// Test that calling Close() twice does not cause a panic.
func TestWorkflowClient_CloseTwice(t *testing.T) {
lis, err := net.Listen("tcp", "localhost:0")
require.NoError(t, err)
grpcServer := grpc.NewServer()
go func() {
_ = grpcServer.Serve(lis)
}()
defer grpcServer.Stop()
addr := lis.Addr().String()
lggr := logger.Test(t)
wc, err := NewWorkflowClient(lggr, addr,
WithWorkflowTransportCredentials(insecure.NewCredentials()),
WithServerName("localhost"),
)
require.NoError(t, err)
require.NotNil(t, wc)
err = wc.Close()
require.NoError(t, err, "First Close() should not return an error")
err = wc.Close()
t.Log("Second Close() call error (if any):", err)
}
// Additional test: Verify that dialGrpc fails if an unreachable address is provided.
func TestWorkflowClient_DialUnreachable(t *testing.T) {
lggr := logger.Test(t)
unreachableAddr := "192.0.2.1:12345" // Reserved for documentation.
wc, err := NewWorkflowClient(lggr, unreachableAddr,
WithWorkflowTransportCredentials(insecure.NewCredentials()),
WithServerName("localhost"),
)
require.NotNil(t, wc)
require.NoError(t, err)
_, err = wc.GetWorkflowExecutionRates(context.Background(), nil)
require.Error(t, err, "Expected dialing an unreachable address to fail")
}
// ---------- Test JWT Token Creation ----------
func TestWorkflowClient_AddJWTAuthToContext(t *testing.T) {
mockJWT := mocks.NewJWTGenerator(t)
req := MockRequest{Field: "test request"}
expectedToken := "mock.jwt.token"
mockJWT.EXPECT().CreateJWTForRequest(req).Return(expectedToken, nil).Once()
wc := &workflowClient{
logger: logger.Test(t),
jwtGenerator: mockJWT,
}
ctx := context.Background()
newCtx, jwtToken, err := wc.addJWTAuth(ctx, req)
require.NoError(t, err)
require.Equal(t, expectedToken, jwtToken, "Expected JWT token to be returned")
// Verify JWT is added to metadata
md, ok := metadata.FromOutgoingContext(newCtx)
require.True(t, ok, "Expected outgoing metadata to be present")
values := md["authorization"]
require.NotEmpty(t, values, "authorization header should be present")
authHeader := values[0]
require.Equal(t, "Bearer "+expectedToken, authHeader, "Authorization header should contain expected token")
}
// Test that client handles the case when no JWT manager is provided.
func TestWorkflowClient_NoSigningKey(t *testing.T) {
ctx := context.Background()
req := MockRequest{Field: "test"}
wc := &workflowClient{
logger: logger.Test(t),
jwtGenerator: nil,
}
newCtx, jwtToken, err := wc.addJWTAuth(ctx, req)
require.NoError(t, err)
require.Empty(t, jwtToken, "Expected empty JWT token when no JWT generator is provided")
// Should return the same context
assert.Equal(t, ctx, newCtx)
}
// Test that client handles JWT manager errors properly
func TestWorkflowClient_VerifySignature_Invalid(t *testing.T) {
mockJWT := mocks.NewJWTGenerator(t)
req := MockRequest{Field: "test"}
mockJWT.EXPECT().CreateJWTForRequest(req).Return("", fmt.Errorf("mock JWT creation error")).Once()
wc := &workflowClient{
logger: logger.Test(t),
jwtGenerator: mockJWT,
}
ctx := context.Background()
_, jwtToken, err := wc.addJWTAuth(ctx, req)
require.Error(t, err)
require.Empty(t, jwtToken, "Expected empty JWT token on error")
assert.Contains(t, err.Error(), "failed to create JWT")
}
func TestWorkflowClient_RepeatedSign(t *testing.T) {
mockJWT := mocks.NewJWTGenerator(t)
req := MockRequest{Field: "repeatable"}
expectedToken := "consistent.jwt.token"
// Expect the same call twice
mockJWT.EXPECT().CreateJWTForRequest(req).Return(expectedToken, nil).Times(2)
wc := &workflowClient{
logger: logger.Test(t),
jwtGenerator: mockJWT,
}
ctx1 := context.Background()
newCtx1, jwtToken1, err := wc.addJWTAuth(ctx1, req)
require.NoError(t, err)
require.Equal(t, expectedToken, jwtToken1, "Expected JWT token to match")
ctx2 := context.Background()
newCtx2, jwtToken2, err := wc.addJWTAuth(ctx2, req)
require.NoError(t, err)
require.Equal(t, expectedToken, jwtToken2, "Expected JWT token to match")
// Both should have the same token since we're mocking the same response
md1, ok := metadata.FromOutgoingContext(newCtx1)
require.True(t, ok)
md2, ok := metadata.FromOutgoingContext(newCtx2)
require.True(t, ok)
assert.Equal(t, md1["authorization"], md2["authorization"], "Expected same authorization header for same request")
}
func TestWorkflowClient_SubmitWorkflowReceipt_WithLogging(t *testing.T) {
// Start a test gRPC server
lis, err := net.Listen("tcp", "localhost:0")
require.NoError(t, err)
grpcServer := grpc.NewServer()
testSrv := &testWorkflowServer{}
pb.RegisterCreditReservationServiceServer(grpcServer, testSrv)
go func() {
_ = grpcServer.Serve(lis)
}()
defer grpcServer.Stop()
addr := lis.Addr().String()
// Create mock JWT manager for testing
mockJWT := mocks.NewJWTGenerator(t)
expectedToken := "test.jwt.token.for.logging"
// Create a test request
req := &pb.SubmitWorkflowReceiptRequest{
WorkflowOwner: "test-owner",
WorkflowId: "test-workflow-id",
WorkflowExecutionId: "test-execution-id",
WorkflowRegistryAddress: "0x123",
WorkflowRegistryChainSelector: 1,
CreditsConsumed: "100",
}
// Expect JWT creation
mockJWT.EXPECT().CreateJWTForRequest(req).Return(expectedToken, nil).Once()
lggr := logger.Test(t)
wc, err := NewWorkflowClient(lggr, addr,
WithWorkflowTransportCredentials(insecure.NewCredentials()),
WithJWTGenerator(mockJWT),
WithServerName("localhost"),
)
require.NoError(t, err)
defer func(wc WorkflowClient) {
_ = wc.Close()
}(wc)
// Call SubmitWorkflowReceipt
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
resp, err := wc.SubmitWorkflowReceipt(ctx, req)
require.NoError(t, err)
require.NotNil(t, resp)
// Note: In a real test, we would inspect the logs to verify the detailed
// logging is happening. For now, we're just ensuring the method works
// with the new logging code.
}