diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 831d86f..571621f 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -6,9 +6,13 @@ on: - main workflow_dispatch: +permissions: + contents: read + jobs: build: runs-on: ubuntu-latest + steps: - name: Checkout uses: actions/checkout@v7 @@ -17,9 +21,13 @@ jobs: uses: actions/setup-go@v7 with: go-version: "1.27.x" + check-latest: true + cache-dependency-path: | + go.sum + tools/go.sum - - name: Verify - run: make verify + - name: Go version + run: go version - name: Verify - run: make verify + run: make verify \ No newline at end of file diff --git a/.golangci.yml b/.golangci.yml index bf6b1d3..eafdb9f 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -85,6 +85,10 @@ linters: - goconst - lll + - path: ^(model/matcher/(grpc_message|string)\.go)$ + linters: + - dupl + - path: ^api/ linters: - dupl @@ -98,6 +102,30 @@ linters: linters: - lll + - path: ^(execute/worker/reporter/config\.go)$ + linters: + - lll + + - path: ^(execute/worker/http/evaluate\.go)$ + linters: + - lll + + - path: ^(execute/runtime/service/(grpc|http)/config\.go)$ + linters: + - lll + + - path: ^execute/runtime/router/(grpc|http)/config\.go$ + linters: + - lll + + - path: ^execute/(call|worker)/config\.go$ + linters: + - lll + + - path: ^(transport/config\.go)$ + linters: + - lll + - path: ^execute/runtime/router/(grpc|http)/router\.go$ linters: - funlen diff --git a/Makefile b/Makefile index 6df5802..5e580d1 100644 --- a/Makefile +++ b/Makefile @@ -24,6 +24,11 @@ lint: install-golangci-lint @echo "Running linter..." $(GOLANGCI_LINT) run +.PHONY: vulncheck +vulncheck: install-govulncheck + @echo "Checking for known vulnerabilities..." + $(GOVULNCHECK) ./... + .PHONY: test test: @echo "Running tests..." @@ -47,5 +52,5 @@ test-race: @go test ./... -race -count=1 -timeout=600s .PHONY: verify -verify: mockgen lint test-race +verify: mockgen lint vulncheck test-race @echo "All verifications passed successfully." diff --git a/api/service_run_test.go b/api/service_run_test.go index 58619a6..4a87b84 100644 --- a/api/service_run_test.go +++ b/api/service_run_test.go @@ -269,7 +269,7 @@ func TestService_RunTestSuite(t *testing.T) { ) testRepo.EXPECT(). - GetByTag(gomock.Any(), "smoke"). + GetByTag(gomock.Any(), "smoke", 11). Return(nil, nil) launcher := &fakeLauncher{} @@ -368,7 +368,7 @@ func TestService_RunTestSuite(t *testing.T) { // test-a is deliberately returned again by the tag lookup. testRepo.EXPECT(). - GetByTag(gomock.Any(), "smoke"). + GetByTag(gomock.Any(), "smoke", 11). Return([]repository.Test{ *runRepositoryTest("test-b", "test-b"), *runRepositoryTest("test-a", "test-a"), @@ -481,7 +481,7 @@ func TestService_RunTestSuite(t *testing.T) { ) testRepo.EXPECT(). - GetByTag(gomock.Any(), "smoke"). + GetByTag(gomock.Any(), "smoke", 3). Return([]repository.Test{ *runRepositoryTest("test-a", "test-a"), *runRepositoryTest("test-b", "test-b"), @@ -560,7 +560,7 @@ func TestService_RunTestSuite(t *testing.T) { ) testRepo.EXPECT(). - GetByTag(gomock.Any(), "smoke"). + GetByTag(gomock.Any(), "smoke", 11). Return([]repository.Test{ *runRepositoryTest("test-a", "test-a"), }, nil) @@ -604,6 +604,109 @@ func TestService_RunTestSuite(t *testing.T) { ) } }) + + t.Run("overlapping selectors at limit", func(t *testing.T) { + ctrl := gomock.NewController(t) + + environmentRepo := mock.NewMockResourceRepository[repository.Environment](ctrl) + testSuiteRepo := mock.NewMockResourceRepository[repository.TestSuite](ctrl) + testRepo := mock.NewMockTestRepository(ctrl) + + environmentRepo.EXPECT(). + GetIDsByID(gomock.Any(), "env"). + Return([]string{"environment-001"}, nil) + + environmentRepo.EXPECT(). + Get(gomock.Any(), "environment-001"). + Return(runRepositoryEnvironment(), nil) + + testSuiteRepo.EXPECT(). + GetIDsByID(gomock.Any(), "suite"). + Return([]string{"testsuite-001"}, nil) + + testSuiteRepo.EXPECT(). + Get(gomock.Any(), "testsuite-001"). + Return( + runRepositoryTestSuite( + model.TestSelectorsSpec{ + IDs: []string{"test-a"}, + Tags: []string{"smoke"}, + }, + ), + nil, + ) + + testRepo.EXPECT(). + GetIDsByID(gomock.Any(), "test-a"). + Return([]string{"test-a"}, nil) + + testRepo.EXPECT(). + Get(gomock.Any(), "test-a"). + Return(runRepositoryTest("test-a", "test-a"), nil) + + // Two matching tests, one already resolved by ID. + testRepo.EXPECT(). + GetByTag(gomock.Any(), "smoke", 3). + Return([]repository.Test{ + *runRepositoryTest("test-a", "test-a"), + *runRepositoryTest("test-b", "test-b"), + }, nil) + + launcher := &fakeLauncher{ + startTestSuiteResult: "suite-execution-001", + } + + service := newRunService( + t, + Repositories{ + Environment: environmentRepo, + Test: testRepo, + TestSuite: testSuiteRepo, + }, + launcher, + 2, + ) + + got, err := service.RunTestSuite( + t.Context(), + TestSuiteRunRequest{ + EnvironmentRef: "env", + TestSuiteRef: "suite", + }, + ) + if err != nil { + t.Fatalf("RunTestSuite() error = %v", err) + } + + if got != "suite-execution-001" { + t.Errorf( + "RunTestSuite() = %q, want suite-execution-001", + got, + ) + } + + if launcher.startTestSuiteCalls != 1 { + t.Fatalf( + "StartTestSuite calls = %d, want 1", + launcher.startTestSuiteCalls, + ) + } + + gotIDs := make([]string, len(launcher.testSuiteRequest.Tests)) + for i, test := range launcher.testSuiteRequest.Tests { + gotIDs[i] = test.ID + } + + wantIDs := []string{"test-a", "test-b"} + + if !reflect.DeepEqual(gotIDs, wantIDs) { + t.Errorf( + "Resolved test IDs = %v, want %v", + gotIDs, + wantIDs, + ) + } + }) } type fakeLauncher struct { @@ -682,11 +785,11 @@ func validEnvironmentSpec() model.EnvironmentSpec { return model.EnvironmentSpec{ Services: []model.ServiceSpec{ { - ID: "api", - Kind: model.ServiceKindHTTP, - Mode: model.ServiceModeReal, - Address: "api:8080", - HTTPTarget: "http://localhost:8080", + ID: "api", + Kind: model.ServiceKindHTTP, + Mode: model.ServiceModeReal, + E2EnginePort: 8080, + Target: "http://localhost:8080", }, }, } diff --git a/api/testsuite.go b/api/testsuite.go index 07815b5..061cedd 100644 --- a/api/testsuite.go +++ b/api/testsuite.go @@ -150,6 +150,7 @@ func (s *Service) resolveTestSuiteTests( selectors model.TestSelectorsSpec, ) ([]model.Test, error) { tests := make(map[string]model.Test) + limit := s.runtimeCfg.MaxResolvedTests for _, ref := range selectors.IDs { test, err := s.GetTest(ctx, ref) @@ -158,6 +159,9 @@ func (s *Service) resolveTestSuiteTests( } tests[test.ID] = *test + if errLimit := checkResolvedTestsLimit(len(tests), limit); errLimit != nil { + return nil, errLimit + } } for _, ref := range selectors.Names { @@ -167,16 +171,26 @@ func (s *Service) resolveTestSuiteTests( } tests[test.ID] = *test + if errLimit := checkResolvedTestsLimit(len(tests), limit); errLimit != nil { + return nil, errLimit + } } for _, tag := range selectors.Tags { - matched, err := s.resources.GetTestsByTag(ctx, tag) + matched, err := s.resources.GetTestsByTag(ctx, tag, limit+1) if err != nil { return nil, err } + if len(matched) > limit { + return nil, checkResolvedTestsLimit(len(matched), limit) + } + for i := range matched { tests[matched[i].ID] = matched[i] + if errLimit := checkResolvedTestsLimit(len(tests), limit); errLimit != nil { + return nil, errLimit + } } } @@ -184,14 +198,6 @@ func (s *Service) resolveTestSuiteTests( return nil, errors.ErrNoTestsResolved } - if len(tests) > s.runtimeCfg.MaxResolvedTests { - return nil, errorc.With( - errors.ErrExceededTestsLimit, - errorc.Int(keys.TestSuiteMaxTestsNumber, s.runtimeCfg.MaxResolvedTests), - errorc.Int(keys.TestSuiteResolvedTestsNumber, len(tests)), - ) - } - ids := make([]string, 0, len(tests)) for id := range tests { ids = append(ids, id) @@ -206,3 +212,14 @@ func (s *Service) resolveTestSuiteTests( return result, nil } + +func checkResolvedTestsLimit(actual, limit int) error { + if actual > limit { + return errorc.With( + errors.ErrExceededTestsLimit, + errorc.Int(keys.TestSuiteMaxTestsNumber, limit), + ) + } + + return nil +} diff --git a/execute/address/resolver.go b/execute/address/resolver.go new file mode 100644 index 0000000..32ba306 --- /dev/null +++ b/execute/address/resolver.go @@ -0,0 +1,118 @@ +package address + +import ( + "net" + "net/url" + "strconv" + "strings" + + "github.com/ygrebnov/errorc" + + "github.com/e2engine/core/pkg/errors" +) + +// Resolver substitutes explicitly mapped hostnames in outgoing addresses. +// Hostname mappings are restricted to DNS names and IPv4 addresses. +type Resolver struct { + hosts map[string]string +} + +func NewResolver(hosts map[string]string) (*Resolver, error) { + copyHosts := make(map[string]string, len(hosts)) + + for from, to := range hosts { + if !validHostname(from) || !validHostname(to) { + return nil, errorc.With( + errors.ErrInvalidHostnameMapping, + ) + } + + copyHosts[from] = to + } + + return &Resolver{hosts: copyHosts}, nil +} + +// ResolveHTTPURL replaces only the hostname of an absolute HTTP(S) URL. +func (r *Resolver) ResolveHTTPURL(value string) (string, error) { + u, err := url.Parse(value) + if err != nil { + return "", errors.ErrInvalidHTTPURL + } + + if (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" { + return "", errors.ErrInvalidHTTPURL + } + + if u.User != nil { + return "", errors.ErrInvalidHTTPURL + } + + if mapped, ok := r.hosts[u.Hostname()]; ok { + if port := u.Port(); port != "" { + u.Host = net.JoinHostPort(mapped, port) + } else if strings.Contains(mapped, ":") { + u.Host = "[" + strings.Trim(mapped, "[]") + "]" + } else { + u.Host = mapped + } + } + + return u.String(), nil +} + +// ResolveGRPCTarget replaces only the hostname in a host:port target. +func (r *Resolver) ResolveGRPCTarget(value string) (string, error) { + host, port, err := net.SplitHostPort(value) + if err != nil { + return "", errors.ErrInvalidGRPCTarget + } + + if host == "" { + return "", errors.ErrInvalidGRPCTarget + } + + portNumber, err := strconv.ParseUint(port, 10, 16) + if err != nil || portNumber == 0 { + return "", errors.ErrInvalidGRPCTarget + } + + if mapped, ok := r.hosts[host]; ok { + return net.JoinHostPort(mapped, port), nil + } + + return value, nil +} + +func validHostname(value string) bool { + if value == "" || len(value) > 253 { + return false + } + + if ip := net.ParseIP(value); ip != nil { + return ip.To4() != nil + } + + for _, label := range strings.Split(value, ".") { + if label == "" || len(label) > 63 { + return false + } + + if label[0] == '-' || label[len(label)-1] == '-' { + return false + } + + for _, c := range label { + if (c >= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || + c == '-' { + continue + } + + return false + } + } + + return true +} diff --git a/execute/address/resolver_test.go b/execute/address/resolver_test.go new file mode 100644 index 0000000..7fa58dc --- /dev/null +++ b/execute/address/resolver_test.go @@ -0,0 +1,553 @@ +package address_test + +import ( + "strings" + "testing" + + "github.com/e2engine/core/execute/address" +) + +func TestNewResolver(t *testing.T) { + tests := []struct { + name string + hosts map[string]string + wantErr bool + }{ + { + name: "nil mappings", + }, + { + name: "empty mappings", + hosts: map[string]string{}, + }, + { + name: "valid mappings", + hosts: map[string]string{ + "telemetry-service": "127.0.0.1", + "dynamodb": "localhost", + }, + }, + { + name: "empty source hostname", + hosts: map[string]string{ + "": "127.0.0.1", + }, + wantErr: true, + }, + { + name: "empty destination hostname", + hosts: map[string]string{ + "dynamodb": "", + }, + wantErr: true, + }, + { + name: "source contains port", + hosts: map[string]string{ + "dynamodb:8000": "127.0.0.1", + }, + wantErr: true, + }, + { + name: "destination contains port", + hosts: map[string]string{ + "dynamodb": "127.0.0.1:8000", + }, + wantErr: true, + }, + { + name: "source contains scheme", + hosts: map[string]string{ + "http://dynamodb": "127.0.0.1", + }, + wantErr: true, + }, + { + name: "destination contains scheme", + hosts: map[string]string{ + "dynamodb": "http://127.0.0.1", + }, + wantErr: true, + }, + { + name: "source contains whitespace", + hosts: map[string]string{ + "my service": "127.0.0.1", + }, + wantErr: true, + }, + { + name: "destination contains whitespace", + hosts: map[string]string{ + "dynamodb": "my host", + }, + wantErr: true, + }, + { + name: "source contains userinfo separator", + hosts: map[string]string{ + "user@host": "127.0.0.1", + }, + wantErr: true, + }, + { + name: "destination contains userinfo separator", + hosts: map[string]string{ + "api": "trusted@attacker.example", + }, + wantErr: true, + }, + { + name: "destination contains query marker", + hosts: map[string]string{ + "api": "host?query", + }, + wantErr: true, + }, + { + name: "destination contains fragment marker", + hosts: map[string]string{ + "api": "host#fragment", + }, + wantErr: true, + }, + { + name: "source starts with hyphen", + hosts: map[string]string{ + "-api": "localhost", + }, + wantErr: true, + }, + { + name: "destination ends with hyphen", + hosts: map[string]string{ + "api": "host-", + }, + wantErr: true, + }, + { + name: "empty DNS label", + hosts: map[string]string{ + "api..internal": "localhost", + }, + wantErr: true, + }, + { + name: "DNS label too long", + hosts: map[string]string{ + "api": strings.Repeat("a", 64) + ".internal", + }, + wantErr: true, + }, + { + name: "hostname too long", + hosts: map[string]string{ + "api": strings.Repeat("a", 63) + "." + + strings.Repeat("b", 63) + "." + + strings.Repeat("c", 63) + "." + + strings.Repeat("d", 63), + }, + wantErr: true, + }, + { + name: "IPv6 mapping rejected", + hosts: map[string]string{ + "api": "::1", + }, + wantErr: true, + }, + { + name: "valid hyphenated hostname", + hosts: map[string]string{ + "api-service": "svc-1.internal", + }, + }, + { + name: "valid mixed-case hostname", + hosts: map[string]string{ + "API": "Svc.Internal", + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + resolver, err := address.NewResolver(tt.hosts) + + if tt.wantErr { + if err == nil { + t.Fatal("expected an error") + } + + return + } + + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + if resolver == nil { + t.Fatal("expected non-nil resolver") + } + }) + } +} + +func TestNewResolver_DefensiveCopy(t *testing.T) { + hosts := map[string]string{ + "dynamodb": "127.0.0.1", + } + + resolver, err := address.NewResolver(hosts) + if err != nil { + t.Fatalf("NewResolver() error: %v", err) + } + + // Mutating the original map must not affect the resolver. + hosts["dynamodb"] = "192.168.1.10" + hosts["telemetry-service"] = "127.0.0.1" + + got, err := resolver.ResolveHTTPURL("http://dynamodb:8000") + if err != nil { + t.Fatalf("ResolveHTTPURL() error: %v", err) + } + + if want := "http://127.0.0.1:8000"; got != want { + t.Errorf("ResolveHTTPURL() = %q, want %q", got, want) + } + + got, err = resolver.ResolveHTTPURL("http://telemetry-service:3000") + if err != nil { + t.Fatalf("ResolveHTTPURL() error: %v", err) + } + + if want := "http://telemetry-service:3000"; got != want { + t.Errorf("ResolveHTTPURL() = %q, want %q", got, want) + } +} + +func TestResolver_ResolveHTTPURL(t *testing.T) { + tests := []struct { + name string + hosts map[string]string + input string + want string + wantErr bool + }{ + { + name: "replace hostname", + hosts: map[string]string{ + "telemetry-service": "127.0.0.1", + }, + input: "http://telemetry-service:3000/health", + want: "http://127.0.0.1:3000/health", + }, + { + name: "replace hostname with another hostname", + hosts: map[string]string{ + "telemetry-service": "telemetry.internal", + }, + input: "http://telemetry-service:3000/health", + want: "http://telemetry.internal:3000/health", + }, + { + name: "preserve HTTPS scheme", + hosts: map[string]string{ + "api": "api.internal", + }, + input: "https://api:8443/v1/events", + want: "https://api.internal:8443/v1/events", + }, + { + name: "preserve path and query", + hosts: map[string]string{ + "api": "127.0.0.1", + }, + input: "http://api:3000/v1/events?limit=10&offset=20", + want: "http://127.0.0.1:3000/v1/events?limit=10&offset=20", + }, + { + name: "preserve escaped path", + hosts: map[string]string{ + "api": "127.0.0.1", + }, + input: "http://api:3000/v1/items/a%2Fb", + want: "http://127.0.0.1:3000/v1/items/a%2Fb", + }, + { + name: "replace hostname without port", + hosts: map[string]string{ + "api": "api.internal", + }, + input: "https://api/health", + want: "https://api.internal/health", + }, + { + name: "unmapped hostname", + hosts: map[string]string{ + "dynamodb": "127.0.0.1", + }, + input: "http://telemetry-service:3000/health", + want: "http://telemetry-service:3000/health", + }, + { + name: "no mappings", + input: "http://telemetry-service:3000/health", + want: "http://telemetry-service:3000/health", + }, + { + name: "external hostname unchanged", + hosts: map[string]string{ + "telemetry-service": "127.0.0.1", + }, + input: "https://api.telemetry.com/health", + want: "https://api.telemetry.com/health", + }, + { + name: "explicit external hostname mapping", + hosts: map[string]string{ + "api.telemetry.com": "staging.telemetry.internal", + }, + input: "https://api.telemetry.com/v1/events", + want: "https://staging.telemetry.internal/v1/events", + }, + { + name: "IPv4 destination", + hosts: map[string]string{ + "api": "192.168.1.10", + }, + input: "http://api:3000/health", + want: "http://192.168.1.10:3000/health", + }, + { + name: "IPv6 source hostname unchanged", + hosts: map[string]string{ + "api": "127.0.0.1", + }, + input: "http://[::1]:3000/health", + want: "http://[::1]:3000/health", + }, + { + name: "invalid URL", + input: "://invalid", + wantErr: true, + }, + { + name: "missing hostname", + input: "http:///health", + wantErr: true, + }, + { + name: "unsupported scheme", + input: "ftp://api:3000/health", + wantErr: true, + }, + { + name: "relative URL", + input: "/health", + wantErr: true, + }, + { + name: "userinfo rejected", + input: "https://username:password@api.example.com/health", + wantErr: true, + }, + { + name: "mapped hostname with userinfo rejected", + hosts: map[string]string{ + "api": "127.0.0.1", + }, + input: "http://user@api:3000/health", + wantErr: true, + }, + { + name: "malformed URL escape", + input: "http://api/%zz", + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + resolver, err := address.NewResolver(tt.hosts) + if err != nil { + t.Fatalf("NewResolver() error: %v", err) + } + + got, err := resolver.ResolveHTTPURL(tt.input) + + if tt.wantErr { + if err == nil { + t.Fatalf( + "ResolveHTTPURL(%q): expected error, got %q", + tt.input, + got, + ) + } + + return + } + + if err != nil { + t.Fatalf( + "ResolveHTTPURL(%q) error: %v", + tt.input, + err, + ) + } + + if got != tt.want { + t.Errorf( + "ResolveHTTPURL(%q) = %q, want %q", + tt.input, + got, + tt.want, + ) + } + }) + } +} + +func TestResolver_ResolveGRPCTarget(t *testing.T) { + tests := []struct { + name string + hosts map[string]string + input string + want string + wantErr bool + }{ + { + name: "replace hostname", + hosts: map[string]string{ + "account": "127.0.0.1", + }, + input: "account:50051", + want: "127.0.0.1:50051", + }, + { + name: "replace hostname with another hostname", + hosts: map[string]string{ + "account": "account.internal", + }, + input: "account:50051", + want: "account.internal:50051", + }, + { + name: "preserve port", + hosts: map[string]string{ + "account": "192.168.1.10", + }, + input: "account:8443", + want: "192.168.1.10:8443", + }, + { + name: "unmapped hostname", + hosts: map[string]string{ + "dynamodb": "127.0.0.1", + }, + input: "account:50051", + want: "account:50051", + }, + { + name: "no mappings", + input: "account:50051", + want: "account:50051", + }, + { + name: "IPv4 target unchanged", + hosts: map[string]string{ + "account": "127.0.0.1", + }, + input: "192.168.1.20:50051", + want: "192.168.1.20:50051", + }, + { + name: "IPv6 target unchanged", + hosts: map[string]string{ + "account": "127.0.0.1", + }, + input: "[::1]:50051", + want: "[::1]:50051", + }, + { + name: "missing port", + input: "account", + wantErr: true, + }, + { + name: "missing colon", + input: "account50051", + wantErr: true, + }, + { + name: "unbracketed IPv6", + input: "::1:50051", + wantErr: true, + }, + { + name: "empty target", + input: "", + wantErr: true, + }, + { + name: "missing hostname", + input: ":50051", + wantErr: true, + }, + { + name: "invalid port", + input: "account:abc", + wantErr: true, + }, + { + name: "port out of range", + input: "account:65536", + wantErr: true, + }, + { + name: "zero port", + input: "account:0", + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + resolver, err := address.NewResolver(tt.hosts) + if err != nil { + t.Fatalf("NewResolver() error: %v", err) + } + + got, err := resolver.ResolveGRPCTarget(tt.input) + + if tt.wantErr { + if err == nil { + t.Fatalf( + "ResolveGRPCTarget(%q): expected error, got %q", + tt.input, + got, + ) + } + + return + } + + if err != nil { + t.Fatalf( + "ResolveGRPCTarget(%q) error: %v", + tt.input, + err, + ) + } + + if got != tt.want { + t.Errorf( + "ResolveGRPCTarget(%q) = %q, want %q", + tt.input, + got, + tt.want, + ) + } + }) + } +} diff --git a/execute/call/call.go b/execute/call/call.go index 86ad49d..ae098a1 100644 --- a/execute/call/call.go +++ b/execute/call/call.go @@ -1,7 +1,14 @@ package call +import ( + "slices" + + "github.com/e2engine/core/internal/util" +) + type Recorder interface { - Record(call Call) + Record(call Call) error + Err() error } type Reader interface { @@ -17,3 +24,88 @@ type Call struct { MockFixtureMatched bool } + +// Size returns the size of variable-length data retained by the call. +// It excludes Go object, map, slice, and allocator overhead. +func (c Call) Size() int64 { + size := int64( + len(c.TestExecutionID) + + len(c.ServiceID), + ) + + if c.HTTP != nil { + size += int64( + len(c.HTTP.Request.Method) + + len(c.HTTP.Request.Path), + ) + + size += stringValuesSize(c.HTTP.Request.Query) + size += stringValuesSize(c.HTTP.Request.Headers) + size += int64(len(c.HTTP.Request.Body)) + + size += stringValuesSize(c.HTTP.Response.Headers) + size += int64(len(c.HTTP.Response.Body)) + } + + if c.GRPC != nil { + size += int64( + len(c.GRPC.Request.Service) + + len(c.GRPC.Request.Method), + ) + + size += stringValuesSize(c.GRPC.Request.Metadata) + size += int64(len(c.GRPC.Request.Message)) + + size += int64(len(c.GRPC.Response.Status)) + size += stringValuesSize(c.GRPC.Response.Metadata) + size += int64(len(c.GRPC.Response.Message)) + } + + return size +} + +// Clone returns an independent copy of the call and its mutable data. +func (c Call) Clone() Call { + clone := c + + if c.HTTP != nil { + httpCall := *c.HTTP + + httpCall.Request.Query = util.CloneStringSliceMap(c.HTTP.Request.Query) + httpCall.Request.Headers = c.HTTP.Request.Headers.Clone() + httpCall.Request.Body = slices.Clone(c.HTTP.Request.Body) + + httpCall.Response.Headers = c.HTTP.Response.Headers.Clone() + httpCall.Response.Body = slices.Clone(c.HTTP.Response.Body) + + clone.HTTP = &httpCall + } + + if c.GRPC != nil { + grpcCall := *c.GRPC + + grpcCall.Request.Metadata = util.CloneStringSliceMap(c.GRPC.Request.Metadata) + grpcCall.Request.Message = slices.Clone(c.GRPC.Request.Message) + + grpcCall.Response.Metadata = util.CloneStringSliceMap(c.GRPC.Response.Metadata) + grpcCall.Response.Message = slices.Clone(c.GRPC.Response.Message) + + clone.GRPC = &grpcCall + } + + return clone +} + +func stringValuesSize(values map[string][]string) int64 { + var size int64 + + for key, items := range values { + size += int64(len(key)) + + for _, item := range items { + size += int64(len(item)) + } + } + + return size +} diff --git a/execute/call/call_test.go b/execute/call/call_test.go new file mode 100644 index 0000000..6b673a3 --- /dev/null +++ b/execute/call/call_test.go @@ -0,0 +1,442 @@ +package call + +import ( + "net/http" + "reflect" + "testing" +) + +func TestCallSize(t *testing.T) { + tests := []struct { + name string + call Call + want int64 + }{ + { + name: "empty call", + call: Call{}, + want: 0, + }, + { + name: "identifiers only", + call: Call{ + TestExecutionID: "exec", + ServiceID: "service", + }, + want: 11, + }, + { + name: "empty HTTP call", + call: Call{ + HTTP: &HTTPCall{}, + }, + want: 0, + }, + { + name: "HTTP request and response", + call: Call{ + TestExecutionID: "e", + ServiceID: "s", + HTTP: &HTTPCall{ + Request: HTTPRequest{ + Method: "GET", + Path: "/p", + Query: map[string][]string{ + "q": {"ab", "c"}, + }, + Headers: http.Header{ + "X-Test": {"v"}, + }, + Body: []byte("abc"), + BodyComplete: true, + }, + Response: HTTPResponse{ + StatusCode: http.StatusOK, + Headers: http.Header{ + "X-Reply": {"ok"}, + }, + Body: []byte("done"), + }, + }, + }, + want: 34, + }, + { + name: "empty gRPC call", + call: Call{ + GRPC: &GRPCCall{}, + }, + want: 0, + }, + { + name: "gRPC request and response", + call: Call{ + GRPC: &GRPCCall{ + Request: GRPCRequest{ + Service: "svc", + Method: "Do", + Metadata: map[string][]string{ + "a": {"one", "two"}, + }, + Message: []byte{0, 1, 2}, + }, + Response: GRPCResponse{ + Status: "OK", + Metadata: map[string][]string{ + "b": {"x"}, + }, + Message: []byte{3, 4}, + }, + }, + }, + want: 21, + }, + { + name: "HTTP and gRPC populated", + call: Call{ + HTTP: &HTTPCall{ + Request: HTTPRequest{ + Body: []byte("abc"), + }, + }, + GRPC: &GRPCCall{ + Response: GRPCResponse{ + Message: []byte{1, 2}, + }, + }, + }, + want: 5, + }, + { + name: "metadata with empty values", + call: Call{ + GRPC: &GRPCCall{ + Request: GRPCRequest{ + Metadata: map[string][]string{ + "key": {}, + "empty": {""}, + }, + }, + }, + }, + want: 8, + }, + { + name: "truncation flags do not affect size", + call: Call{ + HTTP: &HTTPCall{ + Request: HTTPRequest{ + Body: []byte("abc"), + BodyTruncated: true, + BodyComplete: false, + }, + Response: HTTPResponse{ + Body: []byte("12345"), + BodyTruncated: true, + }, + }, + }, + want: 8, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := tt.call.Size(); got != tt.want { + t.Errorf( + "Call.Size() = %d, want %d", + got, + tt.want, + ) + } + }) + } +} + +func TestCallClone(t *testing.T) { + tests := []struct { + name string + call Call + }{ + { + name: "empty call", + call: Call{}, + }, + { + name: "identifiers and flags", + call: Call{ + TestExecutionID: "execution", + ServiceID: "service", + MockFixtureMatched: true, + }, + }, + { + name: "HTTP call", + call: Call{ + HTTP: &HTTPCall{ + Request: HTTPRequest{ + Method: "POST", + Path: "/test", + Query: map[string][]string{ + "q": {"one", "two"}, + }, + Headers: http.Header{ + "X-Request": {"value"}, + }, + Body: []byte("request"), + BodyTruncated: true, + BodyComplete: true, + }, + Response: HTTPResponse{ + StatusCode: http.StatusCreated, + Headers: http.Header{ + "X-Response": {"value"}, + }, + Body: []byte("response"), + BodyTruncated: true, + }, + }, + }, + }, + { + name: "gRPC call", + call: Call{ + GRPC: &GRPCCall{ + Request: GRPCRequest{ + Service: "service", + Method: "Method", + Metadata: map[string][]string{ + "request": {"value"}, + }, + Message: []byte("request"), + }, + Response: GRPCResponse{ + Status: "OK", + Metadata: map[string][]string{ + "response": {"value"}, + }, + Message: []byte("response"), + }, + }, + }, + }, + { + name: "both protocols", + call: Call{ + HTTP: &HTTPCall{ + Request: HTTPRequest{ + Body: []byte("http"), + }, + }, + GRPC: &GRPCCall{ + Request: GRPCRequest{ + Message: []byte("grpc"), + }, + }, + }, + }, + { + name: "nil and empty collections", + call: Call{ + HTTP: &HTTPCall{ + Request: HTTPRequest{ + Query: map[string][]string{ + "nil": nil, + "empty": {}, + }, + Headers: http.Header{ + "Nil": nil, + "Empty": {}, + }, + Body: []byte{}, + }, + Response: HTTPResponse{ + Headers: http.Header{}, + Body: []byte{}, + }, + }, + GRPC: &GRPCCall{ + Request: GRPCRequest{ + Metadata: map[string][]string{ + "empty": {}, + }, + Message: []byte{}, + }, + Response: GRPCResponse{ + Metadata: map[string][]string{}, + }, + }, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + clone := tt.call.Clone() + + if !reflect.DeepEqual(clone, tt.call) { + t.Fatalf( + "Clone() = %#v, want %#v", + clone, + tt.call, + ) + } + + if clone.Size() != tt.call.Size() { + t.Errorf( + "cloned size = %d, want %d", + clone.Size(), + tt.call.Size(), + ) + } + + if tt.call.HTTP != nil { + if clone.HTTP == tt.call.HTTP { + t.Error("HTTPCall pointer was not cloned") + } + + if len(clone.HTTP.Request.Body) > 0 { + clone.HTTP.Request.Body[0] ^= 0xff + + if reflect.DeepEqual( + clone.HTTP.Request.Body, + tt.call.HTTP.Request.Body, + ) { + t.Error("HTTP request body shares storage") + } + } + + if len(clone.HTTP.Response.Body) > 0 { + clone.HTTP.Response.Body[0] ^= 0xff + + if reflect.DeepEqual( + clone.HTTP.Response.Body, + tt.call.HTTP.Response.Body, + ) { + t.Error("HTTP response body shares storage") + } + } + + if clone.HTTP.Request.Query != nil { + clone.HTTP.Request.Query["new"] = []string{"value"} + + if _, exists := tt.call.HTTP.Request.Query["new"]; exists { + t.Error("HTTP query map shares storage") + } + + for key, values := range clone.HTTP.Request.Query { + if key == "new" || len(values) == 0 { + continue + } + + values[0] = "changed" + + if tt.call.HTTP.Request.Query[key][0] == "changed" { + t.Error("HTTP query value slice shares storage") + } + break + } + } + + if clone.HTTP.Request.Headers != nil { + clone.HTTP.Request.Headers.Set("X-Added", "new") + + if tt.call.HTTP.Request.Headers.Get("X-Added") != "" { + t.Error("HTTP request headers share storage") + } + + values := clone.HTTP.Request.Headers["X-Request"] + if len(values) > 0 { + values[0] = "changed" + + if tt.call.HTTP.Request.Headers["X-Request"][0] == "changed" { + t.Error("HTTP request header values share storage") + } + } + } + + if clone.HTTP.Response.Headers != nil { + clone.HTTP.Response.Headers.Set("X-Added", "new") + + if tt.call.HTTP.Response.Headers.Get("X-Added") != "" { + t.Error("HTTP response headers share storage") + } + } + } + + if tt.call.GRPC != nil { + if clone.GRPC == tt.call.GRPC { + t.Error("GRPCCall pointer was not cloned") + } + + if len(clone.GRPC.Request.Message) > 0 { + clone.GRPC.Request.Message[0] ^= 0xff + + if reflect.DeepEqual( + clone.GRPC.Request.Message, + tt.call.GRPC.Request.Message, + ) { + t.Error("gRPC request message shares storage") + } + } + + if len(clone.GRPC.Response.Message) > 0 { + clone.GRPC.Response.Message[0] ^= 0xff + + if reflect.DeepEqual( + clone.GRPC.Response.Message, + tt.call.GRPC.Response.Message, + ) { + t.Error("gRPC response message shares storage") + } + } + + for _, pair := range []struct { + name string + clone map[string][]string + original map[string][]string + }{ + { + name: "request", + clone: clone.GRPC.Request.Metadata, + original: tt.call.GRPC.Request.Metadata, + }, + { + name: "response", + clone: clone.GRPC.Response.Metadata, + original: tt.call.GRPC.Response.Metadata, + }, + } { + if pair.clone == nil { + continue + } + + pair.clone["new"] = []string{"value"} + + if _, exists := pair.original["new"]; exists { + t.Errorf( + "gRPC %s metadata map shares storage", + pair.name, + ) + } + + for key, values := range pair.clone { + if key == "new" || len(values) == 0 { + continue + } + + values[0] = "changed" + + if pair.original[key][0] == "changed" { + t.Errorf( + "gRPC %s metadata values share storage", + pair.name, + ) + } + break + } + } + } + }) + } +} diff --git a/execute/call/config.go b/execute/call/config.go new file mode 100644 index 0000000..4124c62 --- /dev/null +++ b/execute/call/config.go @@ -0,0 +1,6 @@ +package call + +type Config struct { + MaxCalls int `json:"max_calls" yaml:"max_calls" default:"1000" validate:"min(1),max(100000)"` + MaxRecordedBytes int64 `json:"max_recorded_bytes" yaml:"max_recorded_bytes" default:"67108864" validate:"min(1),max(1073741824)"` +} diff --git a/execute/call/http.go b/execute/call/http.go index e31586e..e6ac745 100644 --- a/execute/call/http.go +++ b/execute/call/http.go @@ -10,15 +10,18 @@ type HTTPCall struct { } type HTTPRequest struct { - Method string - Path string - Query map[string][]string - Headers http.Header - Body []byte + Method string + Path string + Query map[string][]string + Headers http.Header + Body []byte + BodyTruncated bool + BodyComplete bool } type HTTPResponse struct { - StatusCode int - Headers http.Header - Body []byte + StatusCode int + Headers http.Header + Body []byte + BodyTruncated bool } diff --git a/execute/call/store.go b/execute/call/store.go index 7a5e963..0ba28c8 100644 --- a/execute/call/store.go +++ b/execute/call/store.go @@ -1,20 +1,62 @@ package call -import "sync" +import ( + "sync" + + "github.com/e2engine/core/pkg/errors" +) type Store struct { mu sync.RWMutex calls []Call + + maxCalls int + maxBytes int64 + recordedBytes int64 + + limitExceeded bool } var _ Recorder = (*Store)(nil) var _ Reader = (*Store)(nil) -func (c *Store) Record(call Call) { +func (c *Store) Record(record Call) error { c.mu.Lock() defer c.mu.Unlock() - c.calls = append(c.calls, call) + if c.limitExceeded { + return errors.ErrCallStoreLimitExceeded + } + + if len(c.calls) >= c.maxCalls { + c.limitExceeded = true + return errors.ErrCallStoreLimitExceeded + } + + size := record.Size() + + if size > c.maxBytes-c.recordedBytes { + c.limitExceeded = true + return errors.ErrCallStoreLimitExceeded + } + + snapshot := record.Clone() + + c.calls = append(c.calls, snapshot) + c.recordedBytes += size + + return nil +} + +func (c *Store) Err() error { + c.mu.RLock() + defer c.mu.RUnlock() + + if c.limitExceeded { + return errors.ErrCallStoreLimitExceeded + } + + return nil } type Filter struct { @@ -38,7 +80,7 @@ func (c *Store) Get( continue } - calls = append(calls, c.calls[i]) + calls = append(calls, c.calls[i].Clone()) } return calls @@ -48,12 +90,19 @@ type StoreFactory interface { New() *Store } -type factory struct{} +type factory struct { + cfg *Config +} func (f *factory) New() *Store { - return &Store{} + return &Store{ + maxCalls: f.cfg.MaxCalls, + maxBytes: f.cfg.MaxRecordedBytes, + } } -func NewStoreFactory() StoreFactory { - return &factory{} +func NewStoreFactory(cfg *Config) StoreFactory { + return &factory{ + cfg: cfg, + } } diff --git a/execute/call/store_test.go b/execute/call/store_test.go index bc07de6..5a9562b 100644 --- a/execute/call/store_test.go +++ b/execute/call/store_test.go @@ -1,9 +1,20 @@ package call -import "testing" +import ( + nativeerrors "errors" + "net/http" + "reflect" + "sync" + "testing" + + "github.com/e2engine/core/pkg/errors" +) func TestStoreGet(t *testing.T) { - store := &Store{} + store := NewStoreFactory(&Config{ + MaxCalls: 3, + MaxRecordedBytes: 1 << 20, + }).New() call1 := Call{ TestExecutionID: "execution-1", @@ -20,9 +31,11 @@ func TestStoreGet(t *testing.T) { ServiceID: "service-2", } - store.Record(call1) - store.Record(call2) - store.Record(call3) + for _, recorded := range []Call{call1, call2, call3} { + if err := store.Record(recorded); err != nil { + t.Fatalf("Record() error = %v", err) + } + } tests := []struct { name string @@ -101,10 +114,13 @@ func TestStoreGet(t *testing.T) { } func TestStoreFactoryNew(t *testing.T) { - factory := NewStoreFactory() + f := NewStoreFactory(&Config{ + MaxCalls: 1, + MaxRecordedBytes: 1 << 20, + }) - store1 := factory.New() - store2 := factory.New() + store1 := f.New() + store2 := f.New() if store1 == nil { t.Fatal("expected first store") @@ -118,9 +134,11 @@ func TestStoreFactoryNew(t *testing.T) { t.Fatal("expected independent stores") } - store1.Record(Call{ + if err := store1.Record(Call{ TestExecutionID: "execution-1", - }) + }); err != nil { + t.Fatalf("Record() error = %v", err) + } if len(store1.Get(Filter{})) != 1 { t.Fatal("expected call in first store") @@ -130,3 +148,787 @@ func TestStoreFactoryNew(t *testing.T) { t.Fatal("expected second store to be empty") } } + +func TestStoreRecordLimit(t *testing.T) { + store := NewStoreFactory(&Config{ + MaxCalls: 2, + MaxRecordedBytes: 1 << 20, + }).New() + + for i := range 2 { + if err := store.Record(Call{ + TestExecutionID: "execution-1", + }); err != nil { + t.Fatalf( + "Record(%d) error = %v", + i, + err, + ) + } + } + + // Reaching the limit is valid. + if err := store.Err(); err != nil { + t.Fatalf( + "Err() = %v, want nil at limit", + err, + ) + } + + // The next record exceeds the limit. + err := store.Record(Call{ + TestExecutionID: "execution-2", + }) + + if !nativeerrors.Is( + err, + errors.ErrCallStoreLimitExceeded, + ) { + t.Fatalf( + "Record() error = %v, want ErrCallStoreLimitExceeded", + err, + ) + } + + // The store retains the failure. + if err := store.Err(); !nativeerrors.Is( + err, + errors.ErrCallStoreLimitExceeded, + ) { + t.Fatalf( + "Err() = %v, want ErrCallStoreLimitExceeded", + err, + ) + } + + // Only the first two calls were recorded. + if got := store.Get(Filter{}); len(got) != 2 { + t.Fatalf( + "Get() returned %d calls, want 2", + len(got), + ) + } + + // Subsequent recording attempts must also fail. + if err := store.Record(Call{}); !nativeerrors.Is( + err, + errors.ErrCallStoreLimitExceeded, + ) { + t.Fatalf( + "subsequent Record() error = %v, want ErrCallStoreLimitExceeded", + err, + ) + } + + if got := store.Get(Filter{}); len(got) != 2 { + t.Fatalf( + "Get() returned %d calls after subsequent failure, want 2", + len(got), + ) + } +} + +func TestStoreFactoryIndependentLimits(t *testing.T) { + f := NewStoreFactory(&Config{ + MaxCalls: 1, + MaxRecordedBytes: 1 << 20, + }) + + first := f.New() + second := f.New() + + if err := first.Record(Call{}); err != nil { + t.Fatalf( + "first.Record() error = %v", + err, + ) + } + + // Overflow the first store. + if err := first.Record(Call{}); !nativeerrors.Is( + err, + errors.ErrCallStoreLimitExceeded, + ) { + t.Fatalf( + "first.Record() error = %v, want ErrCallStoreLimitExceeded", + err, + ) + } + + // The second store must remain unaffected. + if err := second.Err(); err != nil { + t.Fatalf( + "second.Err() = %v, want nil", + err, + ) + } + + if err := second.Record(Call{}); err != nil { + t.Fatalf( + "second.Record() error = %v", + err, + ) + } +} + +func TestStoreConcurrentRecording(t *testing.T) { + const ( + maxCalls = 100 + workers = 20 + perWorker = 20 + ) + + store := NewStoreFactory(&Config{ + MaxCalls: maxCalls, + MaxRecordedBytes: 1 << 20, + }).New() + + var wg sync.WaitGroup + var mu sync.Mutex + + var succeeded int + var rejected int + var unexpected []error + + for range workers { + wg.Add(1) + + go func() { + defer wg.Done() + + for range perWorker { + err := store.Record(Call{ + TestExecutionID: "execution-1", + }) + + // Exercise concurrent reads of the overflow state. + _ = store.Err() + + mu.Lock() + + switch { + case err == nil: + succeeded++ + + case nativeerrors.Is( + err, + errors.ErrCallStoreLimitExceeded, + ): + rejected++ + + default: + unexpected = append(unexpected, err) + } + + mu.Unlock() + } + }() + } + + wg.Wait() + + if len(unexpected) != 0 { + t.Fatalf( + "unexpected Record errors: %v", + unexpected, + ) + } + + if succeeded != maxCalls { + t.Errorf( + "successful records = %d, want %d", + succeeded, + maxCalls, + ) + } + + expectedRejected := workers*perWorker - maxCalls + + if rejected != expectedRejected { + t.Errorf( + "rejected records = %d, want %d", + rejected, + expectedRejected, + ) + } + + if got := len(store.Get(Filter{})); got != maxCalls { + t.Errorf( + "stored calls = %d, want %d", + got, + maxCalls, + ) + } + + if err := store.Err(); !nativeerrors.Is( + err, + errors.ErrCallStoreLimitExceeded, + ) { + t.Errorf( + "Err() = %v, want ErrCallStoreLimitExceeded", + err, + ) + } +} + +func TestStoreRecordedBytesLimit(t *testing.T) { + tests := []struct { + name string + maxBytes int64 + calls []Call + wantAccepted int + wantExceeded bool + }{ + { + name: "exact boundary", + maxBytes: 5, + calls: []Call{ + { + HTTP: &HTTPCall{ + Request: HTTPRequest{ + Body: []byte("ab"), + }, + }, + }, + { + HTTP: &HTTPCall{ + Response: HTTPResponse{ + Body: []byte("cde"), + }, + }, + }, + }, + wantAccepted: 2, + }, + { + name: "cumulative overflow", + maxBytes: 4, + calls: []Call{ + { + HTTP: &HTTPCall{ + Request: HTTPRequest{ + Body: []byte("ab"), + }, + }, + }, + { + HTTP: &HTTPCall{ + Response: HTTPResponse{ + Body: []byte("cde"), + }, + }, + }, + }, + wantAccepted: 1, + wantExceeded: true, + }, + { + name: "single call too large", + maxBytes: 2, + calls: []Call{ + { + GRPC: &GRPCCall{ + Request: GRPCRequest{ + Message: []byte{1, 2, 3}, + }, + }, + }, + }, + wantAccepted: 0, + wantExceeded: true, + }, + { + name: "zero-sized record", + maxBytes: 1, + calls: []Call{ + {}, + }, + wantAccepted: 1, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + store := NewStoreFactory(&Config{ + MaxCalls: 10, + MaxRecordedBytes: tt.maxBytes, + }).New() + + var accepted int + + for _, record := range tt.calls { + err := store.Record(record) + + switch { + case err == nil: + accepted++ + + case nativeerrors.Is( + err, + errors.ErrCallStoreLimitExceeded, + ): + // Expected when the byte limit is exceeded. + + default: + t.Fatalf( + "Record() unexpected error = %v", + err, + ) + } + } + + if accepted != tt.wantAccepted { + t.Errorf( + "accepted calls = %d, want %d", + accepted, + tt.wantAccepted, + ) + } + + recorded := store.Get(Filter{}) + + if len(recorded) != tt.wantAccepted { + t.Errorf( + "retained calls = %d, want %d", + len(recorded), + tt.wantAccepted, + ) + } + + var expectedBytes int64 + + for _, retained := range recorded { + expectedBytes += retained.Size() + } + + if store.recordedBytes != expectedBytes { + t.Errorf( + "recordedBytes = %d, want %d", + store.recordedBytes, + expectedBytes, + ) + } + + if tt.wantExceeded { + if err := store.Err(); !nativeerrors.Is( + err, + errors.ErrCallStoreLimitExceeded, + ) { + t.Errorf( + "Err() = %v, want ErrCallStoreLimitExceeded", + err, + ) + } + + // Once exceeded, even a smaller call is rejected. + if err := store.Record(Call{}); !nativeerrors.Is( + err, + errors.ErrCallStoreLimitExceeded, + ) { + t.Errorf( + "subsequent Record() error = %v, want ErrCallStoreLimitExceeded", + err, + ) + } + + if got := len(store.Get(Filter{})); got != tt.wantAccepted { + t.Errorf( + "retained calls after overflow = %d, want %d", + got, + tt.wantAccepted, + ) + } + } else { + if err := store.Err(); err != nil { + t.Errorf( + "Err() = %v, want nil", + err, + ) + } + } + }) + } +} + +func TestStoreConcurrentRecordedBytesLimit(t *testing.T) { + const ( + maxCalls = 1000 + maxBytes = 100 + workers = 20 + perWorker = 20 + callSize = 3 + ) + + store := NewStoreFactory(&Config{ + MaxCalls: maxCalls, + MaxRecordedBytes: maxBytes, + }).New() + + var wg sync.WaitGroup + var mu sync.Mutex + + var succeeded int + var rejected int + var unexpected []error + + for range workers { + wg.Add(1) + + go func() { + defer wg.Done() + + for range perWorker { + err := store.Record(Call{ + HTTP: &HTTPCall{ + Request: HTTPRequest{ + Body: []byte("abc"), + }, + }, + }) + + _ = store.Err() + + mu.Lock() + + switch { + case err == nil: + succeeded++ + + case nativeerrors.Is( + err, + errors.ErrCallStoreLimitExceeded, + ): + rejected++ + + default: + unexpected = append(unexpected, err) + } + + mu.Unlock() + } + }() + } + + wg.Wait() + + expectedAccepted := maxBytes / callSize + + if len(unexpected) != 0 { + t.Fatalf("unexpected Record() errors: %v", unexpected) + } + + if succeeded != expectedAccepted { + t.Errorf( + "successful records = %d, want %d", + succeeded, + expectedAccepted, + ) + } + + if rejected != workers*perWorker-expectedAccepted { + t.Errorf( + "rejected records = %d, want %d", + rejected, + workers*perWorker-expectedAccepted, + ) + } + + if got := len(store.Get(Filter{})); got != expectedAccepted { + t.Errorf( + "stored calls = %d, want %d", + got, + expectedAccepted, + ) + } + + if want := int64(expectedAccepted * callSize); store.recordedBytes != want { + t.Errorf( + "recordedBytes = %d, want %d", + store.recordedBytes, + want, + ) + } + + if err := store.Err(); !nativeerrors.Is( + err, + errors.ErrCallStoreLimitExceeded, + ) { + t.Errorf( + "Err() = %v, want ErrCallStoreLimitExceeded", + err, + ) + } +} + +func TestStoreCombinedLimits(t *testing.T) { + tests := []struct { + name string + maxCalls int + maxBytes int64 + recordSizes []int + wantAccepted int + wantBytes int64 + }{ + { + name: "call count limit reached first", + maxCalls: 2, + maxBytes: 100, + recordSizes: []int{3, 3, 3}, + wantAccepted: 2, + wantBytes: 6, + }, + { + name: "byte limit reached first", + maxCalls: 100, + maxBytes: 5, + recordSizes: []int{3, 3}, + wantAccepted: 1, + wantBytes: 3, + }, + { + name: "both limits reached exactly", + maxCalls: 2, + maxBytes: 6, + recordSizes: []int{3, 3, 3}, + wantAccepted: 2, + wantBytes: 6, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + store := NewStoreFactory(&Config{ + MaxCalls: tt.maxCalls, + MaxRecordedBytes: tt.maxBytes, + }).New() + + var accepted int + + for _, size := range tt.recordSizes { + err := store.Record(Call{ + HTTP: &HTTPCall{ + Request: HTTPRequest{ + Body: make([]byte, size), + }, + }, + }) + + if err == nil { + accepted++ + continue + } + + if !nativeerrors.Is( + err, + errors.ErrCallStoreLimitExceeded, + ) { + t.Fatalf("Record() unexpected error = %v", err) + } + } + + if accepted != tt.wantAccepted { + t.Errorf( + "accepted = %d, want %d", + accepted, + tt.wantAccepted, + ) + } + + if store.recordedBytes != tt.wantBytes { + t.Errorf( + "recordedBytes = %d, want %d", + store.recordedBytes, + tt.wantBytes, + ) + } + + if got := len(store.Get(Filter{})); got != tt.wantAccepted { + t.Errorf( + "recorded calls = %d, want %d", + got, + tt.wantAccepted, + ) + } + + if err := store.Err(); !nativeerrors.Is( + err, + errors.ErrCallStoreLimitExceeded, + ) { + t.Errorf( + "Err() = %v, want ErrCallStoreLimitExceeded", + err, + ) + } + }) + } +} + +func TestStoreRecordOwnsSnapshot(t *testing.T) { + store := NewStoreFactory(&Config{ + MaxCalls: 10, + MaxRecordedBytes: 1 << 20, + }).New() + + original := ownershipTestCall() + want := original.Clone() + wantBytes := want.Size() + + if err := store.Record(original); err != nil { + t.Fatalf("Record() error = %v", err) + } + + // Modify the original after recording. + mutateOwnershipTestCall(&original) + + got := store.Get(Filter{}) + if len(got) != 1 { + t.Fatalf("Get() returned %d calls, want 1", len(got)) + } + + if !reflect.DeepEqual(got[0], want) { + t.Errorf( + "recorded call changed after input mutation: got %#v, want %#v", + got[0], + want, + ) + } + + if store.recordedBytes != wantBytes { + t.Errorf( + "recordedBytes = %d, want %d", + store.recordedBytes, + wantBytes, + ) + } + + if err := store.Err(); err != nil { + t.Errorf("Err() = %v, want nil", err) + } +} + +func TestStoreGetReturnsIndependentSnapshots(t *testing.T) { + store := NewStoreFactory(&Config{ + MaxCalls: 10, + MaxRecordedBytes: 1 << 20, + }).New() + + original := ownershipTestCall() + want := original.Clone() + wantBytes := want.Size() + + if err := store.Record(original); err != nil { + t.Fatalf("Record() error = %v", err) + } + + first := store.Get(Filter{}) + if len(first) != 1 { + t.Fatalf("first Get() returned %d calls, want 1", len(first)) + } + + // Modify the returned call. + mutateOwnershipTestCall(&first[0]) + + // A subsequent read must return the original data. + second := store.Get(Filter{}) + if len(second) != 1 { + t.Fatalf("second Get() returned %d calls, want 1", len(second)) + } + + if !reflect.DeepEqual(second[0], want) { + t.Errorf( + "stored call changed after Get() result mutation: got %#v, want %#v", + second[0], + want, + ) + } + + if store.recordedBytes != wantBytes { + t.Errorf( + "recordedBytes = %d, want %d", + store.recordedBytes, + wantBytes, + ) + } + + if err := store.Err(); err != nil { + t.Errorf("Err() = %v, want nil", err) + } +} + +func ownershipTestCall() Call { + return Call{ + TestExecutionID: "execution-1", + ServiceID: "service-1", + MockFixtureMatched: true, + + HTTP: &HTTPCall{ + Request: HTTPRequest{ + Method: "POST", + Path: "/test", + Query: map[string][]string{ + "q": {"original"}, + }, + Headers: http.Header{ + "X-Request": {"original"}, + }, + Body: []byte("request"), + BodyComplete: true, + }, + Response: HTTPResponse{ + StatusCode: http.StatusOK, + Headers: http.Header{ + "X-Response": {"original"}, + }, + Body: []byte("response"), + }, + }, + + GRPC: &GRPCCall{ + Request: GRPCRequest{ + Service: "service", + Method: "Method", + Metadata: map[string][]string{ + "request": {"original"}, + }, + Message: []byte("request"), + }, + Response: GRPCResponse{ + Status: "OK", + Metadata: map[string][]string{ + "response": {"original"}, + }, + Message: []byte("response"), + }, + }, + } +} + +func mutateOwnershipTestCall(c *Call) { + c.TestExecutionID = "modified-execution" + c.ServiceID = "modified-service" + c.MockFixtureMatched = false + + // HTTP request. + c.HTTP.Request.Method = "GET" + c.HTTP.Request.Query["q"][0] = "modified" + c.HTTP.Request.Query["extra"] = []string{"added"} + c.HTTP.Request.Headers["X-Request"][0] = "modified" + c.HTTP.Request.Headers.Set("X-Extra", "added") + c.HTTP.Request.Body[0] = 'X' + + // HTTP response. + c.HTTP.Response.StatusCode = http.StatusCreated + c.HTTP.Response.Headers["X-Response"][0] = "modified" + c.HTTP.Response.Body[0] = 'X' + + // gRPC request. + c.GRPC.Request.Service = "modified-service" + c.GRPC.Request.Metadata["request"][0] = "modified" + c.GRPC.Request.Metadata["extra"] = []string{"added"} + c.GRPC.Request.Message[0] = 'X' + + // gRPC response. + c.GRPC.Response.Status = "Internal" + c.GRPC.Response.Metadata["response"][0] = "modified" + c.GRPC.Response.Message[0] = 'X' +} diff --git a/execute/persist/updater.go b/execute/persist/updater.go index 3d382e1..26b9eff 100644 --- a/execute/persist/updater.go +++ b/execute/persist/updater.go @@ -3,6 +3,7 @@ package persist import ( "context" "encoding/json" + "errors" "time" "github.com/ygrebnov/errorc" @@ -16,7 +17,10 @@ import ( var ErrInvalidExecutionStatus = errorc.New("invalid execution status") type TestExecutionRepository interface { - GetByTestSuiteExecutionID(ctx context.Context, id string) ([]corerepository.TestExecution, error) + GetTestSuiteExecutionStates( + ctx context.Context, + testSuiteExecutionID string, + ) ([]corerepository.TestSuiteExecutionState, bool, error) SetRunning(ctx context.Context, params *SetRunningParams) error SetCompleted(ctx context.Context, params *SetCompletedParams) error } @@ -24,10 +28,12 @@ type TestExecutionRepository interface { type TestSuiteExecutionRepository interface { SetRunning(ctx context.Context, params *SetRunningParams) error SetCompleted(ctx context.Context, params *SetCompletedParams) error + GetStatus(ctx context.Context, id string) (corerepository.ExecutionStatus, error) } type SetRunningParams = corerepository.SetRunningParams type SetCompletedParams = corerepository.SetCompletedParams +type ExecutionStatus = corerepository.ExecutionStatus type Updater struct { testExecution TestExecutionRepository @@ -91,7 +97,7 @@ func (u *Updater) SetTestCompleted( ctx, &SetCompletedParams{ ID: result.ExecutionID, - Status: string(result.Status), + Status: ExecutionStatus(result.Status), FinishedAt: result.FinishedAt, Summary: summary, }, @@ -128,7 +134,7 @@ func (u *Updater) SetTestSuiteCompleted( ctx, &SetCompletedParams{ ID: result.ExecutionID, - Status: string(result.Status), + Status: ExecutionStatus(result.Status), FinishedAt: result.FinishedAt, Summary: summary, }, @@ -141,7 +147,7 @@ func (u *Updater) tryCompleteTestSuite( ctx context.Context, testSuiteExecutionID string, ) (bool, error) { - testExecutions, err := u.testExecution.GetByTestSuiteExecutionID( + states, alreadyCompleted, err := u.testExecution.GetTestSuiteExecutionStates( ctx, testSuiteExecutionID, ) @@ -149,46 +155,58 @@ func (u *Updater) tryCompleteTestSuite( return false, err } - summary := &model.TestSuiteExecutionSummary{ - Total: len(testExecutions), + if alreadyCompleted { + return false, nil } + if len(states) == 0 { + return false, nil + } + + summary := &model.TestSuiteExecutionSummary{} + status := model.ExecutionStatusPassed - finishedAt := time.Time{} + var finishedAt time.Time - for i := range testExecutions { - execution := testExecutions[i] + for _, state := range states { + summary.Total += state.Count - switch model.ExecutionStatus(execution.Status) { + switch model.ExecutionStatus(state.Status) { case model.ExecutionStatusPassed: - summary.Passed++ + summary.Passed += state.Count case model.ExecutionStatusFailed: - summary.Failed++ + summary.Failed += state.Count + if status != model.ExecutionStatusError { status = model.ExecutionStatusFailed } case model.ExecutionStatusError: - summary.Errors++ + summary.Errors += state.Count status = model.ExecutionStatusError - case model.ExecutionStatusRunning, model.ExecutionStatusScheduled: + case model.ExecutionStatusRunning, + model.ExecutionStatusScheduled: return false, nil default: return false, errorc.With( ErrInvalidExecutionStatus, - errorc.String(keys.ExecutionStatus, execution.Status), + errorc.String(keys.ExecutionStatus, string(state.Status)), ) } - if execution.FinishedAt.After(finishedAt) { - finishedAt = execution.FinishedAt + if state.LastTestFinishedAt.IsZero() { + return false, ErrInvalidExecutionStatus + } + + if state.LastTestFinishedAt.After(finishedAt) { + finishedAt = state.LastTestFinishedAt } } - return u.SetTestSuiteCompleted( + completed, err := u.SetTestSuiteCompleted( ctx, execute.TestSuiteExecutionResult{ ExecutionID: testSuiteExecutionID, @@ -197,4 +215,40 @@ func (u *Updater) tryCompleteTestSuite( Summary: summary, }, ) + + if !errors.Is( + err, + corerepository.ErrInvalidExecutionStateTransition, + ) { + return completed, err + } + + // Another goroutine may have completed the suite. + current, statusErr := u.testSuiteExecution.GetStatus( + ctx, + testSuiteExecutionID, + ) + if statusErr != nil { + return false, statusErr + } + + switch model.ExecutionStatus(current) { + case model.ExecutionStatusPassed, + model.ExecutionStatusFailed, + model.ExecutionStatusError: + return false, nil + + default: + return false, err + } +} + +func (u *Updater) TryCompleteTestSuite( + ctx context.Context, + testSuiteExecutionID string, +) (bool, error) { + return u.tryCompleteTestSuite( + ctx, + testSuiteExecutionID, + ) } diff --git a/execute/persist/updater_test.go b/execute/persist/updater_test.go index 48ff6ea..5ca2f4b 100644 --- a/execute/persist/updater_test.go +++ b/execute/persist/updater_test.go @@ -1,145 +1,126 @@ package persist import ( - "context" "encoding/json" "errors" "testing" "time" + "go.uber.org/mock/gomock" + "github.com/e2engine/core/execute" + "github.com/e2engine/core/mock" "github.com/e2engine/core/model" "github.com/e2engine/core/repository" ) -func TestUpdaterSetTestRunning(t *testing.T) { - startedAt := time.Date( - 2026, 9, 18, 10, 0, 0, 0, time.UTC, - ) +const ( + testExecutionID = "test-execution-1" + suiteExecutionID = "suite-execution-1" +) - testRepository := &testExecutionRepository{} - updater := NewUpdater( - testRepository, - &testSuiteExecutionRepository{}, - ) +func TestUpdaterSetTestRunning(t *testing.T) { + startedAt := time.Date(2026, 9, 18, 10, 0, 0, 0, time.UTC) + + ctrl := gomock.NewController(t) + tests := mock.NewMockTestExecutionRepository(ctrl) + suites := mock.NewMockTestSuiteExecutionRepository(ctrl) + + tests.EXPECT(). + SetRunning( + gomock.Any(), + &repository.SetRunningParams{ + ID: testExecutionID, + StartedAt: startedAt, + }, + ). + Return(nil) - err := updater.SetTestRunning( - context.Background(), - "test-execution-1", + err := NewUpdater(tests, suites).SetTestRunning( + t.Context(), + testExecutionID, startedAt, ) if err != nil { - t.Fatalf("SetTestRunning() error = %v", err) - } - - if testRepository.running == nil { - t.Fatal("expected SetRunning() to be called") - } - - if testRepository.running.ID != "test-execution-1" { - t.Errorf( - "expected ID test-execution-1, got %s", - testRepository.running.ID, - ) - } - - if !testRepository.running.StartedAt.Equal(startedAt) { - t.Errorf( - "expected StartedAt %v, got %v", - startedAt, - testRepository.running.StartedAt, - ) + t.Fatalf("SetTestRunning: %v", err) } } func TestUpdaterSetTestRunningError(t *testing.T) { - expectedErr := errors.New("set running") + expected := errors.New("set running") - updater := NewUpdater( - &testExecutionRepository{ - setRunningErr: expectedErr, - }, - &testSuiteExecutionRepository{}, - ) + ctrl := gomock.NewController(t) + tests := mock.NewMockTestExecutionRepository(ctrl) - err := updater.SetTestRunning( - context.Background(), - "test-execution-1", + tests.EXPECT(). + SetRunning(gomock.Any(), gomock.Any()). + Return(expected) + + err := NewUpdater( + tests, + mock.NewMockTestSuiteExecutionRepository(ctrl), + ).SetTestRunning( + t.Context(), + testExecutionID, time.Now(), ) - if !errors.Is(err, expectedErr) { - t.Fatalf( - "expected error %v, got %v", - expectedErr, - err, - ) + if !errors.Is(err, expected) { + t.Fatalf("got %v, want %v", err, expected) } } func TestUpdaterSetTestSuiteRunning(t *testing.T) { - startedAt := time.Date( - 2026, 9, 18, 10, 0, 0, 0, time.UTC, - ) + startedAt := time.Date(2026, 9, 18, 10, 0, 0, 0, time.UTC) - suiteRepository := &testSuiteExecutionRepository{} - updater := NewUpdater( - &testExecutionRepository{}, - suiteRepository, - ) + ctrl := gomock.NewController(t) + suites := mock.NewMockTestSuiteExecutionRepository(ctrl) - err := updater.SetTestSuiteRunning( - context.Background(), - "test-suite-execution-1", + suites.EXPECT(). + SetRunning( + gomock.Any(), + &repository.SetRunningParams{ + ID: suiteExecutionID, + StartedAt: startedAt, + }, + ). + Return(nil) + + err := NewUpdater( + mock.NewMockTestExecutionRepository(ctrl), + suites, + ).SetTestSuiteRunning( + t.Context(), + suiteExecutionID, startedAt, ) - if err != nil { - t.Fatalf("SetTestSuiteRunning() error = %v", err) - } - - if suiteRepository.running == nil { - t.Fatal("expected SetRunning() to be called") - } - if suiteRepository.running.ID != - "test-suite-execution-1" { - t.Errorf( - "expected ID test-suite-execution-1, got %s", - suiteRepository.running.ID, - ) - } - - if !suiteRepository.running.StartedAt.Equal(startedAt) { - t.Errorf( - "expected StartedAt %v, got %v", - startedAt, - suiteRepository.running.StartedAt, - ) + if err != nil { + t.Fatalf("SetTestSuiteRunning: %v", err) } } func TestUpdaterSetTestSuiteRunningError(t *testing.T) { - expectedErr := errors.New("set suite running") + expected := errors.New("set suite running") - updater := NewUpdater( - &testExecutionRepository{}, - &testSuiteExecutionRepository{ - setRunningErr: expectedErr, - }, - ) + ctrl := gomock.NewController(t) + suites := mock.NewMockTestSuiteExecutionRepository(ctrl) + + suites.EXPECT(). + SetRunning(gomock.Any(), gomock.Any()). + Return(expected) - err := updater.SetTestSuiteRunning( - context.Background(), - "test-suite-execution-1", + err := NewUpdater( + mock.NewMockTestExecutionRepository(ctrl), + suites, + ).SetTestSuiteRunning( + t.Context(), + suiteExecutionID, time.Now(), ) - if !errors.Is(err, expectedErr) { - t.Fatalf( - "expected error %v, got %v", - expectedErr, - err, - ) + if !errors.Is(err, expected) { + t.Fatalf("got %v, want %v", err, expected) } } @@ -148,482 +129,476 @@ func TestUpdaterSetTestCompletedStandalone(t *testing.T) { 2026, 9, 18, 10, 1, 0, 0, time.UTC, ) - summary := &model.TestExecutionSummary{ - Error: "test error", - } - - testRepository := &testExecutionRepository{} - updater := NewUpdater( - testRepository, - &testSuiteExecutionRepository{}, - ) + ctrl := gomock.NewController(t) + tests := mock.NewMockTestExecutionRepository(ctrl) + + tests.EXPECT(). + SetCompleted(gomock.Any(), gomock.Any()). + DoAndReturn( + func( + _ any, + params *repository.SetCompletedParams, + ) error { + if params.ID != testExecutionID { + t.Errorf("unexpected execution ID: %s", params.ID) + } + + if params.Status != repository.ExecutionStatusError { + t.Errorf("unexpected status: %s", params.Status) + } + + if !params.FinishedAt.Equal(finishedAt) { + t.Errorf( + "FinishedAt = %v, want %v", + params.FinishedAt, + finishedAt, + ) + } + + var summary model.TestExecutionSummary + if err := json.Unmarshal( + params.Summary, + &summary, + ); err != nil { + t.Fatalf("unmarshal summary: %v", err) + } + + if summary.Error != "test error" { + t.Errorf( + "summary error = %q, want %q", + summary.Error, + "test error", + ) + } + + return nil + }, + ) - completed, err := updater.SetTestCompleted( - context.Background(), + completed, err := NewUpdater( + tests, + mock.NewMockTestSuiteExecutionRepository(ctrl), + ).SetTestCompleted( + t.Context(), execute.TestExecutionResult{ - ExecutionID: "test-execution-1", + ExecutionID: testExecutionID, Status: model.ExecutionStatusError, FinishedAt: finishedAt, - Summary: summary, + Summary: &model.TestExecutionSummary{ + Error: "test error", + }, }, ) + if err != nil { - t.Fatalf("SetTestCompleted() error = %v", err) + t.Fatalf("SetTestCompleted: %v", err) } - if !completed { t.Fatal("expected standalone test to be completed") } - - if testRepository.completed == nil { - t.Fatal("expected SetCompleted() to be called") - } - - if testRepository.completed.ID != "test-execution-1" { - t.Errorf( - "expected ID test-execution-1, got %s", - testRepository.completed.ID, - ) - } - - if testRepository.completed.Status != - string(model.ExecutionStatusError) { - t.Errorf( - "expected status %s, got %s", - model.ExecutionStatusError, - testRepository.completed.Status, - ) - } - - if !testRepository.completed.FinishedAt.Equal( - finishedAt, - ) { - t.Errorf( - "expected FinishedAt %v, got %v", - finishedAt, - testRepository.completed.FinishedAt, - ) - } - - var actual model.TestExecutionSummary - if err := json.Unmarshal( - testRepository.completed.Summary, - &actual, - ); err != nil { - t.Fatalf("cannot unmarshal summary: %v", err) - } - - if actual.Error != summary.Error { - t.Errorf( - "expected summary error %q, got %q", - summary.Error, - actual.Error, - ) - } } func TestUpdaterSetTestCompletedNilSummary(t *testing.T) { - testRepository := &testExecutionRepository{} - updater := NewUpdater( - testRepository, - &testSuiteExecutionRepository{}, - ) + ctrl := gomock.NewController(t) + tests := mock.NewMockTestExecutionRepository(ctrl) + + tests.EXPECT(). + SetCompleted(gomock.Any(), gomock.Any()). + DoAndReturn( + func( + _ any, + params *repository.SetCompletedParams, + ) error { + if params.Summary != nil { + t.Errorf( + "expected nil summary, got %s", + params.Summary, + ) + } + return nil + }, + ) - completed, err := updater.SetTestCompleted( - context.Background(), + completed, err := NewUpdater( + tests, + mock.NewMockTestSuiteExecutionRepository(ctrl), + ).SetTestCompleted( + t.Context(), execute.TestExecutionResult{ - ExecutionID: "test-execution-1", + ExecutionID: testExecutionID, Status: model.ExecutionStatusPassed, FinishedAt: time.Now(), }, ) - if err != nil { - t.Fatalf("SetTestCompleted() error = %v", err) - } - if !completed { - t.Fatal("expected standalone test to be completed") - } - - if testRepository.completed.Summary != nil { - t.Errorf( - "expected nil summary, got %s", - testRepository.completed.Summary, - ) + if err != nil || !completed { + t.Fatalf("completed=%v, err=%v", completed, err) } } func TestUpdaterSetTestCompletedError(t *testing.T) { - expectedErr := errors.New("set completed") + expected := errors.New("set completed") - updater := NewUpdater( - &testExecutionRepository{ - setCompletedErr: expectedErr, - }, - &testSuiteExecutionRepository{}, - ) + ctrl := gomock.NewController(t) + tests := mock.NewMockTestExecutionRepository(ctrl) + + tests.EXPECT(). + SetCompleted(gomock.Any(), gomock.Any()). + Return(expected) - completed, err := updater.SetTestCompleted( - context.Background(), + completed, err := NewUpdater( + tests, + mock.NewMockTestSuiteExecutionRepository(ctrl), + ).SetTestCompleted( + t.Context(), execute.TestExecutionResult{ - ExecutionID: "test-execution-1", + ExecutionID: testExecutionID, Status: model.ExecutionStatusPassed, }, ) - if !errors.Is(err, expectedErr) { - t.Fatalf( - "expected error %v, got %v", - expectedErr, - err, - ) - } - if completed { t.Fatal("expected completed to be false") } -} - -func TestUpdaterSetTestCompletedSuiteRunning(t *testing.T) { - testRepository := &testExecutionRepository{ - executions: []repository.TestExecution{ - { - ID: "test-execution-1", - Status: string(model.ExecutionStatusPassed), - FinishedAt: time.Now(), - }, - { - ID: "test-execution-2", - Status: string(model.ExecutionStatusRunning), - }, - }, - } - - suiteRepository := &testSuiteExecutionRepository{} - - updater := NewUpdater( - testRepository, - suiteRepository, - ) - - completed, err := updater.SetTestCompleted( - context.Background(), - execute.TestExecutionResult{ - ExecutionID: "test-execution-1", - TestSuiteExecutionID: "suite-execution-1", - Status: model.ExecutionStatusPassed, - FinishedAt: time.Now(), - }, - ) - if err != nil { - t.Fatalf("SetTestCompleted() error = %v", err) - } - - if completed { - t.Fatal( - "expected suite to remain incomplete", - ) - } - - if suiteRepository.completed != nil { - t.Fatal( - "expected suite SetCompleted() not to be called", - ) + if !errors.Is(err, expected) { + t.Fatalf("got %v, want %v", err, expected) } } -func TestUpdaterSetTestCompletedSuiteScheduled(t *testing.T) { - testRepository := &testExecutionRepository{ - executions: []repository.TestExecution{ - { - Status: string( - model.ExecutionStatusPassed, - ), - FinishedAt: time.Now(), - }, - { - Status: string( - model.ExecutionStatusScheduled, - ), - }, - }, - } - - updater := NewUpdater( - testRepository, - &testSuiteExecutionRepository{}, - ) - - completed, err := updater.SetTestCompleted( - context.Background(), - execute.TestExecutionResult{ - ExecutionID: "test-execution-1", - TestSuiteExecutionID: "suite-execution-1", - Status: model.ExecutionStatusPassed, - FinishedAt: time.Now(), - }, - ) - if err != nil { - t.Fatalf("SetTestCompleted() error = %v", err) - } - - if completed { - t.Fatal( - "expected suite to remain incomplete", - ) - } -} - -func TestUpdaterSetTestCompletedSuitePassed(t *testing.T) { - firstFinishedAt := time.Date( - 2026, 9, 18, 10, 1, 0, 0, time.UTC, +func TestUpdaterSetTestCompletedSuiteStates(t *testing.T) { + base := time.Date( + 2026, 9, 18, 10, 0, 0, 0, time.UTC, ) - secondFinishedAt := firstFinishedAt.Add(time.Minute) - testRepository := &testExecutionRepository{ - executions: []repository.TestExecution{ - { - Status: string( - model.ExecutionStatusPassed, - ), - FinishedAt: firstFinishedAt, + stateErr := errors.New("get states") + completionErr := errors.New("set suite completed") + lookupErr := errors.New("get status") + + testCases := []struct { + name string + + states []repository.TestSuiteExecutionState + alreadyCompleted bool + stateErr error + + completionErr error + currentStatus repository.ExecutionStatus + statusErr error + shouldFinalize bool + shouldLookup bool + + wantStatus model.ExecutionStatus + wantFinished time.Time + wantSummary model.TestSuiteExecutionSummary + wantCompleted bool + wantErr error + }{ + { + name: "running", + states: []repository.TestSuiteExecutionState{ + { + Status: repository.ExecutionStatusPassed, + Count: 1, + LastTestFinishedAt: base, + }, + { + Status: repository.ExecutionStatusRunning, + Count: 1, + }, }, - { - Status: string( - model.ExecutionStatusPassed, - ), - FinishedAt: secondFinishedAt, + }, + { + name: "scheduled", + states: []repository.TestSuiteExecutionState{ + { + Status: repository.ExecutionStatusScheduled, + Count: 1, + }, + { + Status: repository.ExecutionStatusPassed, + Count: 1, + LastTestFinishedAt: base, + }, }, }, - } - - suiteRepository := &testSuiteExecutionRepository{} - - updater := NewUpdater( - testRepository, - suiteRepository, - ) - - completed, err := updater.SetTestCompleted( - context.Background(), - execute.TestExecutionResult{ - ExecutionID: "test-execution-2", - TestSuiteExecutionID: "suite-execution-1", - Status: model.ExecutionStatusPassed, - FinishedAt: secondFinishedAt, + { + name: "empty", }, - ) - if err != nil { - t.Fatalf("SetTestCompleted() error = %v", err) - } - - if !completed { - t.Fatal("expected suite to be completed") - } - - assertSuiteCompleted( - t, - suiteRepository.completed, - model.ExecutionStatusPassed, - secondFinishedAt, - model.TestSuiteExecutionSummary{ - Total: 2, - Passed: 2, + { + name: "already completed", + alreadyCompleted: true, }, - ) -} - -func TestUpdaterSetTestCompletedSuiteFailed(t *testing.T) { - finishedAt := time.Date( - 2026, 9, 18, 10, 2, 0, 0, time.UTC, - ) - - testRepository := &testExecutionRepository{ - executions: []repository.TestExecution{ - { - Status: string( - model.ExecutionStatusPassed, - ), - FinishedAt: finishedAt.Add(-time.Minute), + { + name: "already completed skips states", + alreadyCompleted: true, + states: []repository.TestSuiteExecutionState{ + { + Status: repository.ExecutionStatusPassed, + Count: 1, + LastTestFinishedAt: base, + }, }, - { - Status: string( - model.ExecutionStatusFailed, - ), - FinishedAt: finishedAt, + }, + { + name: "passed", + states: []repository.TestSuiteExecutionState{ + { + Status: repository.ExecutionStatusPassed, + Count: 2, + LastTestFinishedAt: base.Add(2 * time.Minute), + }, }, + wantStatus: model.ExecutionStatusPassed, + wantFinished: base.Add(2 * time.Minute), + wantSummary: model.TestSuiteExecutionSummary{Total: 2, Passed: 2}, + wantCompleted: true, + shouldFinalize: true, }, - } - - suiteRepository := &testSuiteExecutionRepository{} - - updater := NewUpdater( - testRepository, - suiteRepository, - ) - - completed, err := updater.SetTestCompleted( - context.Background(), - execute.TestExecutionResult{ - ExecutionID: "test-execution-2", - TestSuiteExecutionID: "suite-execution-1", - Status: model.ExecutionStatusFailed, - FinishedAt: finishedAt, + { + name: "failed", + states: []repository.TestSuiteExecutionState{ + { + Status: repository.ExecutionStatusPassed, + Count: 1, + LastTestFinishedAt: base, + }, + { + Status: repository.ExecutionStatusFailed, + Count: 2, + LastTestFinishedAt: base.Add(time.Minute), + }, + }, + wantStatus: model.ExecutionStatusFailed, + wantFinished: base.Add(time.Minute), + wantSummary: model.TestSuiteExecutionSummary{Total: 3, Passed: 1, Failed: 2}, + wantCompleted: true, + shouldFinalize: true, }, - ) - if err != nil { - t.Fatalf("SetTestCompleted() error = %v", err) - } - - if !completed { - t.Fatal("expected suite to be completed") - } - - assertSuiteCompleted( - t, - suiteRepository.completed, - model.ExecutionStatusFailed, - finishedAt, - model.TestSuiteExecutionSummary{ - Total: 2, - Passed: 1, - Failed: 1, + { + name: "error precedence", + states: []repository.TestSuiteExecutionState{ + { + Status: repository.ExecutionStatusError, + Count: 1, + LastTestFinishedAt: base, + }, + { + Status: repository.ExecutionStatusFailed, + Count: 1, + LastTestFinishedAt: base.Add(3 * time.Minute), + }, + { + Status: repository.ExecutionStatusPassed, + Count: 1, + LastTestFinishedAt: base.Add(time.Minute), + }, + }, + wantStatus: model.ExecutionStatusError, + wantFinished: base.Add(3 * time.Minute), + wantSummary: model.TestSuiteExecutionSummary{Total: 3, Passed: 1, Failed: 1, Errors: 1}, + wantCompleted: true, + shouldFinalize: true, }, - ) -} - -func TestUpdaterSetTestCompletedSuiteErrorPrecedence( - t *testing.T, -) { - finishedAt := time.Date( - 2026, 9, 18, 10, 3, 0, 0, time.UTC, - ) - - testRepository := &testExecutionRepository{ - executions: []repository.TestExecution{ - { - Status: string( - model.ExecutionStatusPassed, - ), - FinishedAt: finishedAt.Add(-3 * time.Minute), + { + name: "invalid status", + states: []repository.TestSuiteExecutionState{ + {Status: repository.ExecutionStatus("invalid"), Count: 1}, }, - { - Status: string( - model.ExecutionStatusError, - ), - FinishedAt: finishedAt.Add(-2 * time.Minute), + wantErr: ErrInvalidExecutionStatus, + }, + { + name: "missing finish time", + states: []repository.TestSuiteExecutionState{ + {Status: repository.ExecutionStatusPassed, Count: 1}, }, - { - Status: string( - model.ExecutionStatusFailed, - ), - FinishedAt: finishedAt, + wantErr: ErrInvalidExecutionStatus, + }, + { + name: "states query error", + stateErr: stateErr, + wantErr: stateErr, + }, + { + name: "suite completion error", + states: []repository.TestSuiteExecutionState{ + { + Status: repository.ExecutionStatusPassed, + Count: 1, + LastTestFinishedAt: base, + }, }, + completionErr: completionErr, + wantErr: completionErr, + shouldFinalize: true, + wantStatus: model.ExecutionStatusPassed, + wantFinished: base, + wantSummary: model.TestSuiteExecutionSummary{Total: 1, Passed: 1}, }, - } - - suiteRepository := &testSuiteExecutionRepository{} - - updater := NewUpdater( - testRepository, - suiteRepository, - ) - - completed, err := updater.SetTestCompleted( - context.Background(), - execute.TestExecutionResult{ - ExecutionID: "test-execution-3", - TestSuiteExecutionID: "suite-execution-1", - Status: model.ExecutionStatusFailed, - FinishedAt: finishedAt, + { + name: "concurrent suite completion", + states: []repository.TestSuiteExecutionState{ + { + Status: repository.ExecutionStatusPassed, + Count: 1, + LastTestFinishedAt: base, + }, + }, + completionErr: repository.ErrInvalidExecutionStateTransition, + currentStatus: repository.ExecutionStatusPassed, + shouldFinalize: true, + shouldLookup: true, + wantStatus: model.ExecutionStatusPassed, + wantFinished: base, + wantSummary: model.TestSuiteExecutionSummary{Total: 1, Passed: 1}, }, - ) - if err != nil { - t.Fatalf("SetTestCompleted() error = %v", err) - } - - if !completed { - t.Fatal("expected suite to be completed") - } - - assertSuiteCompleted( - t, - suiteRepository.completed, - model.ExecutionStatusError, - finishedAt, - model.TestSuiteExecutionSummary{ - Total: 3, - Passed: 1, - Failed: 1, - Errors: 1, + { + name: "concurrent suite completion failed", + states: []repository.TestSuiteExecutionState{ + { + Status: repository.ExecutionStatusPassed, + Count: 1, + LastTestFinishedAt: base, + }, + }, + completionErr: repository.ErrInvalidExecutionStateTransition, + currentStatus: repository.ExecutionStatusFailed, + shouldFinalize: true, + shouldLookup: true, + wantStatus: model.ExecutionStatusPassed, + wantFinished: base, + wantSummary: model.TestSuiteExecutionSummary{Total: 1, Passed: 1}, }, - ) -} - -func TestUpdaterSetTestCompletedInvalidStatus(t *testing.T) { - updater := NewUpdater( - &testExecutionRepository{ - executions: []repository.TestExecution{ + { + name: "rejected while running", + states: []repository.TestSuiteExecutionState{ { - Status: "invalid", + Status: repository.ExecutionStatusPassed, + Count: 1, + LastTestFinishedAt: base, }, }, + completionErr: repository.ErrInvalidExecutionStateTransition, + currentStatus: repository.ExecutionStatusRunning, + wantErr: repository.ErrInvalidExecutionStateTransition, + shouldFinalize: true, + shouldLookup: true, + wantStatus: model.ExecutionStatusPassed, + wantFinished: base, + wantSummary: model.TestSuiteExecutionSummary{Total: 1, Passed: 1}, }, - &testSuiteExecutionRepository{}, - ) - - completed, err := updater.SetTestCompleted( - context.Background(), - execute.TestExecutionResult{ - ExecutionID: "test-execution-1", - TestSuiteExecutionID: "suite-execution-1", - Status: model.ExecutionStatusPassed, + { + name: "status lookup error", + states: []repository.TestSuiteExecutionState{ + { + Status: repository.ExecutionStatusPassed, + Count: 1, + LastTestFinishedAt: base, + }, + }, + completionErr: repository.ErrInvalidExecutionStateTransition, + statusErr: lookupErr, + wantErr: lookupErr, + shouldFinalize: true, + shouldLookup: true, + wantStatus: model.ExecutionStatusPassed, + wantFinished: base, + wantSummary: model.TestSuiteExecutionSummary{Total: 1, Passed: 1}, }, - ) - - if !errors.Is(err, ErrInvalidExecutionStatus) { - t.Fatalf( - "expected ErrInvalidExecutionStatus, got %v", - err, - ) } - if completed { - t.Fatal("expected completed to be false") + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + ctrl := gomock.NewController(t) + tests := mock.NewMockTestExecutionRepository(ctrl) + suites := mock.NewMockTestSuiteExecutionRepository(ctrl) + + tests.EXPECT(). + SetCompleted(gomock.Any(), gomock.Any()). + Return(nil) + + tests.EXPECT(). + GetTestSuiteExecutionStates( + gomock.Any(), + suiteExecutionID, + ). + Return(tc.states, tc.alreadyCompleted, tc.stateErr) + + if tc.shouldFinalize { + suites.EXPECT(). + SetCompleted(gomock.Any(), gomock.Any()). + DoAndReturn( + func( + _ any, + params *repository.SetCompletedParams, + ) error { + assertSuiteCompleted( + t, + params, + tc.wantStatus, + tc.wantFinished, + tc.wantSummary, + ) + return tc.completionErr + }, + ) + } + + if tc.shouldLookup { + suites.EXPECT(). + GetStatus(gomock.Any(), suiteExecutionID). + Return(tc.currentStatus, tc.statusErr) + } + + completed, err := NewUpdater(tests, suites). + SetTestCompleted( + t.Context(), + execute.TestExecutionResult{ + ExecutionID: testExecutionID, + TestSuiteExecutionID: suiteExecutionID, + Status: model.ExecutionStatusPassed, + FinishedAt: base, + }, + ) + + if completed != tc.wantCompleted { + t.Errorf( + "completed=%v, want %v", + completed, + tc.wantCompleted, + ) + } + + if tc.wantErr == nil && err != nil { + t.Fatalf("unexpected error: %v", err) + } + if tc.wantErr != nil && !errors.Is(err, tc.wantErr) { + t.Fatalf( + "error=%v, want %v", + err, + tc.wantErr, + ) + } + }) } } -func TestUpdaterSetTestCompletedGetSuiteExecutionsError( - t *testing.T, -) { - expectedErr := errors.New("get executions") - - updater := NewUpdater( - &testExecutionRepository{ - getErr: expectedErr, - }, - &testSuiteExecutionRepository{}, - ) +func TestUpdaterTryCompleteTestSuite(t *testing.T) { + ctrl := gomock.NewController(t) + tests := mock.NewMockTestExecutionRepository(ctrl) + suites := mock.NewMockTestSuiteExecutionRepository(ctrl) - completed, err := updater.SetTestCompleted( - context.Background(), - execute.TestExecutionResult{ - ExecutionID: "test-execution-1", - TestSuiteExecutionID: "suite-execution-1", - Status: model.ExecutionStatusPassed, - }, - ) + tests.EXPECT(). + GetTestSuiteExecutionStates( + gomock.Any(), + suiteExecutionID, + ). + Return(nil, true, nil) - if !errors.Is(err, expectedErr) { - t.Fatalf( - "expected error %v, got %v", - expectedErr, - err, - ) - } + completed, err := NewUpdater(tests, suites). + TryCompleteTestSuite(t.Context(), suiteExecutionID) - if completed { - t.Fatal("expected completed to be false") + if err != nil || completed { + t.Fatalf("completed=%v, err=%v", completed, err) } } @@ -637,111 +612,112 @@ func TestUpdaterSetTestSuiteCompleted(t *testing.T) { Passed: 3, } - suiteRepository := &testSuiteExecutionRepository{} - updater := NewUpdater( - &testExecutionRepository{}, - suiteRepository, - ) + ctrl := gomock.NewController(t) + suites := mock.NewMockTestSuiteExecutionRepository(ctrl) + + suites.EXPECT(). + SetCompleted(gomock.Any(), gomock.Any()). + DoAndReturn( + func( + _ any, + params *repository.SetCompletedParams, + ) error { + assertSuiteCompleted( + t, + params, + model.ExecutionStatusPassed, + finishedAt, + *summary, + ) + return nil + }, + ) - completed, err := updater.SetTestSuiteCompleted( - context.Background(), + completed, err := NewUpdater( + mock.NewMockTestExecutionRepository(ctrl), + suites, + ).SetTestSuiteCompleted( + t.Context(), execute.TestSuiteExecutionResult{ - ExecutionID: "suite-execution-1", + ExecutionID: suiteExecutionID, Status: model.ExecutionStatusPassed, FinishedAt: finishedAt, Summary: summary, }, ) - if err != nil { - t.Fatalf( - "SetTestSuiteCompleted() error = %v", - err, - ) - } - if !completed { - t.Fatal("expected completed to be true") + if err != nil || !completed { + t.Fatalf("completed=%v, err=%v", completed, err) } - - assertSuiteCompleted( - t, - suiteRepository.completed, - model.ExecutionStatusPassed, - finishedAt, - *summary, - ) } -func TestUpdaterSetTestSuiteCompletedNilSummary( - t *testing.T, -) { - suiteRepository := &testSuiteExecutionRepository{} - updater := NewUpdater( - &testExecutionRepository{}, - suiteRepository, - ) +func TestUpdaterSetTestSuiteCompletedNilSummary(t *testing.T) { + ctrl := gomock.NewController(t) + suites := mock.NewMockTestSuiteExecutionRepository(ctrl) + + suites.EXPECT(). + SetCompleted(gomock.Any(), gomock.Any()). + DoAndReturn( + func( + _ any, + params *repository.SetCompletedParams, + ) error { + if params.Summary != nil { + t.Errorf( + "expected nil summary, got %s", + params.Summary, + ) + } + return nil + }, + ) - completed, err := updater.SetTestSuiteCompleted( - context.Background(), + completed, err := NewUpdater( + mock.NewMockTestExecutionRepository(ctrl), + suites, + ).SetTestSuiteCompleted( + t.Context(), execute.TestSuiteExecutionResult{ - ExecutionID: "suite-execution-1", + ExecutionID: suiteExecutionID, Status: model.ExecutionStatusError, FinishedAt: time.Now(), }, ) - if err != nil { - t.Fatalf( - "SetTestSuiteCompleted() error = %v", - err, - ) - } - - if !completed { - t.Fatal("expected completed to be true") - } - if suiteRepository.completed.Summary != nil { - t.Errorf( - "expected nil summary, got %s", - suiteRepository.completed.Summary, - ) + if err != nil || !completed { + t.Fatalf("completed=%v, err=%v", completed, err) } } func TestUpdaterSetTestSuiteCompletedError(t *testing.T) { - expectedErr := errors.New("set suite completed") + expected := errors.New("set suite completed") - updater := NewUpdater( - &testExecutionRepository{}, - &testSuiteExecutionRepository{ - setCompletedErr: expectedErr, - }, - ) + ctrl := gomock.NewController(t) + suites := mock.NewMockTestSuiteExecutionRepository(ctrl) + + suites.EXPECT(). + SetCompleted(gomock.Any(), gomock.Any()). + Return(expected) - completed, err := updater.SetTestSuiteCompleted( - context.Background(), + completed, err := NewUpdater( + mock.NewMockTestExecutionRepository(ctrl), + suites, + ).SetTestSuiteCompleted( + t.Context(), execute.TestSuiteExecutionResult{ - ExecutionID: "suite-execution-1", + ExecutionID: suiteExecutionID, Status: model.ExecutionStatusError, }, ) - if !errors.Is(err, expectedErr) { - t.Fatalf( - "expected error %v, got %v", - expectedErr, - err, - ) - } - - if completed { - t.Fatal("expected completed to be false") + if completed || !errors.Is(err, expected) { + t.Fatalf("completed=%v, err=%v", completed, err) } } func assertSuiteCompleted( t *testing.T, - params *SetCompletedParams, + params *repository.SetCompletedParams, status model.ExecutionStatus, finishedAt time.Time, expectedSummary model.TestSuiteExecutionSummary, @@ -749,109 +725,46 @@ func assertSuiteCompleted( t.Helper() if params == nil { - t.Fatal( - "expected suite SetCompleted() to be called", + t.Fatal("expected suite SetCompleted parameters") + } + + if params.ID != suiteExecutionID { + t.Errorf( + "ID=%q, want %q", + params.ID, + suiteExecutionID, ) } - if params.Status != string(status) { + if params.Status != repository.ExecutionStatus(status) { t.Errorf( - "expected status %s, got %s", - status, + "status=%q, want %q", params.Status, + status, ) } if !params.FinishedAt.Equal(finishedAt) { t.Errorf( - "expected FinishedAt %v, got %v", - finishedAt, + "FinishedAt=%v, want %v", params.FinishedAt, + finishedAt, ) } - var actualSummary model.TestSuiteExecutionSummary + var actual model.TestSuiteExecutionSummary if err := json.Unmarshal( params.Summary, - &actualSummary, + &actual, ); err != nil { - t.Fatalf( - "cannot unmarshal suite summary: %v", - err, - ) + t.Fatalf("unmarshal summary: %v", err) } - if actualSummary != expectedSummary { + if actual != expectedSummary { t.Errorf( - "expected summary %+v, got %+v", + "summary=%+v, want %+v", + actual, expectedSummary, - actualSummary, ) } } - -type testExecutionRepository struct { - executions []repository.TestExecution - - running *SetRunningParams - completed *SetCompletedParams - - getErr error - setRunningErr error - setCompletedErr error -} - -func (r *testExecutionRepository) GetByTestSuiteExecutionID( - _ context.Context, - _ string, -) ([]repository.TestExecution, error) { - if r.getErr != nil { - return nil, r.getErr - } - - return r.executions, nil -} - -func (r *testExecutionRepository) SetRunning( - _ context.Context, - params *SetRunningParams, -) error { - r.running = params - - return r.setRunningErr -} - -func (r *testExecutionRepository) SetCompleted( - _ context.Context, - params *SetCompletedParams, -) error { - r.completed = params - - return r.setCompletedErr -} - -type testSuiteExecutionRepository struct { - running *SetRunningParams - completed *SetCompletedParams - - setRunningErr error - setCompletedErr error -} - -func (r *testSuiteExecutionRepository) SetRunning( - _ context.Context, - params *SetRunningParams, -) error { - r.running = params - - return r.setRunningErr -} - -func (r *testSuiteExecutionRepository) SetCompleted( - _ context.Context, - params *SetCompletedParams, -) error { - r.completed = params - - return r.setCompletedErr -} diff --git a/execute/runtime/config/config.go b/execute/runtime/config/config.go index 3993429..86f9449 100644 --- a/execute/runtime/config/config.go +++ b/execute/runtime/config/config.go @@ -2,16 +2,49 @@ package config import ( "time" + + grpcservice "github.com/e2engine/core/execute/runtime/service/grpc" + httpservice "github.com/e2engine/core/execute/runtime/service/http" ) type Config struct { - ServiceProvider *ProviderConfig `json:"service_provider" yaml:"service_provider" env:"SERVICE_PROVIDER" default:"dive" validateElem:"omitempty"` - EnvironmentCleanupTimeout time.Duration `json:"environment_cleanup_timeout" yaml:"environment_cleanup_timeout" env:"ENVIRONMENT_CLEANUP_TIMEOUT" default:"30s" validate:"min(1s)"` - JobPublishTimeout time.Duration `json:"job_publish_timeout" yaml:"job_publish_timeout" env:"JOB_PUBLISH_TIMEOUT" default:"30s" validate:"min(1s)"` - ExecutionCheckTimeout time.Duration `json:"execution_check_timeout" yaml:"execution_check_timeout" env:"EXECUTION_CHECK_TIMEOUT" default:"30s" validate:"min(1s)"` - MaxResolvedTests int `json:"max_resolved_tests" yaml:"max_resolved_tests" env:"MAX_RESOLVED_TESTS" default:"1000" validate:"min(1)"` + Service *ServiceConfig `json:"service" yaml:"service" env:"SERVICE" default:"dive" validateElem:"omitempty"` + Router *RouterConfig `json:"router" yaml:"router" env:"ROUTER" default:"dive"` + EnvironmentCleanupTimeout time.Duration `json:"environment_cleanup_timeout" yaml:"environment_cleanup_timeout" env:"ENVIRONMENT_CLEANUP_TIMEOUT" default:"30s" validate:"min(1s),max(10m)"` + JobPublishTimeout time.Duration `json:"job_publish_timeout" yaml:"job_publish_timeout" env:"JOB_PUBLISH_TIMEOUT" default:"30s" validate:"min(1s),max(5m)"` + ExecutionCheckTimeout time.Duration `json:"execution_check_timeout" yaml:"execution_check_timeout" env:"EXECUTION_CHECK_TIMEOUT" default:"30s" validate:"min(1s),max(5m)"` + MaxResolvedTests int `json:"max_resolved_tests" yaml:"max_resolved_tests" env:"MAX_RESOLVED_TESTS" default:"1000" validate:"min(1),max(10000)"` + E2EngineListenInterface string `json:"e2engine_listen_interface" yaml:"e2engine_listen_interface" env:"E2ENGINE_LISTEN_INTERFACE" default:"127.0.0.1" validate:"ip"` +} + +type ServiceConfig struct { + MockHTTP *httpservice.MockHTTPServiceConfig `json:"mock_http" yaml:"mock_http" default:"dive"` + MockGRPC *grpcservice.MockGRPCServiceConfig `json:"mock_grpc" yaml:"mock_grpc" default:"dive"` + RealHTTP *httpservice.RealHTTPServiceConfig `json:"real_http" yaml:"real_http" default:"dive"` + RealGRPC *grpcservice.RealGRPCServiceConfig `json:"real_grpc" yaml:"real_grpc" default:"dive"` + // BufDescriptorLoaderToken is a token used to authenticate with the Buf Descriptor Loader service. + // It can be provided via environment variable. + BufDescriptorLoaderToken string `json:"-" yaml:"-" env:"BUF_DESCRIPTOR_LOADER_TOKEN"` } -type ProviderConfig struct { - BufDescriptorLoaderToken string `json:"buf_descriptor_loader_token,omitempty" yaml:"buf_descriptor_loader_token,omitempty" env:"BUF_DESCRIPTOR_LOADER_TOKEN"` // TODO: add validation. +type RouterConfig struct { + HTTP *HTTPRouterConfig `json:"http" yaml:"http" default:"dive"` + GRPC *GRPCRouterConfig `json:"grpc" yaml:"grpc" default:"dive"` +} + +type HTTPRouterConfig struct { + MaxRecordedBodySize int64 `json:"max_recorded_body_size" yaml:"max_recorded_body_size" env:"MAX_RECORDED_BODY_SIZE" default:"1048576" validate:"min(1),max(67108864)"` + + ReadHeaderTimeout time.Duration `json:"read_header_timeout" yaml:"read_header_timeout" env:"READ_HEADER_TIMEOUT" default:"5s" validate:"min(1s),max(1m)"` + IdleTimeout time.Duration `json:"idle_timeout" yaml:"idle_timeout" env:"IDLE_TIMEOUT" default:"60s" validate:"min(1s),max(10m)"` + + ResponseHeaderTimeout time.Duration `json:"response_header_timeout" yaml:"response_header_timeout" env:"RESPONSE_HEADER_TIMEOUT" default:"30s" validate:"min(1s),max(5m)"` + + MaxResponseHeaderBytes int64 `json:"max_response_header_bytes" yaml:"max_response_header_bytes" env:"MAX_RESPONSE_HEADER_BYTES" default:"1048576" validate:"min(1024),max(16777216)"` +} + +type GRPCRouterConfig struct { + MaxMessageSize int `json:"max_message_size" yaml:"max_message_size" env:"MAX_MESSAGE_SIZE" default:"4194304" validate:"min(1),max(67108864)"` + + MaxMetadataSize uint32 `json:"max_metadata_size" yaml:"max_metadata_size" env:"MAX_METADATA_SIZE" default:"65536" validate:"min(1024),max(1048576)"` } diff --git a/execute/runtime/environment.go b/execute/runtime/environment.go index 20c7225..5d2293b 100644 --- a/execute/runtime/environment.go +++ b/execute/runtime/environment.go @@ -3,6 +3,8 @@ package runtime import ( "context" nativeerrors "errors" + "net" + "strconv" "sync" "github.com/ygrebnov/errorc" @@ -83,9 +85,12 @@ func (e *Environment) Mount(ctx context.Context) error { } route := &Route{ - ServiceID: e.spec.Services[i].ID, - Kind: e.spec.Services[i].Kind, - ListenAddress: e.spec.Services[i].Address, + ServiceID: e.spec.Services[i].ID, + Kind: e.spec.Services[i].Kind, + ListenAddress: net.JoinHostPort( + e.cfg.E2EngineListenInterface, + strconv.Itoa(e.spec.Services[i].E2EnginePort), + ), RuntimeAddress: e.services[i].GetRuntimeAddress(), } diff --git a/execute/runtime/environment_test.go b/execute/runtime/environment_test.go index 4c0d9a8..de446b8 100644 --- a/execute/runtime/environment_test.go +++ b/execute/runtime/environment_test.go @@ -861,9 +861,16 @@ func newTestEnvironment( t *testing.T, services []runtime.Service, router runtime.Router, + listenInterface ...string, ) *runtime.Environment { t.Helper() + interfaceAddress := "127.0.0.1" + + if len(listenInterface) > 0 { + interfaceAddress = listenInterface[0] + } + logger, err := log.NewSilentLogger() if err != nil { t.Fatalf( @@ -878,10 +885,10 @@ func newTestEnvironment( for i := range services { spec.Services[i] = model.ServiceSpec{ - ID: fmt.Sprintf("service-%d", i+1), - Kind: model.ServiceKindHTTP, - Mode: model.ServiceModeMocked, - Address: fmt.Sprintf("127.0.0.1:808%d", i+1), + ID: fmt.Sprintf("service-%d", i+1), + Kind: model.ServiceKindHTTP, + Mode: model.ServiceModeMocked, + E2EnginePort: 8081 + i, Fixtures: []model.FixtureSpec{ { When: model.FixtureWhen{ @@ -926,13 +933,19 @@ func newTestEnvironment( env, err := runtime.NewEnvironment( context.Background(), &config.Config{ + E2EngineListenInterface: interfaceAddress, EnvironmentCleanupTimeout: time.Second, }, logger, modelEnv, serviceProvider, routerProvider, - call.NewStoreFactory().New(), + call.NewStoreFactory( + &call.Config{ + MaxCalls: 1000, + MaxRecordedBytes: 1024 * 1024, + }, + ).New(), ) if err != nil { t.Fatalf( @@ -961,12 +974,18 @@ func newTestEnvironmentController( return runtime.NewEnvironmentController( &config.Config{ + E2EngineListenInterface: "127.0.0.1", EnvironmentCleanupTimeout: time.Second, }, logger, serviceProvider, routerProvider, - call.NewStoreFactory(), + call.NewStoreFactory( + &call.Config{ + MaxCalls: 1000, + MaxRecordedBytes: 1024 * 1024, + }, + ), ) } @@ -979,10 +998,10 @@ func validTestEnvironment() *model.Environment { Spec: model.EnvironmentSpec{ Services: []model.ServiceSpec{ { - ID: "7398ab887149ec5aa583c564a659a0b0a933ef27bacb675b081a2a752d8a3896", - Kind: model.ServiceKindHTTP, - Mode: model.ServiceModeMocked, - Address: "127.0.0.1:8081", + ID: "7398ab887149ec5aa583c564a659a0b0a933ef27bacb675b081a2a752d8a3896", + Kind: model.ServiceKindHTTP, + Mode: model.ServiceModeMocked, + E2EnginePort: 8081, Fixtures: []model.FixtureSpec{ { When: model.FixtureWhen{ @@ -1087,3 +1106,43 @@ func TestEnvironmentMountRouterErrorUsesCleanupContext( ) } } + +func TestEnvironmentMountCustomListenInterface(t *testing.T) { + ctrl := gomock.NewController(t) + + service := mock.NewMockService(ctrl) + router := mock.NewMockRouter(ctrl) + + env := newTestEnvironment( + t, + []runtime.Service{service}, + router, + "0.0.0.0", + ) + + gomock.InOrder( + service.EXPECT(). + Mount(gomock.Any()). + Return(nil), + + service.EXPECT(). + GetRuntimeAddress(). + Return("127.0.0.1:10001"), + + router.EXPECT(). + Register(&runtime.Route{ + ServiceID: "service-1", + Kind: model.ServiceKindHTTP, + ListenAddress: "0.0.0.0:8081", + RuntimeAddress: "127.0.0.1:10001", + }), + + router.EXPECT(). + Mount(gomock.Any()). + Return(nil), + ) + + if err := env.Mount(context.Background()); err != nil { + t.Fatalf("Mount() error = %v", err) + } +} diff --git a/execute/runtime/router/grpc/router.go b/execute/runtime/router/grpc/router.go index 897d135..c4f0402 100644 --- a/execute/runtime/router/grpc/router.go +++ b/execute/runtime/router/grpc/router.go @@ -5,11 +5,11 @@ import ( nativeerrors "errors" "fmt" "net" + "slices" "strings" e2engine "github.com/e2engine/instrumentation-go" e2enginegrpc "github.com/e2engine/instrumentation-go/grpc" - "github.com/ygrebnov/errorc" grpcpkg "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials/insecure" @@ -19,12 +19,15 @@ import ( "github.com/e2engine/core/execute/call" "github.com/e2engine/core/execute/runtime" + "github.com/e2engine/core/execute/runtime/config" + "github.com/e2engine/core/internal/util" "github.com/e2engine/core/pkg/errors" "github.com/e2engine/core/pkg/keys" "github.com/e2engine/core/pkg/log" ) type Router struct { + cfg *config.GRPCRouterConfig logger log.Logger calls call.Recorder @@ -33,10 +36,12 @@ type Router struct { } func NewRouter( + cfg *config.GRPCRouterConfig, logger log.Logger, calls call.Recorder, ) *Router { return &Router{ + cfg: cfg, logger: logger, calls: calls, services: make(map[string]*runtime.Route), @@ -124,8 +129,13 @@ func (r *Router) Mount(ctx context.Context) error { grpcpkg.WithTransportCredentials( insecure.NewCredentials(), ), + grpcpkg.WithMaxHeaderListSize( + r.cfg.MaxMetadataSize, + ), grpcpkg.WithDefaultCallOptions( grpcpkg.ForceCodec(rawCodec{}), + grpcpkg.MaxCallRecvMsgSize(r.cfg.MaxMessageSize), + grpcpkg.MaxCallSendMsgSize(r.cfg.MaxMessageSize), ), ) if err != nil { @@ -163,6 +173,11 @@ func (r *Router) Mount(ctx context.Context) error { server := grpcpkg.NewServer( grpcpkg.ForceServerCodec(rawCodec{}), + grpcpkg.MaxHeaderListSize( + r.cfg.MaxMetadataSize, + ), + grpcpkg.MaxRecvMsgSize(r.cfg.MaxMessageSize), + grpcpkg.MaxSendMsgSize(r.cfg.MaxMessageSize), grpcpkg.UnknownServiceHandler(handler), ) @@ -235,34 +250,17 @@ func (r *Router) newHandler( var request rawMessage if err := stream.RecvMsg(&request); err != nil { - captureErr := errorc.With( - errors.ErrFailedToCaptureEnvironmentServiceCall, - errorc.String( - keys.EnvironmentServiceID, - route.ServiceID, - ), - errorc.Error( - keys.Cause, - err, - ), - ) - r.logger.Error( errors.ErrFailedToCaptureEnvironmentServiceCall.Error(), - log.String( - keys.EnvironmentServiceID, - route.ServiceID, - ), - log.String( - keys.GRPCMethod, - fullMethod, - ), - log.Err( - keys.Cause, - captureErr, - ), + log.String(keys.EnvironmentServiceID, route.ServiceID), + log.String(keys.GRPCMethod, fullMethod), + log.String(keys.GRPCStatus, status.Code(err).String()), ) + if status.Code(err) == codes.ResourceExhausted { + return err + } + return status.Error( codes.Internal, "failed to receive gRPC request", @@ -299,7 +297,7 @@ func (r *Router) newHandler( service, method := splitFullMethod(fullMethod) - r.calls.Record( + if errRecord := r.calls.Record( call.Call{ TestExecutionID: testExecutionID, ServiceID: route.ServiceID, @@ -307,10 +305,10 @@ func (r *Router) newHandler( Request: call.GRPCRequest{ Service: service, Method: method, - Metadata: cloneMetadata( + Metadata: util.CloneStringSliceMap( incomingMetadata, ), - Message: cloneBytes( + Message: slices.Clone( request, ), }, @@ -320,13 +318,21 @@ func (r *Router) newHandler( responseHeader, responseTrailer, ), - Message: cloneBytes( + Message: slices.Clone( response, ), }, }, }, - ) + ); errRecord != nil { + r.logger.Error( + "Failed to record environment gRPC call", + log.String(keys.EnvironmentServiceID, route.ServiceID), + log.String(keys.GRPCService, service), + log.String(keys.GRPCMethod, method), + log.Err(keys.Cause, errRecord), + ) + } if len(responseHeader) > 0 { if errSend := stream.SendHeader( @@ -358,22 +364,6 @@ func splitFullMethod(fullMethod string) (service, method string) { return service, method } -func cloneMetadata(source metadata.MD) map[string][]string { - result := make( - map[string][]string, - len(source), - ) - - for key, values := range source { - result[key] = append( - []string(nil), - values..., - ) - } - - return result -} - func mergeMetadata( sources ...metadata.MD, ) map[string][]string { @@ -391,22 +381,9 @@ func mergeMetadata( return result } -func cloneBytes( - source []byte, -) []byte { - return append( - []byte(nil), - source..., - ) -} - func (r *Router) Unmount( ctx context.Context, ) error { - if err := ctx.Err(); err != nil { - return err - } - err := r.unmountMountedRoutes( ctx, r.mounted, diff --git a/execute/runtime/router/grpc/router_test.go b/execute/runtime/router/grpc/router_test.go index be66547..9e3095d 100644 --- a/execute/runtime/router/grpc/router_test.go +++ b/execute/runtime/router/grpc/router_test.go @@ -4,7 +4,10 @@ import ( "context" "errors" "net" + "slices" + "strings" "testing" + "time" e2enginegrpc "github.com/e2engine/instrumentation-go/grpc" grpcpkg "google.golang.org/grpc" @@ -15,6 +18,7 @@ import ( "github.com/e2engine/core/execute/call" "github.com/e2engine/core/execute/runtime" + "github.com/e2engine/core/execute/runtime/config" "github.com/e2engine/core/pkg/log" ) @@ -84,41 +88,6 @@ func TestRawCodec(t *testing.T) { } } -func TestCloneMetadata(t *testing.T) { - source := e2enginegrpc.WithTestExecutionID( - metadata.Pairs( - "x-test", "first", - "x-test", "second", - ), - "execution-1", - ) - - got := cloneMetadata(source) - - values := got["x-test"] - if len(values) != 2 || - values[0] != "first" || - values[1] != "second" { - t.Errorf( - "unexpected cloned metadata: %#v", - got, - ) - } - - if len(got) != 2 { - t.Fatalf( - "expected execution ID metadata to be present, got %#v", - got, - ) - } - - source["x-test"][0] = "changed" - - if got["x-test"][0] != "first" { - t.Fatal("expected metadata values to be cloned") - } -} - func TestMergeMetadata(t *testing.T) { header := metadata.Pairs( "x-shared", "header", @@ -157,21 +126,6 @@ func TestMergeMetadata(t *testing.T) { } } -func TestCloneBytes(t *testing.T) { - source := []byte{1, 2, 3} - - got := cloneBytes(source) - - source[0] = 9 - - if got[0] != 1 { - t.Fatalf( - "expected cloned bytes to be independent, got %v", - got, - ) - } -} - func TestRouter(t *testing.T) { var upstreamMetadata metadata.MD var upstreamRequest rawMessage @@ -188,7 +142,7 @@ func TestRouter(t *testing.T) { return err } - upstreamRequest = cloneBytes(request) + upstreamRequest = slices.Clone(request) md, _ := metadata.FromIncomingContext( stream.Context(), @@ -218,7 +172,11 @@ func TestRouter(t *testing.T) { ) defer upstream.stop() - store := &call.Store{} + store := call.NewStoreFactory( + &call.Config{ + MaxCalls: 1000, + MaxRecordedBytes: 1024 * 1024, + }).New() router := newTestGRPCRouter(t, store) router.Register(&runtime.Route{ @@ -418,6 +376,182 @@ func TestRouter(t *testing.T) { } } +func TestRouterMessageSizeLimit(t *testing.T) { + const limit = 5 + + tests := []struct { + name string + request rawMessage + response rawMessage + wantCode codes.Code + wantRecorded bool + wantUpstream bool + }{ + { + name: "exactly at limit", + request: rawMessage{1, 2, 3, 4, 5}, + response: rawMessage{6, 7, 8, 9, 10}, + wantCode: codes.OK, + wantRecorded: true, + wantUpstream: true, + }, + { + name: "oversized request", + request: rawMessage{1, 2, 3, 4, 5, 6}, + response: rawMessage{7}, + wantCode: codes.ResourceExhausted, + }, + { + name: "oversized response", + request: rawMessage{1}, + response: rawMessage{2, 3, 4, 5, 6, 7}, + wantCode: codes.ResourceExhausted, + wantRecorded: true, + wantUpstream: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + upstreamCalled := make(chan struct{}, 1) + + upstream := newTestGRPCServer( + t, + func(_ any, stream grpcpkg.ServerStream) error { + var request rawMessage + + if err := stream.RecvMsg(&request); err != nil { + return err + } + + upstreamCalled <- struct{}{} + + return stream.SendMsg(&tt.response) + }, + ) + defer upstream.stop() + + store := call.NewStoreFactory( + &call.Config{ + MaxCalls: 1000, + MaxRecordedBytes: 1024 * 1024, + }).New() + router := newTestGRPCRouter(t, store) + router.cfg.MaxMessageSize = limit + + router.Register(&runtime.Route{ + ServiceID: "service-1", + ListenAddress: "127.0.0.1:0", + RuntimeAddress: upstream.address(), + }) + + if err := router.Mount(t.Context()); err != nil { + t.Fatalf("Mount() error = %v", err) + } + + defer func() { + if err := router.Unmount(context.Background()); err != nil { + t.Errorf("Unmount() error = %v", err) + } + }() + + connection, err := grpcpkg.NewClient( + router.mounted[0].listener.Addr().String(), + grpcpkg.WithTransportCredentials( + insecure.NewCredentials(), + ), + grpcpkg.WithDefaultCallOptions( + grpcpkg.ForceCodec(rawCodec{}), + ), + ) + if err != nil { + t.Fatalf("NewClient() error = %v", err) + } + defer connection.Close() + + ctx := metadata.NewOutgoingContext( + t.Context(), + e2enginegrpc.WithTestExecutionID( + nil, + "execution-1", + ), + ) + + var response rawMessage + + err = connection.Invoke( + ctx, + "/test.Service/Method", + &tt.request, + &response, + ) + + if code := status.Code(err); code != tt.wantCode { + t.Fatalf( + "status = %s, want %s (error: %v)", + code, + tt.wantCode, + err, + ) + } + + if tt.wantCode == codes.OK && + string(response) != string(tt.response) { + t.Errorf( + "response = %v, want %v", + response, + tt.response, + ) + } + + calls := store.Get(call.Filter{ + TestExecutionID: "execution-1", + ServiceID: "service-1", + }) + + if tt.wantRecorded { + if len(calls) != 1 { + t.Fatalf( + "recorded calls = %d, want 1", + len(calls), + ) + } + + if calls[0].GRPC == nil { + t.Fatal("expected recorded gRPC call") + } + + if calls[0].GRPC.Response.Status != tt.wantCode.String() { + t.Errorf( + "recorded status = %s, want %s", + calls[0].GRPC.Response.Status, + tt.wantCode, + ) + } + } else if len(calls) != 0 { + t.Errorf( + "recorded calls = %d, want 0", + len(calls), + ) + } + + if tt.wantUpstream { + select { + case <-upstreamCalled: + default: + t.Error("upstream was not invoked") + } + } else { + select { + case <-upstreamCalled: + t.Error("unexpected upstream invocation") + default: + } + } + }) + } +} + func TestRouterUpstreamError(t *testing.T) { upstream := newTestGRPCServer( t, @@ -439,7 +573,11 @@ func TestRouterUpstreamError(t *testing.T) { ) defer upstream.stop() - store := &call.Store{} + store := call.NewStoreFactory( + &call.Config{ + MaxCalls: 1000, + MaxRecordedBytes: 1024 * 1024, + }).New() router := newTestGRPCRouter(t, store) router.Register(&runtime.Route{ @@ -528,7 +666,11 @@ func TestRouterUpstreamError(t *testing.T) { func TestRouterMountCancelledContext(t *testing.T) { router := newTestGRPCRouter( t, - &call.Store{}, + call.NewStoreFactory( + &call.Config{ + MaxCalls: 1000, + MaxRecordedBytes: 1024 * 1024, + }).New(), ) ctx, cancel := context.WithCancel( @@ -547,23 +689,55 @@ func TestRouterMountCancelledContext(t *testing.T) { } func TestRouterUnmountCancelledContext(t *testing.T) { - router := newTestGRPCRouter( + upstream := newTestGRPCServer( t, - &call.Store{}, + func(_ any, stream grpcpkg.ServerStream) error { + return nil + }, ) + defer upstream.stop() - ctx, cancel := context.WithCancel( - context.Background(), + router := newTestGRPCRouter( + t, + call.NewStoreFactory(&call.Config{ + MaxCalls: 1000, + MaxRecordedBytes: 1024 * 1024, + }).New(), ) + + router.Register(&runtime.Route{ + ServiceID: "service-1", + ListenAddress: "127.0.0.1:0", + RuntimeAddress: upstream.address(), + }) + + if err := router.Mount(t.Context()); err != nil { + t.Fatalf("Mount() error = %v", err) + } + + address := router.mounted[0].listener.Addr().String() + + ctx, cancel := context.WithCancel(context.Background()) cancel() err := router.Unmount(ctx) - if !errors.Is(err, context.Canceled) { - t.Fatalf( - "expected context.Canceled, got %v", - err, - ) + if err != nil && !errors.Is(err, context.Canceled) { + t.Fatalf("Unmount() unexpected error = %v", err) + } + + if router.mounted != nil { + t.Fatal("expected mounted routes to be cleared") + } + + connection, err := net.DialTimeout( + "tcp", + address, + time.Second, + ) + if err == nil { + _ = connection.Close() + t.Fatal("listener still accepts connections after unmount") } } @@ -592,7 +766,11 @@ func TestRouterMultipleRoutes(t *testing.T) { router := newTestGRPCRouter( t, - &call.Store{}, + call.NewStoreFactory( + &call.Config{ + MaxCalls: 1000, + MaxRecordedBytes: 1024 * 1024, + }).New(), ) router.Register(&runtime.Route{ @@ -689,6 +867,10 @@ func newTestGRPCRouter( } return NewRouter( + &config.GRPCRouterConfig{ + MaxMessageSize: 4 << 20, + MaxMetadataSize: 64 << 10, + }, logger, store, ) @@ -777,3 +959,244 @@ func TestSplitFullMethod(t *testing.T) { }) } } + +func TestRouterMetadataSizeLimit(t *testing.T) { + const limit uint32 = 1024 + + tests := []struct { + name string + requestValue string + responseValue string + wantOK bool + wantUpstream bool + wantRecorded bool + }{ + { + name: "metadata within limit", + requestValue: "small", + responseValue: "small", + wantOK: true, + wantUpstream: true, + wantRecorded: true, + }, + { + name: "oversized request metadata", + requestValue: strings.Repeat("a", 4096), + }, + { + name: "oversized response metadata", + requestValue: "small", + responseValue: strings.Repeat("b", 4096), + wantUpstream: true, + wantRecorded: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + upstreamCalled := make(chan struct{}, 1) + + upstream := newTestGRPCServer( + t, + func( + _ any, + stream grpcpkg.ServerStream, + ) error { + var request rawMessage + + if err := stream.RecvMsg(&request); err != nil { + return err + } + + upstreamCalled <- struct{}{} + + if err := stream.SendHeader( + metadata.Pairs( + "x-response", + tt.responseValue, + ), + ); err != nil { + return err + } + + response := rawMessage{4, 5, 6} + + return stream.SendMsg(&response) + }, + ) + defer upstream.stop() + + store := call.NewStoreFactory( + &call.Config{ + MaxCalls: 10, + MaxRecordedBytes: 1 << 20, + }, + ).New() + + router := newTestGRPCRouter(t, store) + router.cfg.MaxMetadataSize = limit + + router.Register(&runtime.Route{ + ServiceID: "service-1", + ListenAddress: "127.0.0.1:0", + RuntimeAddress: upstream.address(), + }) + + if err := router.Mount(t.Context()); err != nil { + t.Fatalf( + "Mount() error = %v", + err, + ) + } + + defer func() { + if err := router.Unmount( + context.Background(), + ); err != nil { + t.Errorf( + "Unmount() error = %v", + err, + ) + } + }() + + connection, err := grpcpkg.NewClient( + router.mounted[0].listener.Addr().String(), + grpcpkg.WithTransportCredentials( + insecure.NewCredentials(), + ), + grpcpkg.WithDefaultCallOptions( + grpcpkg.ForceCodec(rawCodec{}), + ), + ) + if err != nil { + t.Fatalf( + "NewClient() error = %v", + err, + ) + } + defer connection.Close() + + ctx := metadata.NewOutgoingContext( + t.Context(), + e2enginegrpc.WithTestExecutionID( + metadata.Pairs( + "x-request", + tt.requestValue, + ), + "execution-1", + ), + ) + + request := rawMessage{1, 2, 3} + + var response rawMessage + var responseHeader metadata.MD + + err = connection.Invoke( + ctx, + "/test.Service/Method", + &request, + &response, + grpcpkg.Header(&responseHeader), + ) + + if tt.wantOK { + if err != nil { + t.Fatalf( + "Invoke() error = %v", + err, + ) + } + + if string(response) != string([]byte{4, 5, 6}) { + t.Errorf( + "response = %v, want [4 5 6]", + response, + ) + } + + values := responseHeader.Get("x-response") + + if len(values) != 1 || + values[0] != tt.responseValue { + t.Errorf( + "response metadata = %v, want [%s]", + values, + tt.responseValue, + ) + } + } else if err == nil { + t.Fatal( + "expected metadata size limit error", + ) + } + + select { + case <-upstreamCalled: + if !tt.wantUpstream { + t.Error( + "unexpected upstream invocation", + ) + } + + default: + if tt.wantUpstream { + t.Error( + "upstream was not invoked", + ) + } + } + + calls := store.Get(call.Filter{ + TestExecutionID: "execution-1", + ServiceID: "service-1", + }) + + if tt.wantRecorded { + if len(calls) != 1 { + t.Fatalf( + "recorded calls = %d, want 1", + len(calls), + ) + } + + if calls[0].GRPC == nil { + t.Fatal( + "expected recorded gRPC call", + ) + } + + if tt.wantOK { + if calls[0].GRPC.Response.Status != + codes.OK.String() { + t.Errorf( + "recorded status = %s, want %s", + calls[0].GRPC.Response.Status, + codes.OK, + ) + } + } else { + if calls[0].GRPC.Response.Status == + codes.OK.String() { + t.Error( + "expected recorded non-OK status", + ) + } + } + } else if len(calls) != 0 { + t.Errorf( + "recorded calls = %d, want 0", + len(calls), + ) + } + + if err := store.Err(); err != nil { + t.Errorf( + "call store error = %v, want nil", + err, + ) + } + }) + } +} diff --git a/execute/runtime/router/http/request.go b/execute/runtime/router/http/request.go index fa102c2..1032e2d 100644 --- a/execute/runtime/router/http/request.go +++ b/execute/runtime/router/http/request.go @@ -1,31 +1,101 @@ package http import ( - "bytes" "io" "net/http" + "slices" + "sync" "github.com/e2engine/core/execute/call" - "github.com/e2engine/core/internal/util" ) -func captureRequest(req *http.Request) (call.HTTPRequest, error) { - rawBody, err := io.ReadAll(req.Body) - if err != nil { - return call.HTTPRequest{}, err +type requestCapturer struct { + request call.HTTPRequest + body *capturingReadCloser +} + +func newRequestCapturer(req *http.Request, maxBodySize int64) *requestCapturer { + capture := &requestCapturer{ + request: call.HTTPRequest{ + Method: req.Method, + Path: req.URL.Path, + Query: req.URL.Query().Clone(), + Headers: req.Header.Clone(), + }, + } + + if req.Body != nil { + capture.body = &capturingReadCloser{ + ReadCloser: req.Body, + maxBodySize: maxBodySize, + contentLength: req.ContentLength, + complete: req.ContentLength == 0, + } + req.Body = capture.body + } + + return capture +} + +func (c *requestCapturer) GetRequest() call.HTTPRequest { + request := c.request + + if c.body != nil { + c.body.mu.Lock() + + request.Body = slices.Clone(c.body.body) + request.BodyTruncated = c.body.truncated + request.BodyComplete = c.body.complete + + c.body.mu.Unlock() + } else { + request.BodyComplete = true } - if err := req.Body.Close(); err != nil { - return call.HTTPRequest{}, err + return request +} + +type capturingReadCloser struct { + mu sync.Mutex + + io.ReadCloser + + maxBodySize int64 + body []byte + truncated bool + complete bool + + contentLength int64 + bytesRead int64 +} + +func (r *capturingReadCloser) Read(p []byte) (int, error) { + n, err := r.ReadCloser.Read(p) + + r.mu.Lock() + defer r.mu.Unlock() + + r.bytesRead += int64(n) + + if n > 0 { + remaining := r.maxBodySize - int64(len(r.body)) + + if remaining > 0 { + captureSize := min(n, int(remaining)) + r.body = append(r.body, p[:captureSize]...) + + if captureSize < n { + r.truncated = true + } + } else { + r.truncated = true + } } - req.Body = io.NopCloser(bytes.NewReader(rawBody)) + if err == io.EOF || + (r.contentLength >= 0 && r.bytesRead == r.contentLength) { + r.complete = true + } - return call.HTTPRequest{ - Method: req.Method, - Path: req.URL.Path, - Query: req.URL.Query().Clone(), - Headers: req.Header.Clone(), - Body: util.CloneBytes(rawBody), - }, nil + return n, err } diff --git a/execute/runtime/router/http/request_test.go b/execute/runtime/router/http/request_test.go index 9171fe0..c412bba 100644 --- a/execute/runtime/router/http/request_test.go +++ b/execute/runtime/router/http/request_test.go @@ -1,6 +1,7 @@ package http import ( + "bytes" "io" "net/http" "strings" @@ -9,12 +10,14 @@ import ( e2enginehttp "github.com/e2engine/instrumentation-go/http" ) -func TestCaptureRequest(t *testing.T) { +func TestRequestCapturer(t *testing.T) { + const body = `{"value":42}` + req, err := http.NewRequestWithContext( t.Context(), http.MethodPost, "http://example.com/path?foo=bar&foo=baz", - strings.NewReader(`{"value":42}`), + strings.NewReader(body), ) if err != nil { t.Fatalf("cannot create request: %v", err) @@ -22,14 +25,29 @@ func TestCaptureRequest(t *testing.T) { req.Header.Set("Content-Type", "application/json") req.Header.Set("X-Test", "test") + req.Header = e2enginehttp.WithTestExecutionID( + req.Header, + "execution-1", + ) - req.Header = e2enginehttp.WithTestExecutionID(req.Header, "execution-1") + capturer := newRequestCapturer(req, 1024) - got, err := captureRequest(req) + // The request body is captured as it is read for forwarding. + forwarded, err := io.ReadAll(req.Body) if err != nil { - t.Fatalf("captureRequest() error = %v", err) + t.Fatalf("cannot read forwarded body: %v", err) + } + + if string(forwarded) != body { + t.Errorf( + "forwarded body = %q, want %q", + forwarded, + body, + ) } + got := capturer.GetRequest() + if got.Method != http.MethodPost { t.Errorf("expected method POST, got %s", got.Method) } @@ -59,31 +77,336 @@ func TestCaptureRequest(t *testing.T) { ) } - if id := e2enginehttp.TestExecutionID(got.Headers); id == "" { + if id := e2enginehttp.TestExecutionID(got.Headers); id != "execution-1" { t.Errorf( - "expected execution ID header to be present, got %q", + "expected execution ID execution-1, got %q", id, ) } - if string(got.Body) != `{"value":42}` { + if string(got.Body) != body { t.Errorf( - "unexpected body %q", + "unexpected captured body %q", string(got.Body), ) } - // captureRequest must restore the body because the reverse proxy - // still needs to read it. - body, err := io.ReadAll(req.Body) + if got.BodyTruncated { + t.Error("expected body not to be truncated") + } + + if !got.BodyComplete { + t.Error("expected body to be complete") + } +} + +func TestRequestCapturerBodyLimit(t *testing.T) { + const limit int64 = 5 + + tests := []struct { + name string + chunks []string + wantBody string + wantTruncated bool + }{ + { + name: "below limit", + chunks: []string{"abcd"}, + wantBody: "abcd", + }, + { + name: "exactly at limit", + chunks: []string{"abcde"}, + wantBody: "abcde", + }, + { + name: "exceeds in single read", + chunks: []string{"abcdef"}, + wantBody: "abcde", + wantTruncated: true, + }, + { + name: "exceeds across reads", + chunks: []string{"ab", "cdef"}, + wantBody: "abcde", + wantTruncated: true, + }, + { + name: "empty body", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + payload := strings.Join(tt.chunks, "") + + req, err := http.NewRequestWithContext( + t.Context(), + http.MethodPost, + "http://example.com", + strings.NewReader(payload), + ) + if err != nil { + t.Fatalf("cannot create request: %v", err) + } + + capturer := newRequestCapturer(req, limit) + + var forwarded bytes.Buffer + + // Read the request body in the specified chunks. + for _, chunk := range tt.chunks { + p := make([]byte, len(chunk)) + + n, err := io.ReadFull(req.Body, p) + if err != nil { + t.Fatalf("cannot read request body: %v", err) + } + + forwarded.Write(p[:n]) + } + + // Forwarding must preserve the complete body. + if forwarded.String() != payload { + t.Errorf( + "forwarded body = %q, want %q", + forwarded.String(), + payload, + ) + } + + got := capturer.GetRequest() + + if string(got.Body) != tt.wantBody { + t.Errorf( + "captured body = %q, want %q", + string(got.Body), + tt.wantBody, + ) + } + + if got.BodyTruncated != tt.wantTruncated { + t.Errorf( + "BodyTruncated = %t, want %t", + got.BodyTruncated, + tt.wantTruncated, + ) + } + + if !got.BodyComplete { + t.Error("expected fully consumed body to be complete") + } + }) + } +} + +func TestRequestCapturerBodyCompletion(t *testing.T) { + tests := []struct { + name string + body string + contentLength int64 + readBytes int + readEOF bool + wantBody string + wantComplete bool + }{ + { + name: "known content length fully consumed", + body: "abcdef", + contentLength: 6, + readBytes: 6, + wantBody: "abcdef", + wantComplete: true, + }, + { + name: "known content length partially consumed", + body: "abcdef", + contentLength: 6, + readBytes: 3, + wantBody: "abc", + }, + { + name: "unknown content length EOF observed", + body: "abcdef", + contentLength: -1, + readBytes: 6, + readEOF: true, + wantBody: "abcdef", + wantComplete: true, + }, + { + name: "unknown content length EOF not observed", + body: "abcdef", + contentLength: -1, + readBytes: 6, + wantBody: "abcdef", + }, + { + name: "unknown content length partially consumed", + body: "abcdef", + contentLength: -1, + readBytes: 3, + wantBody: "abc", + }, + { + name: "empty body", + contentLength: 0, + wantComplete: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + req, err := http.NewRequestWithContext( + t.Context(), + http.MethodPost, + "http://example.com", + io.NopCloser(strings.NewReader(tt.body)), + ) + if err != nil { + t.Fatal(err) + } + + req.ContentLength = tt.contentLength + + capturer := newRequestCapturer(req, 1024) + + if tt.readBytes > 0 { + buf := make([]byte, tt.readBytes) + + if _, err := io.ReadFull(req.Body, buf); err != nil { + t.Fatalf("ReadFull() error = %v", err) + } + } + + if tt.readEOF { + buf := make([]byte, 1) + + n, err := req.Body.Read(buf) + if n != 0 || err != io.EOF { + t.Fatalf( + "expected EOF, got n=%d, err=%v", + n, + err, + ) + } + } + + got := capturer.GetRequest() + + if string(got.Body) != tt.wantBody { + t.Errorf( + "captured body = %q, want %q", + got.Body, + tt.wantBody, + ) + } + + if got.BodyComplete != tt.wantComplete { + t.Errorf( + "BodyComplete = %t, want %t", + got.BodyComplete, + tt.wantComplete, + ) + } + + if got.BodyTruncated { + t.Error("unexpected body truncation") + } + }) + } +} + +func TestRequestCapturerConcurrentAccess(t *testing.T) { + const body = "abcdefghij" + + req, err := http.NewRequestWithContext( + t.Context(), + http.MethodPost, + "http://example.com", + strings.NewReader(body), + ) if err != nil { - t.Fatalf("ReadAll(request body) error = %v", err) + t.Fatal(err) } - if string(body) != `{"value":42}` { + capturer := newRequestCapturer(req, 5) + + done := make(chan error, 1) + + go func() { + _, err := io.Copy(io.Discard, req.Body) + done <- err + }() + + for i := 0; i < 100; i++ { + got := capturer.GetRequest() + + if len(got.Body) > 5 { + t.Errorf( + "captured body exceeds limit: %d", + len(got.Body), + ) + } + } + + if err := <-done; err != nil { + t.Fatalf("reading request body failed: %v", err) + } + + got := capturer.GetRequest() + + if string(got.Body) != "abcde" { t.Errorf( - "expected restored body, got %q", - string(body), + "captured body = %q, want %q", + got.Body, + "abcde", ) } + + if !got.BodyTruncated { + t.Error("expected body to be truncated") + } + + if !got.BodyComplete { + t.Error("expected body to be complete") + } +} + +func TestRequestCapturerTruncatedAndIncomplete(t *testing.T) { + req, err := http.NewRequestWithContext( + t.Context(), + http.MethodPost, + "http://example.com", + strings.NewReader("abcdefghij"), + ) + if err != nil { + t.Fatal(err) + } + + capturer := newRequestCapturer(req, 3) + + buf := make([]byte, 5) + + if _, err := io.ReadFull(req.Body, buf); err != nil { + t.Fatal(err) + } + + got := capturer.GetRequest() + + if string(got.Body) != "abc" { + t.Errorf( + "captured body = %q, want %q", + got.Body, + "abc", + ) + } + + if !got.BodyTruncated { + t.Error("expected body to be truncated") + } + + if got.BodyComplete { + t.Error("expected body to be incomplete") + } } diff --git a/execute/runtime/router/http/response.go b/execute/runtime/router/http/response.go index a1bec71..16b524f 100644 --- a/execute/runtime/router/http/response.go +++ b/execute/runtime/router/http/response.go @@ -2,21 +2,27 @@ package http import ( "net/http" + "slices" "github.com/e2engine/core/execute/call" - "github.com/e2engine/core/internal/util" ) type ResponseRecorder struct { - w http.ResponseWriter - statusCode int - header http.Header - body []byte + w http.ResponseWriter + statusCode int + header http.Header + body []byte + maxBodySize int64 + bodyTruncated bool } -func newResponseRecorder(w http.ResponseWriter) *ResponseRecorder { +func newResponseRecorder( + w http.ResponseWriter, + maxBodySize int64, +) *ResponseRecorder { return &ResponseRecorder{ - w: w, + w: w, + maxBodySize: maxBodySize, } } @@ -30,7 +36,7 @@ func (r *ResponseRecorder) WriteHeader(statusCode int) { } r.statusCode = statusCode - r.header = util.CloneHTTPHeader(r.w.Header()) + r.header = r.w.Header().Clone() r.w.WriteHeader(statusCode) } @@ -43,7 +49,18 @@ func (r *ResponseRecorder) Write(p []byte) (int, error) { n, err := r.w.Write(p) if n > 0 { - r.body = append(r.body, p[:n]...) + remaining := r.maxBodySize - int64(len(r.body)) + + if remaining > 0 { + captureSize := min(n, int(remaining)) + r.body = append(r.body, p[:captureSize]...) + + if captureSize < n { + r.bodyTruncated = true + } + } else { + r.bodyTruncated = true + } } return n, err @@ -59,9 +76,10 @@ func (r *ResponseRecorder) GetResponse() call.HTTPResponse { } return call.HTTPResponse{ - StatusCode: statusCode, - Headers: util.CloneHTTPHeader(headers), - Body: util.CloneBytes(r.body), + StatusCode: statusCode, + Headers: headers.Clone(), + Body: slices.Clone(r.body), + BodyTruncated: r.bodyTruncated, } } @@ -75,4 +93,7 @@ func (r *ResponseRecorder) Flush() { } } -// TODO: preserve http.Hijacker in ResponseRecorder. +// TODO: support HTTP connection upgrades (http.Hijacker). +// Hijacked connections require explicit lifecycle management because +// http.Server.Shutdown and Close do not terminate them. +// They also bypass the current request/response recording limits. diff --git a/execute/runtime/router/http/response_test.go b/execute/runtime/router/http/response_test.go index 96be0a8..eeb7f17 100644 --- a/execute/runtime/router/http/response_test.go +++ b/execute/runtime/router/http/response_test.go @@ -3,12 +3,13 @@ package http import ( "net/http" "net/http/httptest" + "strings" "testing" ) func TestResponseRecorder(t *testing.T) { w := httptest.NewRecorder() - recorder := newResponseRecorder(w) + recorder := newResponseRecorder(w, 1024) recorder.Header().Set("X-Test", "value") recorder.WriteHeader(http.StatusCreated) if _, err := recorder.Write([]byte("response")); err != nil { @@ -38,7 +39,7 @@ func TestResponseRecorder(t *testing.T) { func TestResponseRecorderImplicitOK(t *testing.T) { w := httptest.NewRecorder() - recorder := newResponseRecorder(w) + recorder := newResponseRecorder(w, 1024) if _, err := recorder.Write([]byte("response")); err != nil { t.Fatalf("Write() error = %v", err) } @@ -60,7 +61,7 @@ func TestResponseRecorderImplicitOK(t *testing.T) { func TestResponseRecorderEmptyResponse(t *testing.T) { w := httptest.NewRecorder() - recorder := newResponseRecorder(w) + recorder := newResponseRecorder(w, 1024) recorder.Header().Set("X-Test", "value") got := recorder.GetResponse() if got.StatusCode != http.StatusOK { @@ -86,7 +87,7 @@ func TestResponseRecorderEmptyResponse(t *testing.T) { func TestResponseRecorderFirstWriteHeaderWins(t *testing.T) { w := httptest.NewRecorder() - recorder := newResponseRecorder(w) + recorder := newResponseRecorder(w, 1024) recorder.WriteHeader(http.StatusCreated) recorder.WriteHeader(http.StatusInternalServerError) got := recorder.GetResponse() @@ -101,7 +102,7 @@ func TestResponseRecorderFirstWriteHeaderWins(t *testing.T) { func TestResponseRecorderFlush(t *testing.T) { w := httptest.NewRecorder() - recorder := newResponseRecorder(w) + recorder := newResponseRecorder(w, 1024) recorder.Flush() got := recorder.GetResponse() if got.StatusCode != http.StatusOK { @@ -115,3 +116,74 @@ func TestResponseRecorderFlush(t *testing.T) { t.Fatal("expected underlying writer to be flushed") } } + +func TestResponseRecorderBodySizeLimit(t *testing.T) { + tests := []struct { + name string + writes []string + wantBody string + wantTruncated bool + }{ + { + name: "below limit", + writes: []string{"abcd"}, + wantBody: "abcd", + }, + { + name: "exactly at limit", + writes: []string{"abcde"}, + wantBody: "abcde", + }, + { + name: "exceeds in one write", + writes: []string{"abcdef"}, + wantBody: "abcde", + wantTruncated: true, + }, + { + name: "exceeds across writes", + writes: []string{"ab", "cdef"}, + wantBody: "abcde", + wantTruncated: true, + }, + { + name: "empty", + wantBody: "", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + w := httptest.NewRecorder() + r := newResponseRecorder(w, 5) + + for _, part := range tt.writes { + if _, err := r.Write([]byte(part)); err != nil { + t.Fatal(err) + } + } + + got := r.GetResponse() + + if string(got.Body) != tt.wantBody || + got.BodyTruncated != tt.wantTruncated { + t.Errorf( + "recorded body = %q truncated = %t; want %q truncated = %t", + got.Body, + got.BodyTruncated, + tt.wantBody, + tt.wantTruncated, + ) + } + + // The original response must be forwarded completely. + if want := strings.Join(tt.writes, ""); w.Body.String() != want { + t.Errorf( + "forwarded body = %q, want %q", + w.Body.String(), + want, + ) + } + }) + } +} diff --git a/execute/runtime/router/http/router.go b/execute/runtime/router/http/router.go index 4085505..24441a0 100644 --- a/execute/runtime/router/http/router.go +++ b/execute/runtime/router/http/router.go @@ -9,16 +9,16 @@ import ( "net/url" e2enginehttp "github.com/e2engine/instrumentation-go/http" - "github.com/ygrebnov/errorc" "github.com/e2engine/core/execute/call" "github.com/e2engine/core/execute/runtime" - "github.com/e2engine/core/pkg/errors" + "github.com/e2engine/core/execute/runtime/config" "github.com/e2engine/core/pkg/keys" "github.com/e2engine/core/pkg/log" ) type Router struct { + cfg *config.HTTPRouterConfig logger log.Logger calls call.Recorder @@ -27,10 +27,12 @@ type Router struct { } func NewRouter( + cfg *config.HTTPRouterConfig, logger log.Logger, calls call.Recorder, ) *Router { return &Router{ + cfg: cfg, logger: logger, services: make(map[string]*runtime.Route), calls: calls, @@ -48,9 +50,10 @@ func (r *Router) Register(route *runtime.Route) { } type mountedRoute struct { - route *runtime.Route - listener net.Listener - server *http.Server + route *runtime.Route + listener net.Listener + server *http.Server + transport *http.Transport } func (r *Router) Mount(ctx context.Context) error { @@ -71,17 +74,24 @@ func (r *Router) Mount(ctx context.Context) error { proxy := httputil.NewSingleHostReverseProxy(target) + // Clone the default transport to preserve connection pooling, + // dial timeouts, keep-alive settings, and other defaults. + transport := http.DefaultTransport.(*http.Transport).Clone() + + transport.ResponseHeaderTimeout = r.cfg.ResponseHeaderTimeout + transport.MaxResponseHeaderBytes = r.cfg.MaxResponseHeaderBytes + + proxy.Transport = transport + proxy.ErrorHandler = func( w http.ResponseWriter, req *http.Request, - proxyErr error, + _ error, ) { r.logger.Error( "Failed to proxy environment request", log.String(keys.EnvironmentServiceID, route.ServiceID), log.String(keys.RequestMethod, req.Method), - log.String(keys.RequestURLPath, req.URL.Path), - log.Err(keys.Cause, proxyErr), ) http.Error( @@ -99,48 +109,28 @@ func (r *Router) Mount(ctx context.Context) error { "Routing environment request", log.String(keys.EnvironmentServiceID, route.ServiceID), log.String(keys.RequestMethod, req.Method), - log.String(keys.RequestURLPath, req.URL.Path), ) - request, errCapture := captureRequest(req) - if errCapture != nil { - captureErr := errorc.With( - errors.ErrFailedToCaptureEnvironmentServiceCall, - errorc.String(keys.EnvironmentServiceID, route.ServiceID), - errorc.String(keys.RequestMethod, req.Method), - errorc.String(keys.RequestURLPath, req.URL.Path), - errorc.Error(keys.Cause, errCapture), - ) - - r.logger.Error( - errors.ErrFailedToCaptureEnvironmentServiceCall.Error(), - log.String(keys.EnvironmentServiceID, route.ServiceID), - log.String(keys.RequestMethod, req.Method), - log.String(keys.RequestURLPath, req.URL.Path), - log.Err(keys.Cause, captureErr), - ) - - http.Error( - w, - http.StatusText(http.StatusInternalServerError), - http.StatusInternalServerError, - ) - - return - } - - responseRecorder := newResponseRecorder(w) + request := newRequestCapturer(req, r.cfg.MaxRecordedBodySize) + response := newResponseRecorder(w, r.cfg.MaxRecordedBodySize) - proxy.ServeHTTP(responseRecorder, req) + proxy.ServeHTTP(response, req) - r.calls.Record(call.Call{ + if errRecord := r.calls.Record(call.Call{ TestExecutionID: e2enginehttp.TestExecutionID(req.Header), ServiceID: route.ServiceID, HTTP: &call.HTTPCall{ - Request: request, - Response: responseRecorder.GetResponse(), + Request: request.GetRequest(), + Response: response.GetResponse(), }, - }) + }); errRecord != nil { + r.logger.Error( + "Failed to record environment HTTP call", + log.String(keys.EnvironmentServiceID, route.ServiceID), + log.String(keys.RequestMethod, req.Method), + log.Err(keys.Cause, errRecord), + ) + } }) listenerConfig := net.ListenConfig{} @@ -150,6 +140,8 @@ func (r *Router) Mount(ctx context.Context) error { route.ListenAddress, ) if err != nil { + transport.CloseIdleConnections() + return nativeerrors.Join( err, r.unmountMountedRoutes(ctx, mounted), @@ -157,22 +149,27 @@ func (r *Router) Mount(ctx context.Context) error { } server := &http.Server{ - Handler: handler, + Handler: handler, + ReadHeaderTimeout: r.cfg.ReadHeaderTimeout, + IdleTimeout: r.cfg.IdleTimeout, + MaxHeaderBytes: 1 << 20, // Go's existing default (1MiB) } mounted = append( mounted, mountedRoute{ - route: route, - listener: listener, - server: server, + route: route, + listener: listener, + server: server, + transport: transport, }, ) go func() { err := server.Serve(listener) if err != nil && - !nativeerrors.Is(err, http.ErrServerClosed) { + !nativeerrors.Is(err, http.ErrServerClosed) && + !nativeerrors.Is(err, net.ErrClosed) { r.logger.Error( "Environment router listener stopped unexpectedly", log.String( @@ -197,13 +194,12 @@ func (r *Router) Mount(ctx context.Context) error { } func (r *Router) Unmount(ctx context.Context) error { - if err := ctx.Err(); err != nil { - return err - } - err := r.unmountMountedRoutes(ctx, r.mounted) r.mounted = nil + // TODO: if additional shutdown resources are introduced, we should revisit + // whether failed cleanup should allow retries + return err } @@ -219,13 +215,34 @@ func (r *Router) unmountMountedRoutes( if err := route.server.Shutdown(ctx); err != nil { r.logger.Error( "Failed to unmount router route", - log.String(keys.EnvironmentServiceID, route.route.ServiceID), - log.String(keys.EnvironmentServiceListenAddress, route.route.ListenAddress), + log.String( + keys.EnvironmentServiceID, + route.route.ServiceID, + ), + log.String( + keys.EnvironmentServiceListenAddress, + route.route.ListenAddress, + ), log.Err(keys.Cause, err), ) accErr = nativeerrors.Join(accErr, err) + + // Force-close active connections when graceful + // shutdown cannot complete. + if closeErr := route.server.Close(); closeErr != nil { + accErr = nativeerrors.Join(accErr, closeErr) + } } + + // Ensure the listener is closed even if Shutdown() + // runs before Serve() registers it. + if err := route.listener.Close(); err != nil && + !nativeerrors.Is(err, net.ErrClosed) { + accErr = nativeerrors.Join(accErr, err) + } + + route.transport.CloseIdleConnections() } return accErr diff --git a/execute/runtime/router/http/router_test.go b/execute/runtime/router/http/router_test.go index aaa7893..b39564e 100644 --- a/execute/runtime/router/http/router_test.go +++ b/execute/runtime/router/http/router_test.go @@ -9,11 +9,13 @@ import ( "net/http/httptest" "strings" "testing" + "time" e2enginehttp "github.com/e2engine/instrumentation-go/http" "github.com/e2engine/core/execute/call" "github.com/e2engine/core/execute/runtime" + "github.com/e2engine/core/execute/runtime/config" "github.com/e2engine/core/pkg/log" ) @@ -45,7 +47,11 @@ func TestRouter(t *testing.T) { ) defer upstream.Close() - store := &call.Store{} + store := call.NewStoreFactory( + &call.Config{ + MaxCalls: 1000, + MaxRecordedBytes: 1024 * 1024, + }).New() router := newTestHTTPRouter(t, store) router.Register(&runtime.Route{ @@ -201,6 +207,10 @@ func TestRouter(t *testing.T) { ) } + if got.HTTP.Request.BodyTruncated { + t.Error("expected recorded request body not to be truncated") + } + if got.HTTP.Response.StatusCode != http.StatusCreated { t.Errorf( "expected recorded status %d, got %d", @@ -222,10 +232,18 @@ func TestRouter(t *testing.T) { string(got.HTTP.Response.Body), ) } + + if got.HTTP.Response.BodyTruncated { + t.Error("expected recorded response body not to be truncated") + } } func TestRouterProxyError(t *testing.T) { - store := &call.Store{} + store := call.NewStoreFactory( + &call.Config{ + MaxCalls: 1000, + MaxRecordedBytes: 1024 * 1024, + }).New() router := newTestHTTPRouter(t, store) // Obtain an address that currently has no listener. @@ -314,7 +332,11 @@ func TestRouterProxyError(t *testing.T) { } func TestRouterMountCancelledContext(t *testing.T) { - router := newTestHTTPRouter(t, &call.Store{}) + router := newTestHTTPRouter(t, call.NewStoreFactory( + &call.Config{ + MaxCalls: 1000, + MaxRecordedBytes: 1024 * 1024, + }).New()) ctx, cancel := context.WithCancel(context.Background()) cancel() @@ -330,23 +352,57 @@ func TestRouterMountCancelledContext(t *testing.T) { } func TestRouterUnmountCancelledContext(t *testing.T) { - router := newTestHTTPRouter(t, &call.Store{}) + store := call.NewStoreFactory(&call.Config{ + MaxCalls: 10, + MaxRecordedBytes: 1 << 20, + }).New() + + router := newTestHTTPRouter(t, store) + + router.Register(&runtime.Route{ + ServiceID: "service-1", + ListenAddress: "127.0.0.1:0", + RuntimeAddress: "127.0.0.1:1", + }) + + if err := router.Mount(t.Context()); err != nil { + t.Fatalf("Mount() error = %v", err) + } + + address := router.mounted[0].listener.Addr().String() ctx, cancel := context.WithCancel(context.Background()) cancel() err := router.Unmount(ctx) - if !errors.Is(err, context.Canceled) { + if err != nil && !errors.Is(err, context.Canceled) { t.Fatalf( - "expected context.Canceled, got %v", + "Unmount() unexpected error = %v", err, ) } + + if router.mounted != nil { + t.Fatal("expected mounted routes to be cleared") + } + + conn, err := net.DialTimeout("tcp", address, time.Second) + if err == nil { + _ = conn.Close() + t.Fatal("listener still accepts connections after unmount") + } } func TestRouterMultipleRoutes(t *testing.T) { - router := newTestHTTPRouter(t, &call.Store{}) + router := newTestHTTPRouter( + t, + call.NewStoreFactory( + &call.Config{ + MaxCalls: 1000, + MaxRecordedBytes: 1024 * 1024, + }).New(), + ) router.Register(&runtime.Route{ ServiceID: "service-1", @@ -380,6 +436,553 @@ func TestRouterMultipleRoutes(t *testing.T) { } } +func TestRouterTruncatedBodyRecording(t *testing.T) { + const ( + requestBody = "123456789" + responseBody = "abcdefghi" + ) + + upstream := httptest.NewServer(http.HandlerFunc( + func(w http.ResponseWriter, req *http.Request) { + body, err := io.ReadAll(req.Body) + if err != nil { + t.Errorf("ReadAll(upstream request) error = %v", err) + return + } + + if string(body) != requestBody { + t.Errorf( + "upstream request body = %q, want %q", + body, + requestBody, + ) + } + + if _, err := io.WriteString(w, responseBody); err != nil { + t.Errorf("Write(upstream response) error = %v", err) + } + }, + )) + defer upstream.Close() + + store := call.NewStoreFactory( + &call.Config{ + MaxCalls: 1000, + MaxRecordedBytes: 1024 * 1024, + }).New() + router := newTestHTTPRouter(t, store) + router.cfg.MaxRecordedBodySize = 5 + + router.Register(&runtime.Route{ + ServiceID: "service-1", + ListenAddress: "127.0.0.1:0", + RuntimeAddress: upstream.Listener.Addr().String(), + }) + + if err := router.Mount(t.Context()); err != nil { + t.Fatalf("Mount() error = %v", err) + } + + defer func() { + if err := router.Unmount(context.Background()); err != nil { + t.Errorf("Unmount() error = %v", err) + } + }() + + address := router.mounted[0].listener.Addr().String() + + req, err := http.NewRequestWithContext( + t.Context(), + http.MethodPost, + "http://"+address+"/test", + strings.NewReader(requestBody), + ) + if err != nil { + t.Fatal(err) + } + + req.Header = e2enginehttp.WithTestExecutionID( + req.Header, + "execution-1", + ) + + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatal(err) + } + + // Verify that the complete response was forwarded. + if string(body) != responseBody { + t.Errorf( + "forwarded response body = %q, want %q", + body, + responseBody, + ) + } + + calls := store.Get(call.Filter{ + TestExecutionID: "execution-1", + ServiceID: "service-1", + }) + + if len(calls) != 1 { + t.Fatalf( + "recorded calls = %d, want 1", + len(calls), + ) + } + + if calls[0].HTTP == nil { + t.Fatal("expected recorded HTTP call") + } + + got := calls[0].HTTP + + // Only the first five request bytes should be recorded. + if string(got.Request.Body) != requestBody[:5] { + t.Errorf( + "recorded request body = %q, want %q", + got.Request.Body, + requestBody[:5], + ) + } + + if !got.Request.BodyTruncated { + t.Error("expected recorded request body to be truncated") + } + + // Only the first five response bytes should be recorded. + if string(got.Response.Body) != responseBody[:5] { + t.Errorf( + "recorded response body = %q, want %q", + got.Response.Body, + responseBody[:5], + ) + } + + if !got.Response.BodyTruncated { + t.Error("expected recorded response body to be truncated") + } +} + +func TestRouterResponseHeaderTimeout(t *testing.T) { + upstreamEntered := make(chan struct{}) + + upstream := httptest.NewServer( + http.HandlerFunc(func( + w http.ResponseWriter, + req *http.Request, + ) { + close(upstreamEntered) + + // Wait until the reverse proxy cancels the request + // because of the response-header timeout. + <-req.Context().Done() + }), + ) + defer upstream.Close() + + store := call.NewStoreFactory( + &call.Config{ + MaxCalls: 10, + MaxRecordedBytes: 1 << 20, + }, + ).New() + + router := newTestHTTPRouter(t, store) + router.cfg.ResponseHeaderTimeout = 50 * time.Millisecond + + router.Register(&runtime.Route{ + ServiceID: "service-1", + ListenAddress: "127.0.0.1:0", + RuntimeAddress: upstream.Listener.Addr().String(), + }) + + if err := router.Mount(t.Context()); err != nil { + t.Fatalf("Mount() error = %v", err) + } + + defer func() { + if err := router.Unmount(context.Background()); err != nil { + t.Errorf("Unmount() error = %v", err) + } + }() + + address := router.mounted[0].listener.Addr().String() + + req, err := http.NewRequestWithContext( + t.Context(), + http.MethodGet, + "http://"+address+"/timeout", + nil, + ) + if err != nil { + t.Fatal(err) + } + + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("Do() error = %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusBadGateway { + t.Errorf( + "status = %d, want %d", + resp.StatusCode, + http.StatusBadGateway, + ) + } + + select { + case <-upstreamEntered: + default: + t.Error("upstream handler was not entered") + } +} + +func TestRouterResponseHeaderTimeoutDoesNotLimitBody(t *testing.T) { + const delay = 150 * time.Millisecond + + upstream := httptest.NewServer( + http.HandlerFunc(func( + w http.ResponseWriter, + _ *http.Request, + ) { + w.WriteHeader(http.StatusOK) + + // Flush headers immediately so that the timeout + // applies only to receiving the initial headers. + w.(http.Flusher).Flush() + + time.Sleep(delay) + + if _, err := io.WriteString(w, "late body"); err != nil { + t.Errorf("Write() error = %v", err) + } + }), + ) + defer upstream.Close() + + store := call.NewStoreFactory( + &call.Config{ + MaxCalls: 10, + MaxRecordedBytes: 1 << 20, + }, + ).New() + + router := newTestHTTPRouter(t, store) + router.cfg.ResponseHeaderTimeout = 50 * time.Millisecond + + router.Register(&runtime.Route{ + ServiceID: "service-1", + ListenAddress: "127.0.0.1:0", + RuntimeAddress: upstream.Listener.Addr().String(), + }) + + if err := router.Mount(t.Context()); err != nil { + t.Fatalf("Mount() error = %v", err) + } + + defer func() { + if err := router.Unmount(context.Background()); err != nil { + t.Errorf("Unmount() error = %v", err) + } + }() + + address := router.mounted[0].listener.Addr().String() + + req, err := http.NewRequestWithContext( + t.Context(), + http.MethodGet, + "http://"+address+"/slow-body", + nil, + ) + if err != nil { + t.Fatal(err) + } + + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("Do() error = %v", err) + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatalf("ReadAll() error = %v", err) + } + + if resp.StatusCode != http.StatusOK { + t.Errorf( + "status = %d, want %d", + resp.StatusCode, + http.StatusOK, + ) + } + + if string(body) != "late body" { + t.Errorf( + "body = %q, want %q", + body, + "late body", + ) + } + + calls := store.Get(call.Filter{ + ServiceID: "service-1", + }) + + if len(calls) != 1 { + t.Fatalf( + "recorded calls = %d, want 1", + len(calls), + ) + } + + if calls[0].HTTP == nil { + t.Fatal("expected recorded HTTP call") + } + + recorded := calls[0].HTTP.Response + + if recorded.StatusCode != http.StatusOK { + t.Errorf( + "recorded status = %d, want %d", + recorded.StatusCode, + http.StatusOK, + ) + } + + if string(recorded.Body) != "late body" { + t.Errorf( + "recorded response body = %q, want %q", + recorded.Body, + "late body", + ) + } + + if recorded.BodyTruncated { + t.Error("recorded response body must not be truncated") + } + + if err := store.Err(); err != nil { + t.Errorf( + "call store error = %v, want nil", + err, + ) + } +} + +func TestRouterMaxResponseHeaderBytes(t *testing.T) { + upstream := httptest.NewServer( + http.HandlerFunc(func( + w http.ResponseWriter, + _ *http.Request, + ) { + w.Header().Set( + "X-Large-Header", + strings.Repeat("a", 4096), + ) + w.WriteHeader(http.StatusOK) + }), + ) + defer upstream.Close() + + store := call.NewStoreFactory(&call.Config{ + MaxCalls: 10, + MaxRecordedBytes: 1 << 20, + }).New() + + router := newTestHTTPRouter(t, store) + router.cfg.MaxResponseHeaderBytes = 1024 + + router.Register(&runtime.Route{ + ServiceID: "service-1", + ListenAddress: "127.0.0.1:0", + RuntimeAddress: upstream.Listener.Addr().String(), + }) + + if err := router.Mount(t.Context()); err != nil { + t.Fatalf("Mount() error = %v", err) + } + + defer func() { + if err := router.Unmount(context.Background()); err != nil { + t.Errorf("Unmount() error = %v", err) + } + }() + + req, err := http.NewRequestWithContext( + t.Context(), + http.MethodGet, + "http://"+router.mounted[0].listener.Addr().String()+"/large-header", + nil, + ) + if err != nil { + t.Fatal(err) + } + + req.Header = e2enginehttp.WithTestExecutionID( + req.Header, + "execution-1", + ) + + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("Do() error = %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusBadGateway { + t.Errorf( + "status = %d, want %d", + resp.StatusCode, + http.StatusBadGateway, + ) + } + + calls := store.Get(call.Filter{ + TestExecutionID: "execution-1", + ServiceID: "service-1", + }) + + if len(calls) != 1 { + t.Fatalf("recorded calls = %d, want 1", len(calls)) + } + + if calls[0].HTTP == nil { + t.Fatal("expected recorded HTTP call") + } + + if got := calls[0].HTTP.Response.StatusCode; got != http.StatusBadGateway { + t.Errorf( + "recorded status = %d, want %d", + got, + http.StatusBadGateway, + ) + } + + if err := store.Err(); err != nil { + t.Errorf("store.Err() = %v, want nil", err) + } +} + +func TestRouterUnmountClosesActiveRequest(t *testing.T) { + upstreamEntered := make(chan struct{}) + upstreamCanceled := make(chan struct{}) + + upstream := httptest.NewServer( + http.HandlerFunc(func( + w http.ResponseWriter, + req *http.Request, + ) { + close(upstreamEntered) + + <-req.Context().Done() + + close(upstreamCanceled) + }), + ) + defer upstream.Close() + + store := call.NewStoreFactory(&call.Config{ + MaxCalls: 10, + MaxRecordedBytes: 1 << 20, + }).New() + + router := newTestHTTPRouter(t, store) + + router.Register(&runtime.Route{ + ServiceID: "service-1", + ListenAddress: "127.0.0.1:0", + RuntimeAddress: upstream.Listener.Addr().String(), + }) + + if err := router.Mount(t.Context()); err != nil { + t.Fatalf("Mount() error = %v", err) + } + + address := router.mounted[0].listener.Addr().String() + + client := &http.Client{ + Timeout: 5 * time.Second, + } + + requestDone := make(chan error, 1) + + go func() { + req, err := http.NewRequestWithContext( + t.Context(), + http.MethodGet, + "http://"+address+"/blocked", + nil, + ) + if err != nil { + requestDone <- err + return + } + + resp, err := client.Do(req) + if err == nil { + _ = resp.Body.Close() + requestDone <- errors.New( + "request unexpectedly succeeded", + ) + return + } + + requestDone <- err + }() + + select { + case <-upstreamEntered: + case <-time.After(5 * time.Second): + t.Fatal("request did not reach upstream") + } + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + if err := router.Unmount(ctx); !errors.Is(err, context.Canceled) { + t.Errorf( + "Unmount() error = %v, want context.Canceled", + err, + ) + } + + if router.mounted != nil { + t.Error("mounted routes not cleared") + } + + if conn, err := net.DialTimeout( + "tcp", + address, + time.Second, + ); err == nil { + _ = conn.Close() + t.Error("listener still accepts connections") + } + + select { + case <-requestDone: + case <-time.After(5 * time.Second): + t.Error("active client request did not terminate") + } + + select { + case <-upstreamCanceled: + case <-time.After(5 * time.Second): + t.Error("upstream request context was not canceled") + } +} + func newTestHTTPRouter( t *testing.T, store *call.Store, @@ -394,5 +997,13 @@ func newTestHTTPRouter( ) } - return NewRouter(logger, store) + routerCfg := &config.HTTPRouterConfig{ + MaxRecordedBodySize: 1024, + ReadHeaderTimeout: 5 * time.Second, + IdleTimeout: 60 * time.Second, + ResponseHeaderTimeout: 30 * time.Second, + MaxResponseHeaderBytes: 1 << 20, + } + + return NewRouter(routerCfg, logger, store) } diff --git a/execute/runtime/router/router.go b/execute/runtime/router/router.go index e5c6263..4f6372a 100644 --- a/execute/runtime/router/router.go +++ b/execute/runtime/router/router.go @@ -6,6 +6,7 @@ import ( "github.com/e2engine/core/execute/call" "github.com/e2engine/core/execute/runtime" + "github.com/e2engine/core/execute/runtime/config" grpcrouter "github.com/e2engine/core/execute/runtime/router/grpc" httprouter "github.com/e2engine/core/execute/runtime/router/http" "github.com/e2engine/core/model" @@ -48,19 +49,25 @@ func (r *Router) Register(route *runtime.Route) { } } -type Provider struct{} +type Provider struct { + cfg *config.RouterConfig +} -func NewProvider() *Provider { - return &Provider{} +func NewProvider(cfg *config.RouterConfig) *Provider { + return &Provider{ + cfg: cfg, + } } func (p *Provider) Get(logger log.Logger, calls call.Recorder) runtime.Router { return &Router{ http: httprouter.NewRouter( + p.cfg.HTTP, logger.With(log.String(keys.Component, "environment_http_router")), calls, ), grpc: grpcrouter.NewRouter( + p.cfg.GRPC, logger.With(log.String(keys.Component, "environment_grpc_router")), calls, ), diff --git a/execute/runtime/router/router_test.go b/execute/runtime/router/router_test.go index 05bbac5..31e3083 100644 --- a/execute/runtime/router/router_test.go +++ b/execute/runtime/router/router_test.go @@ -7,6 +7,7 @@ import ( "github.com/e2engine/core/execute/call" "github.com/e2engine/core/execute/runtime" + "github.com/e2engine/core/execute/runtime/config" "github.com/e2engine/core/model" "github.com/e2engine/core/pkg/log" ) @@ -44,17 +45,42 @@ func TestRouterMountCancelledContext(t *testing.T) { func TestRouterUnmountCancelledContext(t *testing.T) { r := newTestRouter(t) + r.Register(&runtime.Route{ + ServiceID: "http-service", + Kind: model.ServiceKindHTTP, + ListenAddress: "127.0.0.1:0", + RuntimeAddress: "127.0.0.1:10001", + }) + + r.Register(&runtime.Route{ + ServiceID: "grpc-service", + Kind: model.ServiceKindGRPC, + ListenAddress: "127.0.0.1:0", + RuntimeAddress: "127.0.0.1:10002", + }) + + if err := r.Mount(context.Background()); err != nil { + t.Fatalf("Mount() error = %v", err) + } + ctx, cancel := context.WithCancel(context.Background()) cancel() - err := r.Unmount(ctx) + if err := r.Unmount(ctx); err != nil && + !errors.Is(err, context.Canceled) { + t.Fatalf("Unmount() unexpected error = %v", err) + } - if !errors.Is(err, context.Canceled) { + if err := r.Mount(context.Background()); err != nil { t.Fatalf( - "expected context.Canceled, got %v", + "Mount() after canceled Unmount() error = %v", err, ) } + + if err := r.Unmount(context.Background()); err != nil { + t.Fatalf("final Unmount() error = %v", err) + } } func TestRouterRegisterHTTP(t *testing.T) { @@ -132,8 +158,22 @@ func newTestRouter(t *testing.T) runtime.Router { ) } - return NewProvider().Get( + cfg := &config.RouterConfig{ + HTTP: &config.HTTPRouterConfig{ + MaxRecordedBodySize: 1024, + }, + GRPC: &config.GRPCRouterConfig{ + MaxMessageSize: 1024, + }, + } + + return NewProvider(cfg).Get( logger, - call.NewStoreFactory().New(), + call.NewStoreFactory( + &call.Config{ + MaxCalls: 1000, + MaxRecordedBytes: 1024 * 1024, + }, + ).New(), ) } diff --git a/execute/runtime/service/address_resolver.go b/execute/runtime/service/address_resolver.go new file mode 100644 index 0000000..0f51062 --- /dev/null +++ b/execute/runtime/service/address_resolver.go @@ -0,0 +1,8 @@ +package service + +type addressResolver interface { + ResolveHTTPURL(value string) (string, error) + ResolveGRPCTarget(value string) (string, error) +} + +//go:generate go run -mod=mod go.uber.org/mock/mockgen -source=address_resolver.go -destination=mock_address_resolver_test.go -package=service diff --git a/execute/runtime/service/grpc/address_resolver.go b/execute/runtime/service/grpc/address_resolver.go new file mode 100644 index 0000000..d0d0c1c --- /dev/null +++ b/execute/runtime/service/grpc/address_resolver.go @@ -0,0 +1,7 @@ +package grpc + +type addressResolver interface { + ResolveGRPCTarget(value string) (string, error) +} + +//go:generate go run -mod=mod go.uber.org/mock/mockgen -source=address_resolver.go -destination=mock_address_resolver_test.go -package=grpc diff --git a/execute/runtime/service/grpc/config.go b/execute/runtime/service/grpc/config.go new file mode 100644 index 0000000..87058c2 --- /dev/null +++ b/execute/runtime/service/grpc/config.go @@ -0,0 +1,13 @@ +package grpc + +type MockGRPCServiceConfig struct { + MaxMessageSize int `json:"max_message_size" yaml:"max_message_size" env:"MAX_MESSAGE_SIZE" default:"4194304" validate:"min(1),max(67108864)"` + + MaxMetadataSize uint32 `json:"max_metadata_size" yaml:"max_metadata_size" env:"MAX_METADATA_SIZE" default:"65536" validate:"min(1024),max(1048576)"` +} + +type RealGRPCServiceConfig struct { + MaxMessageSize int `json:"max_message_size" yaml:"max_message_size" env:"MAX_MESSAGE_SIZE" default:"4194304" validate:"min(1),max(67108864)"` + + MaxMetadataSize uint32 `json:"max_metadata_size" yaml:"max_metadata_size" env:"MAX_METADATA_SIZE" default:"65536" validate:"min(1024),max(1048576)"` +} diff --git a/execute/runtime/service/grpc/methodresolver.go b/execute/runtime/service/grpc/methodresolver.go index 0d72268..ce40055 100644 --- a/execute/runtime/service/grpc/methodresolver.go +++ b/execute/runtime/service/grpc/methodresolver.go @@ -1,10 +1,13 @@ package grpc import ( + "bytes" "context" "crypto/sha256" "encoding/hex" "hash" + "io" + "path/filepath" "sync" "github.com/bufbuild/protocompile" @@ -53,6 +56,7 @@ func (r *ProtoMethodResolver) ResolveMethod( spec *model.GRPCProtoSpec, method string, ) (protoreflect.MethodDescriptor, error) { + // TODO: verify that context cancellation is respected. switch { case spec.External != nil: return r.resolveExternal( @@ -122,29 +126,50 @@ func (r *ProtoMethodResolver) loadFile( ctx context.Context, path string, ) (*protoregistry.Files, error) { - if err := util.ValidateFilePath(path); err != nil { - return nil, err + absolutePath, err := filepath.Abs(path) + if err != nil { + return nil, errorc.With( + errors.ErrCannotLoadGRPCProto, + errorc.String(keys.FilePath, path), + errorc.Error(keys.Cause, err), + ) + } + + if errValidate := util.ValidateFilePath(absolutePath); errValidate != nil { + return nil, errorc.With( + errors.ErrInaccessiblePath, + errorc.String(keys.FilePath, path), + ) } r.mu.RLock() - files := r.files[path] + files := r.files[absolutePath] r.mu.RUnlock() if files != nil { return files, nil } - // TODO: use a controlled resolver that opens and validates protobuf files - // through the shared file-loading abstraction, including imported files. + root := filepath.Dir(absolutePath) + compiler := protocompile.Compiler{ Resolver: protocompile.WithStandardImports( - &protocompile.SourceResolver{}, + &protocompile.SourceResolver{ + Accessor: func(name string) (io.ReadCloser, error) { + data, errRead := util.ReadFileWithinRoot(root, name) + if errRead != nil { + return nil, errRead + } + + return io.NopCloser(bytes.NewReader(data)), nil + }, + }, ), } compiled, err := compiler.Compile( ctx, - path, + filepath.Base(absolutePath), ) if err != nil { return nil, errorc.With( @@ -162,10 +187,7 @@ func (r *ProtoMethodResolver) loadFile( return nil, errorc.With( errors.ErrCannotLoadGRPCProto, errorc.String(keys.FilePath, path), - errorc.String( - keys.Operation, - "register protobuf file", - ), + errorc.String(keys.Operation, "register protobuf file"), errorc.Error(keys.Cause, err), ) } @@ -173,10 +195,10 @@ func (r *ProtoMethodResolver) loadFile( r.mu.Lock() - if existing := r.files[path]; existing != nil { + if existing := r.files[absolutePath]; existing != nil { files = existing } else { - r.files[path] = files + r.files[absolutePath] = files } r.mu.Unlock() diff --git a/execute/runtime/service/grpc/methodresolver_test.go b/execute/runtime/service/grpc/methodresolver_test.go index 2aaa671..53c465b 100644 --- a/execute/runtime/service/grpc/methodresolver_test.go +++ b/execute/runtime/service/grpc/methodresolver_test.go @@ -13,6 +13,7 @@ import ( "github.com/e2engine/core/model" "github.com/e2engine/core/pkg/errors" + "github.com/e2engine/core/util" ) func TestProtoMethodResolverResolveExternalModule(t *testing.T) { @@ -752,6 +753,300 @@ func TestInternalContractKey(t *testing.T) { } } +func TestProtoMethodResolverResolveExternalFileImports(t *testing.T) { + tests := []struct { + name string + proto string + imports map[string]string + }{ + { + name: "nested import", + proto: ` +syntax = "proto3"; +package users.v1; + +import "common/types.proto"; + +service UserService { + rpc GetUser(GetUserRequest) returns (GetUserResponse); +} +`, + imports: map[string]string{ + "common/types.proto": ` +syntax = "proto3"; +package users.v1; + +message GetUserRequest { + string id = 1; +} + +message GetUserResponse { + string name = 1; +} +`, + }, + }, + { + name: "standard protobuf import", + proto: ` +syntax = "proto3"; +package users.v1; + +import "google/protobuf/timestamp.proto"; + +service UserService { + rpc GetUser(GetUserRequest) returns (GetUserResponse); +} + +message GetUserRequest { + string id = 1; +} + +message GetUserResponse { + google.protobuf.Timestamp created_at = 1; +} +`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + dir := t.TempDir() + + for name, content := range tt.imports { + path := filepath.Join(dir, name) + + if err := os.MkdirAll( + filepath.Dir(path), + 0o700, + ); err != nil { + t.Fatal(err) + } + + if err := os.WriteFile( + path, + []byte(content), + 0o600, + ); err != nil { + t.Fatal(err) + } + } + + path := filepath.Join(dir, "users.proto") + + if err := os.WriteFile( + path, + []byte(tt.proto), + 0o600, + ); err != nil { + t.Fatal(err) + } + + resolver := NewProtoMethodResolver(nil) + + spec := &model.GRPCProtoSpec{ + External: &model.GRPCExternalProtoSpec{ + File: path, + Service: "users.v1.UserService", + }, + } + + method, err := resolver.ResolveMethod( + context.Background(), + spec, + "GetUser", + ) + if err != nil { + t.Fatalf("ResolveMethod() error = %v", err) + } + + if method.FullName() != "users.v1.UserService.GetUser" { + t.Errorf( + "unexpected method: %s", + method.FullName(), + ) + } + }) + } +} + +func TestProtoMethodResolverResolveExternalFileSecurity(t *testing.T) { + tests := []struct { + name string + importPath string + setup func(t *testing.T, root, parent string) + expectedError error + }{ + { + name: "parent directory traversal", + importPath: "../secret.proto", + setup: func(t *testing.T, root, parent string) { + if err := os.WriteFile( + filepath.Join(parent, "secret.proto"), + []byte(` +syntax = "proto3"; +package users.v1; +message Secret {} +`), + 0o600, + ); err != nil { + t.Fatal(err) + } + }, + expectedError: errors.ErrCannotLoadGRPCProto, + }, + { + name: "symlink escaping root", + importPath: "secret.proto", + setup: func(t *testing.T, root, parent string) { + outside := filepath.Join(parent, "secret.proto") + + if err := os.WriteFile( + outside, + []byte(` +syntax = "proto3"; +package users.v1; +message Secret {} +`), + 0o600, + ); err != nil { + t.Fatal(err) + } + + if err := os.Symlink( + outside, + filepath.Join(root, "secret.proto"), + ); err != nil { + t.Fatal(err) + } + }, + expectedError: errors.ErrCannotLoadGRPCProto, + }, + { + name: "oversized imported file", + importPath: "large.proto", + setup: func(t *testing.T, root, parent string) { + path := filepath.Join(root, "large.proto") + + file, err := os.Create(path) + if err != nil { + t.Fatal(err) + } + defer file.Close() + + if err := file.Truncate( + util.MaxFileSize + 1, + ); err != nil { + t.Fatal(err) + } + }, + expectedError: errors.ErrCannotLoadGRPCProto, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + parent := t.TempDir() + root := filepath.Join(parent, "proto") + + if err := os.Mkdir(root, 0o700); err != nil { + t.Fatal(err) + } + + tt.setup(t, root, parent) + + source := ` +syntax = "proto3"; +package users.v1; + +import "` + tt.importPath + `"; + +service UserService { + rpc GetUser(GetUserRequest) returns (GetUserResponse); +} + +message GetUserRequest {} +message GetUserResponse {} +` + + path := filepath.Join(root, "users.proto") + + if err := os.WriteFile( + path, + []byte(source), + 0o600, + ); err != nil { + t.Fatal(err) + } + + resolver := NewProtoMethodResolver(nil) + + spec := &model.GRPCProtoSpec{ + External: &model.GRPCExternalProtoSpec{ + File: path, + Service: "users.v1.UserService", + }, + } + + _, err := resolver.ResolveMethod( + context.Background(), + spec, + "GetUser", + ) + + if !nativeerrors.Is(err, tt.expectedError) { + t.Errorf( + "expected error %v, got %v", + tt.expectedError, + err, + ) + } + }) + } +} + +func TestProtoMethodResolverResolveExternalFileTooLarge(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "large.proto") + + file, err := os.Create(path) + if err != nil { + t.Fatal(err) + } + + if err := file.Truncate(util.MaxFileSize + 1); err != nil { + _ = file.Close() + t.Fatal(err) + } + + if err := file.Close(); err != nil { + t.Fatal(err) + } + + resolver := NewProtoMethodResolver(nil) + + spec := &model.GRPCProtoSpec{ + External: &model.GRPCExternalProtoSpec{ + File: path, + Service: "users.v1.UserService", + }, + } + + _, err = resolver.ResolveMethod( + context.Background(), + spec, + "GetUser", + ) + + if !nativeerrors.Is(err, errors.ErrInaccessiblePath) { + t.Errorf( + "expected error %v, got %v", + errors.ErrInaccessiblePath, + err, + ) + } +} + func cloneInternalProtoSpec( spec *model.GRPCInternalProtoSpec, ) *model.GRPCInternalProtoSpec { diff --git a/execute/runtime/service/grpc/mock.go b/execute/runtime/service/grpc/mock.go index 510ad2d..8b9188d 100644 --- a/execute/runtime/service/grpc/mock.go +++ b/execute/runtime/service/grpc/mock.go @@ -26,6 +26,7 @@ import ( ) type MockGRPCService struct { + cfg *MockGRPCServiceConfig logger log.Logger spec *model.ServiceSpec @@ -57,11 +58,13 @@ type Fixture struct { } func NewMockGRPCService( + cfg *MockGRPCServiceConfig, logger log.Logger, spec *model.ServiceSpec, resolver MethodResolver, ) *MockGRPCService { return &MockGRPCService{ + cfg: cfg, logger: logger.With( log.String( keys.EnvironmentServiceID, @@ -103,6 +106,9 @@ func (s *MockGRPCService) Mount( s.runtimeAddress = listener.Addr().String() s.server = ggrpc.NewServer( + ggrpc.MaxRecvMsgSize(s.cfg.MaxMessageSize), + ggrpc.MaxSendMsgSize(s.cfg.MaxMessageSize), + ggrpc.MaxHeaderListSize(s.cfg.MaxMetadataSize), ggrpc.UnknownServiceHandler(s.handle), ) @@ -163,9 +169,7 @@ func (s *MockGRPCService) handle( _ any, stream ggrpc.ServerStream, ) error { - fullMethod, ok := ggrpc.MethodFromServerStream( - stream, - ) + fullMethod, ok := ggrpc.MethodFromServerStream(stream) if !ok { return status.Error( codes.Internal, @@ -183,7 +187,7 @@ func (s *MockGRPCService) handle( if err != nil { return status.Error( codes.Unimplemented, - err.Error(), + "cannot resolve gRPC method", ) } @@ -195,17 +199,13 @@ func (s *MockGRPCService) handle( ) } - request := dynamicpb.NewMessage( - method.Input(), - ) + request := dynamicpb.NewMessage(method.Input()) if errRecv := stream.RecvMsg(request); errRecv != nil { return errRecv } - incomingMetadata, _ := metadata.FromIncomingContext( - stream.Context(), - ) + incomingMetadata, _ := metadata.FromIncomingContext(stream.Context()) fixture, err := s.match( fullMethod, @@ -213,9 +213,14 @@ func (s *MockGRPCService) handle( incomingMetadata, ) if err != nil { + s.logger.Error( + "Failed to match gRPC request", + log.String(keys.GRPCMethod, fullMethod), + ) + return status.Error( codes.Internal, - err.Error(), + "failed to match gRPC request", ) } @@ -225,9 +230,7 @@ func (s *MockGRPCService) handle( log.String(keys.GRPCMethod, fullMethod), ) - stream.SetTrailer( - metadata.Pairs(string(keys.E2EngineMockMissMetadata), "true"), - ) + stream.SetTrailer(metadata.Pairs(string(keys.E2EngineMockMissMetadata), "true")) return status.Error( codes.Unimplemented, @@ -262,9 +265,14 @@ func (s *MockGRPCService) handle( fixture.response, ) if err != nil { + s.logger.Error( + "Failed to build gRPC mock response", + log.String(keys.GRPCMethod, fullMethod), + ) + return status.Error( codes.Internal, - err.Error(), + "failed to build gRPC response", ) } diff --git a/execute/runtime/service/grpc/mock_address_resolver_test.go b/execute/runtime/service/grpc/mock_address_resolver_test.go new file mode 100644 index 0000000..b1a23e0 --- /dev/null +++ b/execute/runtime/service/grpc/mock_address_resolver_test.go @@ -0,0 +1,55 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: address_resolver.go +// +// Generated by this command: +// +// mockgen -source=address_resolver.go -destination=mock_address_resolver_test.go -package=grpc +// + +// Package grpc is a generated GoMock package. +package grpc + +import ( + reflect "reflect" + + gomock "go.uber.org/mock/gomock" +) + +// MockaddressResolver is a mock of addressResolver interface. +type MockaddressResolver struct { + ctrl *gomock.Controller + recorder *MockaddressResolverMockRecorder + isgomock struct{} +} + +// MockaddressResolverMockRecorder is the mock recorder for MockaddressResolver. +type MockaddressResolverMockRecorder struct { + mock *MockaddressResolver +} + +// NewMockaddressResolver creates a new mock instance. +func NewMockaddressResolver(ctrl *gomock.Controller) *MockaddressResolver { + mock := &MockaddressResolver{ctrl: ctrl} + mock.recorder = &MockaddressResolverMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockaddressResolver) EXPECT() *MockaddressResolverMockRecorder { + return m.recorder +} + +// ResolveGRPCTarget mocks base method. +func (m *MockaddressResolver) ResolveGRPCTarget(value string) (string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ResolveGRPCTarget", value) + ret0, _ := ret[0].(string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ResolveGRPCTarget indicates an expected call of ResolveGRPCTarget. +func (mr *MockaddressResolverMockRecorder) ResolveGRPCTarget(value any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ResolveGRPCTarget", reflect.TypeOf((*MockaddressResolver)(nil).ResolveGRPCTarget), value) +} diff --git a/execute/runtime/service/grpc/mock_test.go b/execute/runtime/service/grpc/mock_test.go index a3ea89b..b2a4c73 100644 --- a/execute/runtime/service/grpc/mock_test.go +++ b/execute/runtime/service/grpc/mock_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" nativeerrors "errors" + "strings" "testing" "time" @@ -11,6 +12,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protodesc" "google.golang.org/protobuf/reflect/protoreflect" @@ -1160,6 +1162,10 @@ func TestMockGRPCServiceHandle(t *testing.T) { method := testMethodDescriptor(t) service := &MockGRPCService{ + cfg: &MockGRPCServiceConfig{ + MaxMessageSize: 4 << 20, + MaxMetadataSize: 64 << 10, + }, logger: logger, spec: &model.ServiceSpec{ Proto: &model.GRPCProtoSpec{}, @@ -1320,6 +1326,274 @@ func TestMockGRPCServiceHandle(t *testing.T) { } } +func TestMockGRPCServiceMessageSizeLimit(t *testing.T) { + method := testMethodDescriptor(t) + + tests := []struct { + name string + requestID string + responseName string + limit int + wantCode codes.Code + }{ + { + name: "request exactly at limit", + requestID: "abc", + limit: 5, + wantCode: codes.OK, + }, + { + name: "request exceeds limit", + requestID: "abcd", + limit: 5, + wantCode: codes.ResourceExhausted, + }, + { + name: "response exactly at limit", + responseName: "abc", + limit: 5, + wantCode: codes.OK, + }, + { + name: "response exceeds limit", + responseName: "abcd", + limit: 5, + wantCode: codes.ResourceExhausted, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + logger, err := log.NewSilentLogger() + if err != nil { + t.Fatal(err) + } + + service := &MockGRPCService{ + cfg: &MockGRPCServiceConfig{ + MaxMessageSize: tt.limit, + MaxMetadataSize: 64 << 10, + }, + logger: logger, + spec: &model.ServiceSpec{ + Proto: &model.GRPCProtoSpec{}, + }, + fixtures: []Fixture{ + { + service: "users.v1.UserService", + method: "GetUser", + status: codes.OK, + response: map[string]any{ + "name": tt.responseName, + }, + }, + }, + resolver: &testMethodResolver{ + method: method, + }, + } + + if err := service.Mount(t.Context()); err != nil { + t.Fatalf("Mount() error = %v", err) + } + + defer func() { + ctx, cancel := context.WithTimeout( + context.Background(), + 5*time.Second, + ) + defer cancel() + + if err := service.Unmount(ctx); err != nil { + t.Errorf("Unmount() error = %v", err) + } + }() + + conn, err := grpc.NewClient( + service.GetRuntimeAddress(), + grpc.WithTransportCredentials( + insecure.NewCredentials(), + ), + ) + if err != nil { + t.Fatalf("NewClient() error = %v", err) + } + defer conn.Close() + + request := dynamicpb.NewMessage(method.Input()) + + if tt.requestID != "" { + request.Set( + method.Input().Fields().ByName("id"), + protoreflect.ValueOfString(tt.requestID), + ) + } + + response := dynamicpb.NewMessage(method.Output()) + + err = conn.Invoke( + t.Context(), + "/users.v1.UserService/GetUser", + request, + response, + ) + + if code := status.Code(err); code != tt.wantCode { + t.Fatalf( + "status = %s, want %s (error: %v)", + code, + tt.wantCode, + err, + ) + } + + if tt.wantCode == codes.OK { + name := method.Output().Fields().ByName("name") + + if got := response.Get(name).String(); got != tt.responseName { + t.Errorf( + "response name = %q, want %q", + got, + tt.responseName, + ) + } + } + }) + } +} + +func TestMockGRPCServiceMetadataSizeLimit(t *testing.T) { + method := testMethodDescriptor(t) + + tests := []struct { + name string + metadata string + wantError bool + }{ + { + name: "metadata within limit", + metadata: "small", + }, + { + name: "metadata exceeds limit", + metadata: strings.Repeat("a", 4096), + wantError: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + logger, err := log.NewSilentLogger() + if err != nil { + t.Fatal(err) + } + + service := &MockGRPCService{ + cfg: &MockGRPCServiceConfig{ + MaxMessageSize: 4 << 20, + MaxMetadataSize: 1024, + }, + logger: logger, + spec: &model.ServiceSpec{ + Proto: &model.GRPCProtoSpec{}, + }, + fixtures: []Fixture{ + { + service: "users.v1.UserService", + method: "GetUser", + status: codes.OK, + response: map[string]any{ + "name": "matched", + }, + }, + }, + resolver: &testMethodResolver{ + method: method, + }, + } + + if err := service.Mount(t.Context()); err != nil { + t.Fatalf("Mount() error = %v", err) + } + + defer func() { + ctx, cancel := context.WithTimeout( + context.Background(), + 5*time.Second, + ) + defer cancel() + + if err := service.Unmount(ctx); err != nil { + t.Errorf( + "Unmount() error = %v", + err, + ) + } + }() + + conn, err := grpc.NewClient( + service.GetRuntimeAddress(), + grpc.WithTransportCredentials( + insecure.NewCredentials(), + ), + ) + if err != nil { + t.Fatalf("NewClient() error = %v", err) + } + defer conn.Close() + + ctx, cancel := context.WithTimeout( + t.Context(), + 5*time.Second, + ) + defer cancel() + + ctx = metadata.NewOutgoingContext( + ctx, + metadata.Pairs( + "x-test", + tt.metadata, + ), + ) + + request := dynamicpb.NewMessage(method.Input()) + response := dynamicpb.NewMessage(method.Output()) + + err = conn.Invoke( + ctx, + "/users.v1.UserService/GetUser", + request, + response, + ) + + if tt.wantError { + if err == nil { + t.Fatal( + "Invoke() unexpectedly succeeded with oversized metadata", + ) + } + return + } + + if err != nil { + t.Fatalf("Invoke() error = %v", err) + } + + name := method.Output(). + Fields(). + ByName("name") + + if got := response.Get(name).String(); got != "matched" { + t.Errorf( + "response name = %q, want %q", + got, + "matched", + ) + } + }) + } +} + func containsString( values []string, expected string, diff --git a/execute/runtime/service/grpc/real.go b/execute/runtime/service/grpc/real.go index 042cafe..dcf7907 100644 --- a/execute/runtime/service/grpc/real.go +++ b/execute/runtime/service/grpc/real.go @@ -20,25 +20,32 @@ import ( ) type RealGRPCService struct { + cfg *RealGRPCServiceConfig logger log.Logger spec *model.ServiceSpec + addressResolver addressResolver + server *ggrpc.Server connection *ggrpc.ClientConn runtimeAddress string } func NewRealGRPCService( + cfg *RealGRPCServiceConfig, logger log.Logger, spec *model.ServiceSpec, + addressResolver addressResolver, ) (*RealGRPCService, error) { return &RealGRPCService{ + cfg: cfg, logger: logger.With( log.String(keys.EnvironmentServiceID, spec.ID), log.String(keys.EnvironmentServiceKind, string(spec.Kind)), log.String(keys.EnvironmentServiceMode, string(spec.Mode)), ), - spec: spec, + spec: spec, + addressResolver: addressResolver, }, nil } @@ -47,13 +54,22 @@ func (s *RealGRPCService) Mount(ctx context.Context) error { return err } + resolvedTarget, err := s.addressResolver.ResolveGRPCTarget(s.spec.Target) + if err != nil { + return err + } + connection, err := ggrpc.NewClient( - s.spec.GRPCTarget, + resolvedTarget, ggrpc.WithTransportCredentials( insecure.NewCredentials(), + // TODO: preserve the logical hostname separately when introducing TLS support ), + ggrpc.WithMaxHeaderListSize(s.cfg.MaxMetadataSize), ggrpc.WithDefaultCallOptions( ggrpc.ForceCodec(rawCodec{}), + ggrpc.MaxCallRecvMsgSize(s.cfg.MaxMessageSize), + ggrpc.MaxCallSendMsgSize(s.cfg.MaxMessageSize), ), ) if err != nil { @@ -76,9 +92,10 @@ func (s *RealGRPCService) Mount(ctx context.Context) error { s.server = ggrpc.NewServer( ggrpc.ForceServerCodec(rawCodec{}), - ggrpc.UnknownServiceHandler( - s.handle, - ), + ggrpc.MaxHeaderListSize(s.cfg.MaxMetadataSize), + ggrpc.MaxRecvMsgSize(s.cfg.MaxMessageSize), + ggrpc.MaxSendMsgSize(s.cfg.MaxMessageSize), + ggrpc.UnknownServiceHandler(s.handle), ) go func() { @@ -123,7 +140,10 @@ func (s *RealGRPCService) Unmount(ctx context.Context) error { s.server.Stop() if s.connection != nil { - _ = s.connection.Close() + return nativeerrors.Join( + ctx.Err(), + s.connection.Close(), + ) } return ctx.Err() @@ -178,13 +198,10 @@ func (s *RealGRPCService) handle( ggrpc.Trailer(&responseTrailer), ggrpc.ForceCodec(rawCodec{}), ) - if err != nil { - return err - } if len(responseHeader) > 0 { - if err := stream.SendHeader(responseHeader); err != nil { - return err + if errSend := stream.SendHeader(responseHeader); errSend != nil { + return errSend } } @@ -192,6 +209,10 @@ func (s *RealGRPCService) handle( stream.SetTrailer(responseTrailer) } + if err != nil { + return err + } + return stream.SendMsg(&response) } diff --git a/execute/runtime/service/grpc/real_test.go b/execute/runtime/service/grpc/real_test.go index ecb3801..51fb9c0 100644 --- a/execute/runtime/service/grpc/real_test.go +++ b/execute/runtime/service/grpc/real_test.go @@ -4,12 +4,16 @@ import ( "context" nativeerrors "errors" "net" + "strings" "testing" "time" + "go.uber.org/mock/gomock" ggrpc "google.golang.org/grpc" + "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" "github.com/e2engine/core/model" "github.com/e2engine/core/pkg/errors" @@ -204,6 +208,43 @@ func TestRealGRPCServiceMountCanceledContext(t *testing.T) { } } +func TestRealGRPCServiceMountAddressResolutionError(t *testing.T) { + ctrl := gomock.NewController(t) + + addressResolver := NewMockaddressResolver(ctrl) + + resolveErr := nativeerrors.New("cannot resolve target") + + addressResolver.EXPECT(). + ResolveGRPCTarget("gateway-host:9000"). + Return("", resolveErr) + + service := &RealGRPCService{ + spec: &model.ServiceSpec{ + Target: "gateway-host:9000", + }, + addressResolver: addressResolver, + } + + err := service.Mount(context.Background()) + + if !nativeerrors.Is(err, resolveErr) { + t.Errorf( + "expected %v, got %v", + resolveErr, + err, + ) + } + + if service.server != nil { + t.Error("expected server not to be created") + } + + if service.connection != nil { + t.Error("expected connection not to be created") + } +} + func TestRealGRPCServiceUnmountBeforeMount(t *testing.T) { service := &RealGRPCService{} @@ -301,6 +342,14 @@ func TestRealGRPCServiceProxy(t *testing.T) { defer upstream.Stop() + ctrl := gomock.NewController(t) + + resolver := NewMockaddressResolver(ctrl) + + resolver.EXPECT(). + ResolveGRPCTarget("gateway-host:9000"). + Return(upstreamListener.Addr().String(), nil) + logger, err := log.NewSilentLogger() if err != nil { t.Fatalf( @@ -310,11 +359,16 @@ func TestRealGRPCServiceProxy(t *testing.T) { } service, err := NewRealGRPCService( + &RealGRPCServiceConfig{ + MaxMessageSize: 4 << 20, + MaxMetadataSize: 64 << 10, + }, logger, &model.ServiceSpec{ - ID: "upstream", - GRPCTarget: upstreamListener.Addr().String(), + ID: "upstream", + Target: "gateway-host:9000", }, + resolver, ) if err != nil { t.Fatalf( @@ -469,3 +523,548 @@ func TestRealGRPCServiceProxy(t *testing.T) { ) } } + +func TestRealGRPCServiceProxyErrorMetadata(t *testing.T) { + const ( + logicalTarget = "gateway-host:9000" + fullMethod = "/users.v1.UserService/GetUser" + ) + + listener, err := (&net.ListenConfig{}).Listen( + t.Context(), + "tcp", + "127.0.0.1:0", + ) + if err != nil { + t.Fatalf("Listen() error = %v", err) + } + + upstream := ggrpc.NewServer( + ggrpc.ForceServerCodec(rawCodec{}), + ggrpc.UnknownServiceHandler( + func(_ any, stream ggrpc.ServerStream) error { + var request rawMessage + + if err := stream.RecvMsg(&request); err != nil { + return err + } + + if string(request) != "request payload" { + t.Errorf( + "upstream request = %q, want %q", + request, + "request payload", + ) + } + + if err := stream.SendHeader( + metadata.Pairs( + "x-request-id", + "abc123", + ), + ); err != nil { + return err + } + + stream.SetTrailer( + metadata.Pairs( + "x-error-code", + "ACCESS_DENIED", + ), + ) + + return status.Error( + codes.PermissionDenied, + "access denied", + ) + }, + ), + ) + + go func() { + _ = upstream.Serve(listener) + }() + + defer upstream.Stop() + + ctrl := gomock.NewController(t) + + resolver := NewMockaddressResolver(ctrl) + + resolver.EXPECT(). + ResolveGRPCTarget(logicalTarget). + Return(listener.Addr().String(), nil) + + logger, err := log.NewSilentLogger() + if err != nil { + t.Fatalf("NewSilentLogger() error = %v", err) + } + + service, err := NewRealGRPCService( + &RealGRPCServiceConfig{ + MaxMessageSize: 4 << 20, + MaxMetadataSize: 64 << 10, + }, + logger, + &model.ServiceSpec{ + ID: "upstream", + Target: logicalTarget, + }, + resolver, + ) + if err != nil { + t.Fatalf("NewRealGRPCService() error = %v", err) + } + + ctx, cancel := context.WithTimeout( + context.Background(), + 5*time.Second, + ) + defer cancel() + + if err := service.Mount(ctx); err != nil { + t.Fatalf("Mount() error = %v", err) + } + + defer func() { + unmountCtx, unmountCancel := context.WithTimeout( + context.Background(), + 5*time.Second, + ) + defer unmountCancel() + + if err := service.Unmount(unmountCtx); err != nil { + t.Errorf("Unmount() error = %v", err) + } + }() + + connection, err := ggrpc.NewClient( + service.GetRuntimeAddress(), + ggrpc.WithTransportCredentials( + insecure.NewCredentials(), + ), + ggrpc.WithDefaultCallOptions( + ggrpc.ForceCodec(rawCodec{}), + ), + ) + if err != nil { + t.Fatalf("NewClient() error = %v", err) + } + defer connection.Close() + + request := rawMessage("request payload") + + var response rawMessage + var responseHeader metadata.MD + var responseTrailer metadata.MD + + err = connection.Invoke( + ctx, + fullMethod, + &request, + &response, + ggrpc.Header(&responseHeader), + ggrpc.Trailer(&responseTrailer), + ) + + if code := status.Code(err); code != codes.PermissionDenied { + t.Errorf( + "status = %s, want %s (error: %v)", + code, + codes.PermissionDenied, + err, + ) + } + + if got := status.Convert(err).Message(); got != "access denied" { + t.Errorf( + "status message = %q, want %q", + got, + "access denied", + ) + } + + if values := responseHeader.Get("x-request-id"); len(values) != 1 || + values[0] != "abc123" { + t.Errorf( + "response header = %v, want [abc123]", + values, + ) + } + + if values := responseTrailer.Get("x-error-code"); len(values) != 1 || + values[0] != "ACCESS_DENIED" { + t.Errorf( + "response trailer = %v, want [ACCESS_DENIED]", + values, + ) + } + + if len(response) != 0 { + t.Errorf( + "expected empty response message, got %v", + response, + ) + } +} + +func TestRealGRPCServiceMessageSizeLimit(t *testing.T) { + const limit = 5 + + tests := []struct { + name string + request rawMessage + response rawMessage + wantCode codes.Code + }{ + { + name: "exactly at limit", + request: rawMessage{1, 2, 3, 4, 5}, + response: rawMessage{6, 7, 8, 9, 10}, + wantCode: codes.OK, + }, + { + name: "request exceeds limit", + request: rawMessage{1, 2, 3, 4, 5, 6}, + response: rawMessage{7}, + wantCode: codes.ResourceExhausted, + }, + { + name: "response exceeds limit", + request: rawMessage{1}, + response: rawMessage{2, 3, 4, 5, 6, 7}, + wantCode: codes.ResourceExhausted, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + upstreamListener, err := (&net.ListenConfig{}).Listen( + t.Context(), + "tcp", + "127.0.0.1:0", + ) + if err != nil { + t.Fatalf("Listen() error = %v", err) + } + + upstream := ggrpc.NewServer( + ggrpc.ForceServerCodec(rawCodec{}), + ggrpc.UnknownServiceHandler( + func(_ any, stream ggrpc.ServerStream) error { + var request rawMessage + + if err := stream.RecvMsg(&request); err != nil { + return err + } + + if string(request) != string(tt.request) { + t.Errorf( + "upstream request = %v, want %v", + request, + tt.request, + ) + } + + return stream.SendMsg(&tt.response) + }, + ), + ) + + go func() { + _ = upstream.Serve(upstreamListener) + }() + defer upstream.Stop() + + ctrl := gomock.NewController(t) + resolver := NewMockaddressResolver(ctrl) + + const logicalTarget = "gateway-host:9000" + + resolver.EXPECT(). + ResolveGRPCTarget(logicalTarget). + Return(upstreamListener.Addr().String(), nil) + + logger, err := log.NewSilentLogger() + if err != nil { + t.Fatalf("NewSilentLogger() error = %v", err) + } + + service, err := NewRealGRPCService( + &RealGRPCServiceConfig{ + MaxMessageSize: limit, + MaxMetadataSize: 64 << 10, + }, + logger, + &model.ServiceSpec{ + ID: "upstream", + Target: logicalTarget, + }, + resolver, + ) + if err != nil { + t.Fatalf("NewRealGRPCService() error = %v", err) + } + + if err := service.Mount(t.Context()); err != nil { + t.Fatalf("Mount() error = %v", err) + } + + defer func() { + ctx, cancel := context.WithTimeout( + context.Background(), + 5*time.Second, + ) + defer cancel() + + if err := service.Unmount(ctx); err != nil { + t.Errorf("Unmount() error = %v", err) + } + }() + + connection, err := ggrpc.NewClient( + service.GetRuntimeAddress(), + ggrpc.WithTransportCredentials( + insecure.NewCredentials(), + ), + ggrpc.WithDefaultCallOptions( + ggrpc.ForceCodec(rawCodec{}), + ), + ) + if err != nil { + t.Fatalf("NewClient() error = %v", err) + } + defer connection.Close() + + var response rawMessage + + err = connection.Invoke( + t.Context(), + "/users.v1.UserService/GetUser", + &tt.request, + &response, + ) + + if code := status.Code(err); code != tt.wantCode { + t.Fatalf( + "status = %s, want %s (error: %v)", + code, + tt.wantCode, + err, + ) + } + + if tt.wantCode == codes.OK { + if string(response) != string(tt.response) { + t.Errorf( + "response = %v, want %v", + response, + tt.response, + ) + } + } + }) + } +} + +func TestRealGRPCServiceMetadataSizeLimit(t *testing.T) { + const ( + limit uint32 = 1024 + logicalTarget = "gateway-host:9000" + fullMethod = "/users.v1.UserService/GetUser" + ) + + tests := []struct { + name string + requestMetadata string + responseMetadata string + wantSuccess bool + wantUpstream bool + }{ + { + name: "within limit", + requestMetadata: "small", + responseMetadata: "small", + wantSuccess: true, + wantUpstream: true, + }, + { + name: "request exceeds limit", + requestMetadata: strings.Repeat("a", 4096), + }, + { + name: "response exceeds limit", + requestMetadata: "small", + responseMetadata: strings.Repeat("b", 4096), + wantUpstream: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + listener, err := (&net.ListenConfig{}).Listen( + t.Context(), + "tcp", + "127.0.0.1:0", + ) + if err != nil { + t.Fatalf("Listen() error = %v", err) + } + + upstreamCalled := make(chan struct{}, 1) + + upstream := ggrpc.NewServer( + ggrpc.ForceServerCodec(rawCodec{}), + ggrpc.UnknownServiceHandler( + func(_ any, stream ggrpc.ServerStream) error { + var request rawMessage + + if err := stream.RecvMsg(&request); err != nil { + return err + } + + upstreamCalled <- struct{}{} + + if err := stream.SendHeader( + metadata.Pairs( + "x-response", + tt.responseMetadata, + ), + ); err != nil { + return err + } + + response := rawMessage("response payload") + return stream.SendMsg(&response) + }, + ), + ) + + go func() { + _ = upstream.Serve(listener) + }() + defer upstream.Stop() + + ctrl := gomock.NewController(t) + resolver := NewMockaddressResolver(ctrl) + + resolver.EXPECT(). + ResolveGRPCTarget(logicalTarget). + Return(listener.Addr().String(), nil) + + logger, err := log.NewSilentLogger() + if err != nil { + t.Fatalf("NewSilentLogger() error = %v", err) + } + + service, err := NewRealGRPCService( + &RealGRPCServiceConfig{ + MaxMessageSize: 4 << 20, + MaxMetadataSize: limit, + }, + logger, + &model.ServiceSpec{ + ID: "upstream", + Target: logicalTarget, + }, + resolver, + ) + if err != nil { + t.Fatalf("NewRealGRPCService() error = %v", err) + } + + if err := service.Mount(t.Context()); err != nil { + t.Fatalf("Mount() error = %v", err) + } + + defer func() { + ctx, cancel := context.WithTimeout( + context.Background(), + 5*time.Second, + ) + defer cancel() + + if err := service.Unmount(ctx); err != nil { + t.Errorf("Unmount() error = %v", err) + } + }() + + connection, err := ggrpc.NewClient( + service.GetRuntimeAddress(), + ggrpc.WithTransportCredentials( + insecure.NewCredentials(), + ), + ggrpc.WithDefaultCallOptions( + ggrpc.ForceCodec(rawCodec{}), + ), + ) + if err != nil { + t.Fatalf("NewClient() error = %v", err) + } + defer connection.Close() + + ctx, cancel := context.WithTimeout( + t.Context(), + 5*time.Second, + ) + defer cancel() + + ctx = metadata.NewOutgoingContext( + ctx, + metadata.Pairs( + "x-request", + tt.requestMetadata, + ), + ) + + request := rawMessage("request payload") + var response rawMessage + var header metadata.MD + + err = connection.Invoke( + ctx, + fullMethod, + &request, + &response, + ggrpc.Header(&header), + ) + + if tt.wantSuccess { + if err != nil { + t.Fatalf("Invoke() error = %v", err) + } + + if string(response) != "response payload" { + t.Errorf( + "response = %q, want %q", + response, + "response payload", + ) + } + + values := header.Get("x-response") + if len(values) != 1 || values[0] != tt.responseMetadata { + t.Errorf( + "response metadata = %v, want [%s]", + values, + tt.responseMetadata, + ) + } + } else if err == nil { + t.Fatal("expected metadata size limit error") + } + + select { + case <-upstreamCalled: + if !tt.wantUpstream { + t.Error("upstream unexpectedly invoked") + } + + default: + if tt.wantUpstream { + t.Error("upstream not invoked") + } + } + }) + } +} diff --git a/execute/runtime/service/http/address_resolver.go b/execute/runtime/service/http/address_resolver.go new file mode 100644 index 0000000..dea6215 --- /dev/null +++ b/execute/runtime/service/http/address_resolver.go @@ -0,0 +1,7 @@ +package http + +type addressResolver interface { + ResolveHTTPURL(value string) (string, error) +} + +//go:generate go run -mod=mod go.uber.org/mock/mockgen -source=address_resolver.go -destination=mock_address_resolver_test.go -package=http diff --git a/execute/runtime/service/http/config.go b/execute/runtime/service/http/config.go new file mode 100644 index 0000000..9ff4e99 --- /dev/null +++ b/execute/runtime/service/http/config.go @@ -0,0 +1,25 @@ +package http + +import "time" + +type MockHTTPServiceConfig struct { + MaxRequestBodySize int64 `json:"max_request_body_size" yaml:"max_request_body_size" env:"MAX_REQUEST_BODY_SIZE" default:"1048576" validate:"min(1),max(67108864)"` + + ReadHeaderTimeout time.Duration `json:"read_header_timeout" yaml:"read_header_timeout" env:"READ_HEADER_TIMEOUT" default:"5s" validate:"min(1s)"` + IdleTimeout time.Duration `json:"idle_timeout" yaml:"idle_timeout" env:"IDLE_TIMEOUT" default:"60s" validate:"min(1s)"` + + MaxRequestHeaderBytes int `json:"max_request_header_bytes" yaml:"max_request_header_bytes" env:"MAX_REQUEST_HEADER_BYTES" default:"1048576" validate:"min(1024),max(16777216)"` +} + +type RealHTTPServiceConfig struct { + MaxRequestBodySize int64 `json:"max_request_body_size" yaml:"max_request_body_size" env:"MAX_REQUEST_BODY_SIZE" default:"1048576" validate:"min(1),max(67108864)"` + + ReadHeaderTimeout time.Duration `json:"read_header_timeout" yaml:"read_header_timeout" env:"READ_HEADER_TIMEOUT" default:"5s" validate:"min(1s)"` + IdleTimeout time.Duration `json:"idle_timeout" yaml:"idle_timeout" env:"IDLE_TIMEOUT" default:"60s" validate:"min(1s)"` + + MaxRequestHeaderBytes int `json:"max_request_header_bytes" yaml:"max_request_header_bytes" env:"MAX_REQUEST_HEADER_BYTES" default:"1048576" validate:"min(1024),max(16777216)"` + + ResponseHeaderTimeout time.Duration `json:"response_header_timeout" yaml:"response_header_timeout" env:"RESPONSE_HEADER_TIMEOUT" default:"30s" validate:"min(1s)"` + + MaxResponseHeaderBytes int64 `json:"max_response_header_bytes" yaml:"max_response_header_bytes" env:"MAX_RESPONSE_HEADER_BYTES" default:"1048576" validate:"min(1024),max(16777216)"` +} diff --git a/execute/runtime/service/http/mock.go b/execute/runtime/service/http/mock.go index 745966f..2ab65ab 100644 --- a/execute/runtime/service/http/mock.go +++ b/execute/runtime/service/http/mock.go @@ -21,6 +21,7 @@ import ( ) type MockHTTPService struct { + cfg *MockHTTPServiceConfig logger log.Logger spec *model.ServiceSpec @@ -30,9 +31,14 @@ type MockHTTPService struct { runtimeAddress string } -func NewMockHTTPService(logger log.Logger, spec *model.ServiceSpec) *MockHTTPService { +func NewMockHTTPService( + cfg *MockHTTPServiceConfig, + logger log.Logger, + spec *model.ServiceSpec, +) *MockHTTPService { // The spec has already been validated higher up the stack, so we can assume it's valid here. return &MockHTTPService{ + cfg: cfg, logger: logger.With( log.String(keys.EnvironmentServiceID, spec.ID), log.String(keys.EnvironmentServiceKind, string(spec.Kind)), @@ -57,7 +63,10 @@ func (s *MockHTTPService) Mount(ctx context.Context) error { s.runtimeAddress = listener.Addr().String() s.server = &http.Server{ - Handler: s, + Handler: s, + ReadHeaderTimeout: s.cfg.ReadHeaderTimeout, + IdleTimeout: s.cfg.IdleTimeout, + MaxHeaderBytes: s.cfg.MaxRequestHeaderBytes, } go func() { @@ -86,7 +95,19 @@ func (s *MockHTTPService) GetRuntimeAddress() string { } func (s *MockHTTPService) Unmount(ctx context.Context) error { - return s.server.Shutdown(ctx) + if s.server == nil { + return nil + } + + err := s.server.Shutdown(ctx) + if err != nil { + return nativeerrors.Join( + err, + s.server.Close(), + ) + } + + return nil } func (s *MockHTTPService) ServeHTTP( @@ -95,9 +116,17 @@ func (s *MockHTTPService) ServeHTTP( ) { fixture, err := s.match(r) if err != nil { + if nativeerrors.Is(err, errors.ErrHTTPRequestBodyTooLarge) { + http.Error( + w, + http.StatusText(http.StatusRequestEntityTooLarge), + http.StatusRequestEntityTooLarge, + ) + return + } http.Error( w, - err.Error(), + http.StatusText(http.StatusBadRequest), http.StatusBadRequest, ) return @@ -109,7 +138,6 @@ func (s *MockHTTPService) ServeHTTP( s.logger.Debug( "No fixture matched request", log.String(keys.RequestMethod, r.Method), - log.String(keys.RequestURLPath, r.URL.Path), ) http.Error( @@ -126,12 +154,16 @@ func (s *MockHTTPService) ServeHTTP( func (s *MockHTTPService) match( r *http.Request, ) (*Fixture, error) { - body, err := io.ReadAll(r.Body) + body, err := io.ReadAll( + io.LimitReader(r.Body, s.cfg.MaxRequestBodySize+1), + ) + if err == nil && int64(len(body)) > s.cfg.MaxRequestBodySize { + return nil, errors.ErrHTTPRequestBodyTooLarge + } if err != nil { s.logger.Error( errors.ErrFailedToReadRequestBody.Error(), log.String(keys.RequestMethod, r.Method), - log.String(keys.RequestURLPath, r.URL.Path), log.Err(keys.Cause, err), ) @@ -143,11 +175,14 @@ func (s *MockHTTPService) match( ) } + query := r.URL.Query() + for i := range s.fixtures { fixture := &s.fixtures[i] - if fixture.method == r.Method && fixture.path == r.URL.Path && - areQueryParamsEqual(fixture.query, r.URL.Query()) && + if fixture.method == r.Method && + fixture.path == r.URL.Path && + areQueryParamsEqual(fixture.query, query) && areHeadersEqual(fixture.headers, r.Header) { equalBody, errBodyEqual := isBodyEqual( fixture.body, @@ -248,15 +283,7 @@ func (s *MockHTTPService) respond( if _, err := w.Write(body); err != nil { s.logger.Error( errors.ErrFailedToWriteResponseBody.Error(), - log.String( - keys.RequestMethod, - fixture.method, - ), - log.String( - keys.RequestURLPath, - fixture.path, - ), - log.Err(keys.Cause, err), + log.String(keys.RequestMethod, fixture.method), ) return diff --git a/execute/runtime/service/http/mock_address_resolver_test.go b/execute/runtime/service/http/mock_address_resolver_test.go new file mode 100644 index 0000000..f4b0b94 --- /dev/null +++ b/execute/runtime/service/http/mock_address_resolver_test.go @@ -0,0 +1,55 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: address_resolver.go +// +// Generated by this command: +// +// mockgen -source=address_resolver.go -destination=mock_address_resolver_test.go -package=http +// + +// Package http is a generated GoMock package. +package http + +import ( + reflect "reflect" + + gomock "go.uber.org/mock/gomock" +) + +// MockaddressResolver is a mock of addressResolver interface. +type MockaddressResolver struct { + ctrl *gomock.Controller + recorder *MockaddressResolverMockRecorder + isgomock struct{} +} + +// MockaddressResolverMockRecorder is the mock recorder for MockaddressResolver. +type MockaddressResolverMockRecorder struct { + mock *MockaddressResolver +} + +// NewMockaddressResolver creates a new mock instance. +func NewMockaddressResolver(ctrl *gomock.Controller) *MockaddressResolver { + mock := &MockaddressResolver{ctrl: ctrl} + mock.recorder = &MockaddressResolverMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockaddressResolver) EXPECT() *MockaddressResolverMockRecorder { + return m.recorder +} + +// ResolveHTTPURL mocks base method. +func (m *MockaddressResolver) ResolveHTTPURL(value string) (string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ResolveHTTPURL", value) + ret0, _ := ret[0].(string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ResolveHTTPURL indicates an expected call of ResolveHTTPURL. +func (mr *MockaddressResolverMockRecorder) ResolveHTTPURL(value any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ResolveHTTPURL", reflect.TypeOf((*MockaddressResolver)(nil).ResolveHTTPURL), value) +} diff --git a/execute/runtime/service/http/mock_test.go b/execute/runtime/service/http/mock_test.go index 9ab3f08..a6b3799 100644 --- a/execute/runtime/service/http/mock_test.go +++ b/execute/runtime/service/http/mock_test.go @@ -1,11 +1,17 @@ package http_test import ( + "bufio" "context" + "errors" + "fmt" "io" + "net" "net/http" + "net/http/httptest" "strings" "testing" + "time" httpservice "github.com/e2engine/core/execute/runtime/service/http" "github.com/e2engine/core/model" @@ -921,28 +927,398 @@ func TestMockHTTPServiceResponse(t *testing.T) { } } +func TestMockHTTPServiceRequestBodySizeLimit(t *testing.T) { + const limit int64 = 5 + + tests := []struct { + name string + body string + fixtureBody *matcher.String + expectedStatus int + }{ + { + name: "below limit", + body: "abcd", + fixtureBody: ptr("abcd"), + expectedStatus: http.StatusOK, + }, + { + name: "exactly at limit", + body: "abcde", + fixtureBody: ptr("abcde"), + expectedStatus: http.StatusOK, + }, + { + name: "exceeds limit by one byte", + body: "abcdef", + fixtureBody: ptr("abcdef"), + expectedStatus: http.StatusRequestEntityTooLarge, + }, + { + name: "exceeds limit without body expectation", + body: "abcdef", + expectedStatus: http.StatusRequestEntityTooLarge, + }, + { + name: "empty body", + expectedStatus: http.StatusOK, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + fixture := newHTTPFixture( + http.MethodPost, + "/test", + nil, + tt.fixtureBody, + nil, + http.StatusOK, + ) + + service := newTestMockHTTPServiceWithConfig( + t, + &httpservice.MockHTTPServiceConfig{ + MaxRequestBodySize: limit, + ReadHeaderTimeout: 5 * time.Second, + IdleTimeout: 60 * time.Second, + MaxRequestHeaderBytes: 1 << 20, + }, + []model.FixtureSpec{fixture}, + ) + + if err := service.Mount(t.Context()); err != nil { + t.Fatalf("Mount() error = %v", err) + } + + t.Cleanup(func() { + if err := service.Unmount(context.Background()); err != nil { + t.Errorf("Unmount() error = %v", err) + } + }) + + req, err := http.NewRequestWithContext( + t.Context(), + http.MethodPost, + "http://"+service.GetRuntimeAddress()+"/test", + strings.NewReader(tt.body), + ) + if err != nil { + t.Fatalf("cannot create request: %v", err) + } + + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("request error = %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != tt.expectedStatus { + t.Errorf( + "expected status %d, got %d", + tt.expectedStatus, + resp.StatusCode, + ) + } + + // An oversized request must not be classified + // as an ordinary fixture mismatch. + if got := resp.Header.Get( + string(keys.E2EngineMockMissHeader), + ); got == "true" { + t.Error("unexpected fixture mismatch header") + } + }) + } +} + +func TestMockHTTPServiceRequestHeaderSizeLimit(t *testing.T) { + service := newTestMockHTTPServiceWithConfig( + t, + &httpservice.MockHTTPServiceConfig{ + MaxRequestBodySize: 1 << 20, + ReadHeaderTimeout: 5 * time.Second, + IdleTimeout: 60 * time.Second, + MaxRequestHeaderBytes: 1024, + }, + []model.FixtureSpec{ + newHTTPFixture( + http.MethodGet, + "/test", + nil, + nil, + nil, + http.StatusOK, + ), + }, + ) + + if err := service.Mount(t.Context()); err != nil { + t.Fatalf("Mount() error = %v", err) + } + + t.Cleanup(func() { + if err := service.Unmount(context.Background()); err != nil { + t.Errorf("Unmount() error = %v", err) + } + }) + + tests := []struct { + name string + header string + wantStatus int + }{ + { + name: "within limit", + header: "small", + wantStatus: http.StatusOK, + }, + { + name: "exceeds limit", + header: strings.Repeat("x", 16<<10), + wantStatus: http.StatusRequestHeaderFieldsTooLarge, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + req, err := http.NewRequestWithContext( + t.Context(), + http.MethodGet, + "http://"+service.GetRuntimeAddress()+"/test", + nil, + ) + if err != nil { + t.Fatal(err) + } + + req.Header.Set("X-Test", tt.header) + + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("Do() error = %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != tt.wantStatus { + t.Errorf( + "status = %d, want %d", + resp.StatusCode, + tt.wantStatus, + ) + } + }) + } +} + +func TestMockHTTPServiceUnmountClosesActiveRequest(t *testing.T) { + service := newTestMockHTTPService( + t, + []model.FixtureSpec{ + newHTTPFixture( + http.MethodPost, + "/test", + nil, + nil, + nil, + http.StatusOK, + ), + }, + ) + + if err := service.Mount(t.Context()); err != nil { + t.Fatalf("Mount() error = %v", err) + } + + defer func() { + _ = service.Unmount(context.Background()) + }() + + conn, err := net.DialTimeout( + "tcp", + service.GetRuntimeAddress(), + 5*time.Second, + ) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + + if err := conn.SetDeadline( + time.Now().Add(5 * time.Second), + ); err != nil { + t.Fatal(err) + } + + _, err = fmt.Fprintf( + conn, + "POST /test HTTP/1.1\r\n"+ + "Host: %s\r\n"+ + "Content-Length: 100\r\n"+ + "Expect: 100-continue\r\n"+ + "\r\n", + service.GetRuntimeAddress(), + ) + if err != nil { + t.Fatal(err) + } + + reader := bufio.NewReader(conn) + + // The server sends 100 Continue when the mock handler + // begins reading the request body. + interim, err := http.ReadResponse( + reader, + &http.Request{ + Method: http.MethodPost, + }, + ) + if err != nil { + t.Fatalf("ReadResponse() error = %v", err) + } + defer interim.Body.Close() + + if interim.StatusCode != http.StatusContinue { + t.Fatalf( + "status = %d, want %d", + interim.StatusCode, + http.StatusContinue, + ) + } + + // The request body remains incomplete. + // Graceful shutdown cannot finish while the handler + // is waiting for the remaining bytes. + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + err = service.Unmount(ctx) + + if err != nil && !errors.Is(err, context.Canceled) { + t.Fatalf( + "Unmount() unexpected error = %v", + err, + ) + } + + // Forced shutdown must terminate the active connection. + _, err = reader.ReadByte() + + if err == nil { + t.Error( + "active connection remained readable after shutdown", + ) + } else if ne, ok := err.(net.Error); ok && ne.Timeout() { + t.Errorf( + "active connection was not closed: %v", + err, + ) + } + + // The listener must also be closed. + newConn, err := net.DialTimeout( + "tcp", + service.GetRuntimeAddress(), + time.Second, + ) + if err == nil { + _ = newConn.Close() + t.Error( + "listener still accepts connections after unmount", + ) + } +} + +type failingRequestBody struct{} + +func (f *failingRequestBody) Read(_ []byte) (int, error) { + return 0, errors.New("simulated read failure") +} + +func (f *failingRequestBody) Close() error { + return nil +} + +func TestMockHTTPServiceRequestBodyReadError(t *testing.T) { + service := newTestMockHTTPService( + t, + []model.FixtureSpec{ + newHTTPFixture( + http.MethodPost, + "/test", + nil, + nil, + nil, + http.StatusOK, + ), + }, + ) + + req := httptest.NewRequest( + http.MethodPost, + "http://example.com/test", + nil, + ) + req.Body = &failingRequestBody{} + + recorder := httptest.NewRecorder() + + service.ServeHTTP(recorder, req) + + if recorder.Code != http.StatusBadRequest { + t.Errorf( + "expected status %d, got %d", + http.StatusBadRequest, + recorder.Code, + ) + } + + if recorder.Header().Get( + string(keys.E2EngineMockMissHeader), + ) == "true" { + t.Error("unexpected fixture mismatch header") + } +} + func newTestMockHTTPService( t *testing.T, fixtures []model.FixtureSpec, ) *httpservice.MockHTTPService { t.Helper() + return newTestMockHTTPServiceWithConfig( + t, + &httpservice.MockHTTPServiceConfig{ + MaxRequestBodySize: 1048576, + ReadHeaderTimeout: 5 * time.Second, + IdleTimeout: 60 * time.Second, + MaxRequestHeaderBytes: 1 << 20, + }, + fixtures, + ) +} + +func newTestMockHTTPServiceWithConfig( + t *testing.T, + cfg *httpservice.MockHTTPServiceConfig, + fixtures []model.FixtureSpec, +) *httpservice.MockHTTPService { + t.Helper() + logger, err := log.NewSilentLogger() if err != nil { - t.Fatalf( - "cannot create silent logger: %v", - err, - ) + t.Fatalf("cannot create silent logger: %v", err) } return httpservice.NewMockHTTPService( + cfg, logger, &model.ServiceSpec{ - ID: "service-1", - Kind: model.ServiceKindHTTP, - Mode: model.ServiceModeMocked, - Address: "127.0.0.1:8080", - Fixtures: fixtures, + ID: "service-1", + Kind: model.ServiceKindHTTP, + Mode: model.ServiceModeMocked, + E2EnginePort: 8080, + Fixtures: fixtures, }, ) } diff --git a/execute/runtime/service/http/real.go b/execute/runtime/service/http/real.go index 79a67ab..a64fbca 100644 --- a/execute/runtime/service/http/real.go +++ b/execute/runtime/service/http/real.go @@ -1,8 +1,10 @@ package http import ( + "bytes" "context" nativeerrors "errors" + "io" "net" "net/http" "net/http/httputil" @@ -16,27 +18,34 @@ import ( // RealHTTPService exposes a real HTTP service through an execution-local // runtime address. // -// ServiceSpec.Address is the logical address owned by EnvironmentRouter. // ServiceSpec.Target is the actual address of the real service. type RealHTTPService struct { + cfg *RealHTTPServiceConfig logger log.Logger spec *model.ServiceSpec + addressResolver addressResolver + server *http.Server + transport *http.Transport runtimeAddress string } func NewRealHTTPService( + cfg *RealHTTPServiceConfig, logger log.Logger, spec *model.ServiceSpec, + addressResolver addressResolver, ) (*RealHTTPService, error) { return &RealHTTPService{ + cfg: cfg, logger: logger.With( log.String(keys.EnvironmentServiceID, spec.ID), log.String(keys.EnvironmentServiceKind, string(spec.Kind)), log.String(keys.EnvironmentServiceMode, string(spec.Mode)), ), - spec: spec, + spec: spec, + addressResolver: addressResolver, }, nil } @@ -45,27 +54,35 @@ func (s *RealHTTPService) Mount(ctx context.Context) error { return err } - target, err := url.Parse(s.spec.HTTPTarget) + resolvedTarget, err := s.addressResolver.ResolveHTTPURL(s.spec.Target) if err != nil { return err } + target, err := url.Parse(resolvedTarget) + if err != nil { + return err + } + + transport := http.DefaultTransport.(*http.Transport).Clone() + + transport.ResponseHeaderTimeout = s.cfg.ResponseHeaderTimeout + transport.MaxResponseHeaderBytes = s.cfg.MaxResponseHeaderBytes + proxy := &httputil.ReverseProxy{ + Transport: transport, Rewrite: func(preq *httputil.ProxyRequest) { + // SetURL uses the resolved target hostname for the upstream Host header. + // Services using virtual-host routing may require the original logical + // hostname instead. Revisit Host/SNI handling if such services are supported. preq.SetURL(target) }, } - proxy.ErrorHandler = func( - w http.ResponseWriter, - req *http.Request, - proxyErr error, - ) { + proxy.ErrorHandler = func(w http.ResponseWriter, req *http.Request, _ error) { s.logger.Error( "Failed to proxy request to real service", log.String(keys.RequestMethod, req.Method), - log.String(keys.RequestURLPath, req.URL.Path), - log.Err(keys.Cause, proxyErr), ) http.Error( @@ -75,6 +92,47 @@ func (s *RealHTTPService) Mount(ctx context.Context) error { ) } + proxyHandler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + limit := s.cfg.MaxRequestBodySize + + // Reject requests whose declared body size exceeds the limit. + if req.ContentLength > limit { + http.Error( + w, + http.StatusText(http.StatusRequestEntityTooLarge), + http.StatusRequestEntityTooLarge, + ) + return + } + + // Read at most limit+1 bytes so requests without a known + // Content-Length are also subject to the size limit. + body, errRead := io.ReadAll(io.LimitReader(req.Body, limit+1)) + if errRead != nil { + http.Error( + w, + http.StatusText(http.StatusBadRequest), + http.StatusBadRequest, + ) + return + } + + if int64(len(body)) > limit { + http.Error( + w, + http.StatusText(http.StatusRequestEntityTooLarge), + http.StatusRequestEntityTooLarge, + ) + return + } + + // Restore the body for the reverse proxy. + req.Body = io.NopCloser(bytes.NewReader(body)) + req.ContentLength = int64(len(body)) + + proxy.ServeHTTP(w, req) + }) + listenerConfig := net.ListenConfig{} listener, err := listenerConfig.Listen( ctx, @@ -82,13 +140,18 @@ func (s *RealHTTPService) Mount(ctx context.Context) error { "127.0.0.1:0", ) if err != nil { + transport.CloseIdleConnections() return err } s.runtimeAddress = listener.Addr().String() + s.transport = transport s.server = &http.Server{ - Handler: proxy, + Handler: proxyHandler, + ReadHeaderTimeout: s.cfg.ReadHeaderTimeout, + IdleTimeout: s.cfg.IdleTimeout, + MaxHeaderBytes: s.cfg.MaxRequestHeaderBytes, } go func() { @@ -122,5 +185,17 @@ func (s *RealHTTPService) Unmount(ctx context.Context) error { return nil } - return s.server.Shutdown(ctx) + err := s.server.Shutdown(ctx) + if err != nil { + err = nativeerrors.Join( + err, + s.server.Close(), + ) + } + + if s.transport != nil { + s.transport.CloseIdleConnections() + } + + return err } diff --git a/execute/runtime/service/http/real_test.go b/execute/runtime/service/http/real_test.go index 859346c..6793973 100644 --- a/execute/runtime/service/http/real_test.go +++ b/execute/runtime/service/http/real_test.go @@ -1,14 +1,19 @@ -package http_test +package http import ( "context" + nativeerrors "errors" "io" + "net" "net/http" "net/http/httptest" "strings" + "sync/atomic" "testing" + "time" + + "go.uber.org/mock/gomock" - httpservice "github.com/e2engine/core/execute/runtime/service/http" "github.com/e2engine/core/model" "github.com/e2engine/core/pkg/log" ) @@ -209,6 +214,158 @@ func TestRealHTTPServiceProxy(t *testing.T) { } } +func TestRealHTTPServiceHostnameResolution(t *testing.T) { + upstream := httptest.NewServer( + http.HandlerFunc(func( + w http.ResponseWriter, + r *http.Request, + ) { + if r.URL.Path != "/health" { + t.Errorf( + "expected path %q, got %q", + "/health", + r.URL.Path, + ) + } + + w.WriteHeader(http.StatusNoContent) + }), + ) + defer upstream.Close() + + ctrl := gomock.NewController(t) + + resolver := NewMockaddressResolver(ctrl) + + resolver.EXPECT(). + ResolveHTTPURL("http://gateway-host:9000"). + Return(upstream.URL, nil) + + logger, err := log.NewSilentLogger() + if err != nil { + t.Fatalf("cannot create silent logger: %v", err) + } + defer logger.Close() + + service, err := NewRealHTTPService( + &RealHTTPServiceConfig{ + MaxRequestBodySize: 1 << 20, + ReadHeaderTimeout: 5 * time.Second, + IdleTimeout: 60 * time.Second, + MaxRequestHeaderBytes: 1 << 20, + ResponseHeaderTimeout: 30 * time.Second, + MaxResponseHeaderBytes: 1 << 20, + }, + logger, + &model.ServiceSpec{ + ID: "gateway", + Kind: model.ServiceKindHTTP, + Mode: model.ServiceModeReal, + E2EnginePort: 8083, + Target: "http://gateway-host:9000", + }, + resolver, + ) + if err != nil { + t.Fatalf("NewRealHTTPService() error = %v", err) + } + + if err := service.Mount(t.Context()); err != nil { + t.Fatalf("Mount() error = %v", err) + } + t.Cleanup(func() { + if err := service.Unmount(context.Background()); err != nil { + t.Errorf("Unmount() error = %v", err) + } + }) + + req, err := http.NewRequestWithContext( + t.Context(), + http.MethodGet, + "http://"+service.GetRuntimeAddress()+"/health", + nil, + ) + if err != nil { + t.Fatalf("cannot create request: %v", err) + } + + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("request error = %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusNoContent { + t.Errorf( + "expected status %d, got %d", + http.StatusNoContent, + resp.StatusCode, + ) + } +} + +func TestRealHTTPServiceMountAddressResolutionError(t *testing.T) { + ctrl := gomock.NewController(t) + + resolver := NewMockaddressResolver(ctrl) + + resolveErr := nativeerrors.New("cannot resolve HTTP target") + + resolver.EXPECT(). + ResolveHTTPURL("http://gateway-host:9000"). + Return("", resolveErr) + + logger, err := log.NewSilentLogger() + if err != nil { + t.Fatalf("cannot create silent logger: %v", err) + } + defer logger.Close() + + service, err := NewRealHTTPService( + &RealHTTPServiceConfig{ + MaxRequestBodySize: 1 << 20, + ReadHeaderTimeout: 5 * time.Second, + IdleTimeout: 60 * time.Second, + MaxRequestHeaderBytes: 1 << 20, + ResponseHeaderTimeout: 30 * time.Second, + MaxResponseHeaderBytes: 1 << 20, + }, + logger, + &model.ServiceSpec{ + ID: "gateway", + Kind: model.ServiceKindHTTP, + Mode: model.ServiceModeReal, + E2EnginePort: 8083, + Target: "http://gateway-host:9000", + }, + resolver, + ) + if err != nil { + t.Fatalf("NewRealHTTPService() error = %v", err) + } + + err = service.Mount(context.Background()) + + if !nativeerrors.Is(err, resolveErr) { + t.Errorf( + "expected error %v, got %v", + resolveErr, + err, + ) + } + + if service.server != nil { + t.Error("expected server not to be created") + } + + if service.GetRuntimeAddress() != "" { + t.Errorf( + "expected empty runtime address, got %q", + service.GetRuntimeAddress(), + ) + } +} + func TestRealHTTPServiceTargetHost(t *testing.T) { var targetHost string @@ -286,12 +443,7 @@ func TestRealHTTPServiceHTTPS(t *testing.T) { // httptest.NewTLSServer uses a test certificate which is not trusted // by the default transport used by ReverseProxy. // - // Replace the proxy target with a TLS server whose certificate is - // trusted by the process would turn this into a transport - // configuration test rather than a RealHTTPService test. - // - // Therefore this test documents the expected behavior of an - // untrusted HTTPS target: the proxy must return Bad Gateway. + // Therefore, the proxy should return Bad Gateway for this target. req, err := http.NewRequestWithContext( t.Context(), @@ -324,8 +476,7 @@ func TestRealHTTPServiceUpstreamUnavailable(t *testing.T) { w http.ResponseWriter, r *http.Request, ) { - }, - ), + }), ) target := upstream.URL @@ -408,29 +559,550 @@ func TestRealHTTPServiceUnmountBeforeMount(t *testing.T) { } } +func TestRealHTTPServiceRequestHeaderSizeLimit(t *testing.T) { + upstream := httptest.NewServer( + http.HandlerFunc(func( + w http.ResponseWriter, + _ *http.Request, + ) { + w.WriteHeader(http.StatusOK) + }), + ) + defer upstream.Close() + + service := newTestRealHTTPService(t, upstream.URL) + service.cfg.MaxRequestHeaderBytes = 1024 + + if err := service.Mount(t.Context()); err != nil { + t.Fatalf("Mount() error = %v", err) + } + + t.Cleanup(func() { + if err := service.Unmount(context.Background()); err != nil { + t.Errorf("Unmount() error = %v", err) + } + }) + + tests := []struct { + name string + header string + wantStatus int + }{ + { + name: "within limit", + header: "small", + wantStatus: http.StatusOK, + }, + { + name: "exceeds limit", + header: strings.Repeat("a", 16<<10), + wantStatus: http.StatusRequestHeaderFieldsTooLarge, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + req, err := http.NewRequestWithContext( + t.Context(), + http.MethodGet, + "http://"+service.GetRuntimeAddress()+"/test", + nil, + ) + if err != nil { + t.Fatal(err) + } + + req.Header.Set("X-Test", tt.header) + + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("Do() error = %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != tt.wantStatus { + t.Errorf( + "status = %d, want %d", + resp.StatusCode, + tt.wantStatus, + ) + } + }) + } +} + +func TestRealHTTPServiceResponseHeaderSizeLimit(t *testing.T) { + upstream := httptest.NewServer( + http.HandlerFunc(func( + w http.ResponseWriter, + req *http.Request, + ) { + if req.URL.Path == "/large" { + w.Header().Set( + "X-Large", + strings.Repeat("a", 4096), + ) + } else { + w.Header().Set("X-Small", "ok") + } + + w.WriteHeader(http.StatusOK) + }), + ) + defer upstream.Close() + + service := newTestRealHTTPService(t, upstream.URL) + service.cfg.MaxResponseHeaderBytes = 1024 + + if err := service.Mount(t.Context()); err != nil { + t.Fatalf("Mount() error = %v", err) + } + + t.Cleanup(func() { + if err := service.Unmount(context.Background()); err != nil { + t.Errorf("Unmount() error = %v", err) + } + }) + + tests := []struct { + name string + path string + wantStatus int + }{ + { + name: "within limit", + path: "/small", + wantStatus: http.StatusOK, + }, + { + name: "exceeds limit", + path: "/large", + wantStatus: http.StatusBadGateway, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + req, err := http.NewRequestWithContext( + t.Context(), + http.MethodGet, + "http://"+service.GetRuntimeAddress()+tt.path, + nil, + ) + if err != nil { + t.Fatal(err) + } + + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("Do() error = %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != tt.wantStatus { + t.Errorf( + "status = %d, want %d", + resp.StatusCode, + tt.wantStatus, + ) + } + }) + } +} + +func TestRealHTTPServiceResponseHeaderTimeout(t *testing.T) { + const ( + headerTimeout = 100 * time.Millisecond + delay = 300 * time.Millisecond + ) + + tests := []struct { + name string + delayBody bool + wantStatus int + wantBody string + }{ + { + name: "response headers timeout", + wantStatus: http.StatusBadGateway, + }, + { + name: "response body may arrive after timeout", + delayBody: true, + wantStatus: http.StatusOK, + wantBody: "delayed response", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + upstream := httptest.NewServer( + http.HandlerFunc(func( + w http.ResponseWriter, + req *http.Request, + ) { + if tt.delayBody { + w.WriteHeader(http.StatusOK) + + // Send response headers immediately. + w.(http.Flusher).Flush() + + time.Sleep(delay) + + _, _ = io.WriteString( + w, + "delayed response", + ) + + return + } + + // Wait for cancellation from the proxy's + // response-header timeout. + <-req.Context().Done() + }), + ) + defer upstream.Close() + + service := newTestRealHTTPService( + t, + upstream.URL, + ) + service.cfg.ResponseHeaderTimeout = headerTimeout + + if err := service.Mount(t.Context()); err != nil { + t.Fatalf("Mount() error = %v", err) + } + + defer func() { + if err := service.Unmount( + context.Background(), + ); err != nil { + t.Errorf("Unmount() error = %v", err) + } + }() + + req, err := http.NewRequestWithContext( + t.Context(), + http.MethodGet, + "http://"+service.GetRuntimeAddress()+"/test", + nil, + ) + if err != nil { + t.Fatal(err) + } + + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("Do() error = %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != tt.wantStatus { + t.Errorf( + "status = %d, want %d", + resp.StatusCode, + tt.wantStatus, + ) + } + + if tt.delayBody { + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatalf("ReadAll() error = %v", err) + } + + if string(body) != tt.wantBody { + t.Errorf( + "body = %q, want %q", + body, + tt.wantBody, + ) + } + } + }) + } +} + +func TestRealHTTPServiceUnmountClosesActiveRequest(t *testing.T) { + upstreamEntered := make(chan struct{}) + upstreamCanceled := make(chan struct{}) + + upstream := httptest.NewServer( + http.HandlerFunc(func( + w http.ResponseWriter, + req *http.Request, + ) { + close(upstreamEntered) + + <-req.Context().Done() + + close(upstreamCanceled) + }), + ) + defer upstream.Close() + + service := newTestRealHTTPService(t, upstream.URL) + + if err := service.Mount(t.Context()); err != nil { + t.Fatalf("Mount() error = %v", err) + } + + address := service.GetRuntimeAddress() + + client := &http.Client{ + Timeout: 5 * time.Second, + } + + requestDone := make(chan error, 1) + + go func() { + req, err := http.NewRequestWithContext( + t.Context(), + http.MethodGet, + "http://"+address+"/blocked", + nil, + ) + if err != nil { + requestDone <- err + return + } + + resp, err := client.Do(req) + if err == nil { + _ = resp.Body.Close() + + requestDone <- nativeerrors.New( + "request unexpectedly succeeded", + ) + return + } + + requestDone <- err + }() + + select { + case <-upstreamEntered: + case <-time.After(5 * time.Second): + t.Fatal("request did not reach upstream") + } + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + err := service.Unmount(ctx) + + if err != nil && !nativeerrors.Is(err, context.Canceled) { + t.Errorf( + "Unmount() error = %v, want nil or context.Canceled", + err, + ) + } + + select { + case <-requestDone: + case <-time.After(5 * time.Second): + t.Error("active client request did not terminate") + } + + select { + case <-upstreamCanceled: + case <-time.After(5 * time.Second): + t.Error("upstream request was not canceled") + } + + conn, err := net.DialTimeout( + "tcp", + address, + time.Second, + ) + if err == nil { + _ = conn.Close() + + t.Error( + "listener still accepts connections after unmount", + ) + } +} + +func TestRealHTTPServiceRequestBodySizeLimit(t *testing.T) { + const limit = int64(16) + + var upstreamCalls atomic.Int32 + + upstream := httptest.NewServer( + http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + upstreamCalls.Add(1) + + body, err := io.ReadAll(r.Body) + if err != nil { + t.Errorf("upstream ReadAll() error = %v", err) + w.WriteHeader(http.StatusInternalServerError) + return + } + + w.WriteHeader(http.StatusOK) + _, _ = w.Write(body) + }), + ) + defer upstream.Close() + + service := newTestRealHTTPService(t, upstream.URL) + service.cfg.MaxRequestBodySize = limit + + if err := service.Mount(t.Context()); err != nil { + t.Fatalf("Mount() error = %v", err) + } + + t.Cleanup(func() { + if err := service.Unmount(context.Background()); err != nil { + t.Errorf("Unmount() error = %v", err) + } + }) + + tests := []struct { + name string + body string + chunked bool + wantStatus int + wantForwarded bool + }{ + { + name: "below limit", + body: strings.Repeat("a", int(limit)-1), + wantStatus: http.StatusOK, + wantForwarded: true, + }, + { + name: "exactly at limit", + body: strings.Repeat("a", int(limit)), + wantStatus: http.StatusOK, + wantForwarded: true, + }, + { + name: "known length exceeds limit", + body: strings.Repeat("a", int(limit)+1), + wantStatus: http.StatusRequestEntityTooLarge, + }, + { + name: "chunked within limit", + body: strings.Repeat("a", int(limit)), + chunked: true, + wantStatus: http.StatusOK, + wantForwarded: true, + }, + { + name: "chunked exceeds limit", + body: strings.Repeat("a", int(limit)+1), + chunked: true, + wantStatus: http.StatusRequestEntityTooLarge, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + before := upstreamCalls.Load() + + req, err := http.NewRequestWithContext( + t.Context(), + http.MethodPost, + "http://"+service.GetRuntimeAddress()+"/upload", + strings.NewReader(tt.body), + ) + if err != nil { + t.Fatal(err) + } + + if tt.chunked { + req.ContentLength = -1 + } + + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("Do() error = %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != tt.wantStatus { + t.Errorf( + "status = %d, want %d", + resp.StatusCode, + tt.wantStatus, + ) + } + + responseBody, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatalf("ReadAll() error = %v", err) + } + + if tt.wantForwarded && string(responseBody) != tt.body { + t.Errorf( + "body = %q, want %q", + responseBody, + tt.body, + ) + } + + wantCalls := before + if tt.wantForwarded { + wantCalls++ + } + + if got := upstreamCalls.Load(); got != wantCalls { + t.Errorf( + "upstream calls = %d, want %d", + got, + wantCalls, + ) + } + }) + } +} + func newTestRealHTTPService( t *testing.T, target string, -) *httpservice.RealHTTPService { +) *RealHTTPService { t.Helper() logger, err := log.NewSilentLogger() if err != nil { - t.Fatalf( - "cannot create silent logger: %v", - err, - ) + t.Fatalf("cannot create silent logger: %v", err) } + t.Cleanup(func() { + if err := logger.Close(); err != nil { + t.Errorf("Close() error = %v", err) + } + }) + + ctrl := gomock.NewController(t) + + resolver := NewMockaddressResolver(ctrl) - service, err := httpservice.NewRealHTTPService( + resolver.EXPECT(). + ResolveHTTPURL(target). + Return(target, nil). + AnyTimes() + + service, err := NewRealHTTPService( + &RealHTTPServiceConfig{ + MaxRequestBodySize: 1 << 20, + ReadHeaderTimeout: 5 * time.Second, + IdleTimeout: 60 * time.Second, + MaxRequestHeaderBytes: 1 << 20, + ResponseHeaderTimeout: 30 * time.Second, + MaxResponseHeaderBytes: 1 << 20, + }, logger, &model.ServiceSpec{ - ID: "service-1", - Kind: model.ServiceKindHTTP, - Mode: model.ServiceModeReal, - Address: "service:8080", - HTTPTarget: target, + ID: "service-1", + Kind: model.ServiceKindHTTP, + Mode: model.ServiceModeReal, + E2EnginePort: 8080, + Target: target, }, + resolver, ) if err != nil { t.Fatalf( diff --git a/execute/runtime/service/mock_address_resolver_test.go b/execute/runtime/service/mock_address_resolver_test.go new file mode 100644 index 0000000..249b332 --- /dev/null +++ b/execute/runtime/service/mock_address_resolver_test.go @@ -0,0 +1,70 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: address_resolver.go +// +// Generated by this command: +// +// mockgen -source=address_resolver.go -destination=mock_address_resolver_test.go -package=service +// + +// Package service is a generated GoMock package. +package service + +import ( + reflect "reflect" + + gomock "go.uber.org/mock/gomock" +) + +// MockaddressResolver is a mock of addressResolver interface. +type MockaddressResolver struct { + ctrl *gomock.Controller + recorder *MockaddressResolverMockRecorder + isgomock struct{} +} + +// MockaddressResolverMockRecorder is the mock recorder for MockaddressResolver. +type MockaddressResolverMockRecorder struct { + mock *MockaddressResolver +} + +// NewMockaddressResolver creates a new mock instance. +func NewMockaddressResolver(ctrl *gomock.Controller) *MockaddressResolver { + mock := &MockaddressResolver{ctrl: ctrl} + mock.recorder = &MockaddressResolverMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockaddressResolver) EXPECT() *MockaddressResolverMockRecorder { + return m.recorder +} + +// ResolveGRPCTarget mocks base method. +func (m *MockaddressResolver) ResolveGRPCTarget(value string) (string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ResolveGRPCTarget", value) + ret0, _ := ret[0].(string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ResolveGRPCTarget indicates an expected call of ResolveGRPCTarget. +func (mr *MockaddressResolverMockRecorder) ResolveGRPCTarget(value any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ResolveGRPCTarget", reflect.TypeOf((*MockaddressResolver)(nil).ResolveGRPCTarget), value) +} + +// ResolveHTTPURL mocks base method. +func (m *MockaddressResolver) ResolveHTTPURL(value string) (string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ResolveHTTPURL", value) + ret0, _ := ret[0].(string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ResolveHTTPURL indicates an expected call of ResolveHTTPURL. +func (mr *MockaddressResolverMockRecorder) ResolveHTTPURL(value any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ResolveHTTPURL", reflect.TypeOf((*MockaddressResolver)(nil).ResolveHTTPURL), value) +} diff --git a/execute/runtime/service/service.go b/execute/runtime/service/service.go index 1bb5d41..6c14cf6 100644 --- a/execute/runtime/service/service.go +++ b/execute/runtime/service/service.go @@ -13,19 +13,17 @@ import ( ) type Provider struct { - cfg *config.ProviderConfig + cfg *config.ServiceConfig logger log.Logger grpcMethodResolver grpcservice.MethodResolver + addressResolver addressResolver } func NewProvider( - cfg *config.ProviderConfig, + cfg *config.ServiceConfig, logger log.Logger, + addressResolver addressResolver, ) *Provider { - if cfg == nil { - cfg = &config.ProviderConfig{} - } - client := http.DefaultClient // TODO: make it configurable. descriptorLoader := grpcservice.NewBufDescriptorLoader( @@ -41,6 +39,7 @@ func NewProvider( cfg: cfg, logger: logger, grpcMethodResolver: methodResolver, + addressResolver: addressResolver, } } @@ -55,6 +54,7 @@ func (p *Provider) GetService( case spec.Kind == model.ServiceKindHTTP && spec.Mode == model.ServiceModeMocked: return httpservice.NewMockHTTPService( + p.cfg.MockHTTP, p.logger, spec, ), nil @@ -62,13 +62,16 @@ func (p *Provider) GetService( case spec.Kind == model.ServiceKindHTTP && spec.Mode == model.ServiceModeReal: return httpservice.NewRealHTTPService( + p.cfg.RealHTTP, p.logger, spec, + p.addressResolver, ) case spec.Kind == model.ServiceKindGRPC && spec.Mode == model.ServiceModeMocked: return grpcservice.NewMockGRPCService( + p.cfg.MockGRPC, p.logger, spec, p.grpcMethodResolver, @@ -77,8 +80,10 @@ func (p *Provider) GetService( case spec.Kind == model.ServiceKindGRPC && spec.Mode == model.ServiceModeReal: return grpcservice.NewRealGRPCService( + p.cfg.RealGRPC, p.logger, spec, + p.addressResolver, ) default: diff --git a/execute/runtime/service/service_test.go b/execute/runtime/service/service_test.go index 216f814..6126bf0 100644 --- a/execute/runtime/service/service_test.go +++ b/execute/runtime/service/service_test.go @@ -1,11 +1,16 @@ -package service_test +package service import ( + "context" + "net/http" + "net/http/httptest" "reflect" "testing" + "time" + + "go.uber.org/mock/gomock" "github.com/e2engine/core/execute/runtime/config" - "github.com/e2engine/core/execute/runtime/service" grpcservice "github.com/e2engine/core/execute/runtime/service/grpc" httpservice "github.com/e2engine/core/execute/runtime/service/http" "github.com/e2engine/core/model" @@ -16,14 +21,11 @@ import ( func TestNewProvider(t *testing.T) { tests := []struct { name string - cfg *config.ProviderConfig + cfg *config.ServiceConfig }{ - { - name: "nil config", - }, { name: "config", - cfg: &config.ProviderConfig{ + cfg: &config.ServiceConfig{ BufDescriptorLoaderToken: "token", }, }, @@ -31,7 +33,7 @@ func TestNewProvider(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - provider := service.NewProvider(tt.cfg, nil) + provider := NewProvider(tt.cfg, nil, nil) if provider == nil { t.Fatal("expected provider") @@ -88,7 +90,14 @@ func TestProvider_GetService(t *testing.T) { if err != nil { t.Fatalf("Unexpected NewSilentLogger error: %q", err) } - provider := service.NewProvider(nil, logger) + + cfg := &config.ServiceConfig{ + MockHTTP: &httpservice.MockHTTPServiceConfig{ + MaxRequestBodySize: 1048576, + }, + } + + provider := NewProvider(cfg, logger, nil) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -136,7 +145,13 @@ func TestProvider_GetService_InvalidConfiguration(t *testing.T) { }, } - provider := service.NewProvider(nil, nil) + cfg := &config.ServiceConfig{ + MockHTTP: &httpservice.MockHTTPServiceConfig{ + MaxRequestBodySize: 1048576, + }, + } + + provider := NewProvider(cfg, nil, nil) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -158,3 +173,96 @@ func TestProvider_GetService_InvalidConfiguration(t *testing.T) { }) } } + +func TestProvider_GetService_AddressResolver(t *testing.T) { + upstream := httptest.NewServer( + http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/health" { + t.Errorf( + "expected path /health, got %q", + r.URL.Path, + ) + } + + w.WriteHeader(http.StatusNoContent) + }), + ) + defer upstream.Close() + + logger, err := log.NewSilentLogger() + if err != nil { + t.Fatalf("NewSilentLogger() error = %v", err) + } + defer logger.Close() + + ctrl := gomock.NewController(t) + + resolver := NewMockaddressResolver(ctrl) + + resolver.EXPECT(). + ResolveHTTPURL("http://gateway-host:9000"). + Return(upstream.URL, nil) + + cfg := &config.ServiceConfig{ + MockHTTP: &httpservice.MockHTTPServiceConfig{ + MaxRequestBodySize: 1048576, + }, + RealHTTP: &httpservice.RealHTTPServiceConfig{ + ResponseHeaderTimeout: 5 * time.Second, + MaxResponseHeaderBytes: 1048576, + }, + } + + provider := NewProvider( + cfg, + logger, + resolver, + ) + + created, err := provider.GetService(&model.ServiceSpec{ + ID: "gateway", + Kind: model.ServiceKindHTTP, + Mode: model.ServiceModeReal, + E2EnginePort: 8083, + Target: "http://gateway-host:9000", + }) + if err != nil { + t.Fatalf("GetService() error = %v", err) + } + + ctx := t.Context() + + if err := created.Mount(ctx); err != nil { + t.Fatalf("Mount() error = %v", err) + } + + defer func() { + if err := created.Unmount(context.Background()); err != nil { + t.Errorf("Unmount() error = %v", err) + } + }() + + req, err := http.NewRequestWithContext( + ctx, + http.MethodGet, + "http://"+created.GetRuntimeAddress()+"/health", + nil, + ) + if err != nil { + t.Fatalf("NewRequestWithContext() error = %v", err) + } + + resp, err := upstream.Client().Do(req) + if err != nil { + t.Fatalf("Do() error = %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusNoContent { + t.Errorf( + "expected status %d, got %d", + http.StatusNoContent, + resp.StatusCode, + ) + } +} diff --git a/execute/worker/address_resolver.go b/execute/worker/address_resolver.go new file mode 100644 index 0000000..26186b0 --- /dev/null +++ b/execute/worker/address_resolver.go @@ -0,0 +1,8 @@ +package worker + +type addressResolver interface { + ResolveHTTPURL(value string) (string, error) + ResolveGRPCTarget(value string) (string, error) +} + +//go:generate go run -mod=mod go.uber.org/mock/mockgen -source=address_resolver.go -destination=mock_address_resolver_test.go -package=worker diff --git a/execute/worker/config.go b/execute/worker/config.go new file mode 100644 index 0000000..f8f1354 --- /dev/null +++ b/execute/worker/config.go @@ -0,0 +1,21 @@ +package worker + +import ( + "time" + + grpcworker "github.com/e2engine/core/execute/worker/grpc" + httpworker "github.com/e2engine/core/execute/worker/http" + reporterPkg "github.com/e2engine/core/execute/worker/reporter" +) + +type Config struct { + TestTimeout time.Duration `json:"test_timeout" yaml:"test_timeout" env:"TEST_TIMEOUT" default:"30s" validate:"min(1s)"` + + HTTPMaxRedirects int `json:"http_max_redirects" yaml:"http_max_redirects" env:"HTTP_MAX_REDIRECTS" default:"0" validate:"min(0),max(10)"` + + HTTPMaxResponseHeaderBytes int64 `json:"http_max_response_header_bytes" yaml:"http_max_response_header_bytes" env:"HTTP_MAX_RESPONSE_HEADER_BYTES" default:"1048576" validate:"min(1024),max(16777216)"` + + HTTPEvaluator *httpworker.EvaluatorConfig `json:"http_evaluator" yaml:"http_evaluator" env:"HTTP_EVALUATOR" default:"dive"` + GRPCExecutor *grpcworker.ExecutorConfig `json:"grpc_executor" yaml:"grpc_executor" env:"GRPC_EXECUTOR" default:"dive"` + Reporter *reporterPkg.Config `json:"reporter" yaml:"reporter" env:"REPORTER"` +} diff --git a/execute/worker/evaluator/evaluator_test.go b/execute/worker/evaluator/evaluator_test.go index 5558527..18f307f 100644 --- a/execute/worker/evaluator/evaluator_test.go +++ b/execute/worker/evaluator/evaluator_test.go @@ -9,6 +9,7 @@ import ( "github.com/e2engine/core/execute/call" "github.com/e2engine/core/model" + errorsPkg "github.com/e2engine/core/pkg/errors" ) func TestEvaluatorEvaluateCalls(t *testing.T) { @@ -38,19 +39,27 @@ func TestEvaluatorEvaluateCalls(t *testing.T) { reporter, ) - calls := &call.Store{} + calls := call.NewStoreFactory( + &call.Config{ + MaxCalls: 1000, + MaxRecordedBytes: 1024 * 1024, + }).New() - calls.Record(call.Call{ + if errRecord := calls.Record(call.Call{ TestExecutionID: "execution-1", ServiceID: "http-service", HTTP: &call.HTTPCall{}, - }) + }); errRecord != nil { + t.Fatalf("failed to record call: %v", errRecord) + } - calls.Record(call.Call{ + if errRecord := calls.Record(call.Call{ TestExecutionID: "execution-1", ServiceID: "grpc-service", GRPC: &call.GRPCCall{}, - }) + }); errRecord != nil { + t.Fatalf("failed to record call: %v", errRecord) + } gomock.InOrder( reporter.EXPECT().AddDeviation(httpEvaluator.deviation), @@ -151,33 +160,45 @@ func TestEvaluatorEvaluateActualCalls(t *testing.T) { reporter, ) - calls := &call.Store{} + calls := call.NewStoreFactory( + &call.Config{ + MaxCalls: 1000, + MaxRecordedBytes: 1024 * 1024, + }).New() - calls.Record(call.Call{ + if errRecord := calls.Record(call.Call{ TestExecutionID: "execution-1", ServiceID: "http-service", HTTP: &call.HTTPCall{}, - }) + }); errRecord != nil { + t.Fatalf("failed to record call: %v", errRecord) + } - calls.Record(call.Call{ + if errRecord := calls.Record(call.Call{ TestExecutionID: "execution-1", ServiceID: "grpc-service", GRPC: &call.GRPCCall{}, - }) + }); errRecord != nil { + t.Fatalf("failed to record call: %v", errRecord) + } // Must not be evaluated because the service is not mocked. - calls.Record(call.Call{ + if errRecord := calls.Record(call.Call{ TestExecutionID: "execution-1", ServiceID: "real-service", HTTP: &call.HTTPCall{}, - }) + }); errRecord != nil { + t.Fatalf("failed to record call: %v", errRecord) + } // Must not be evaluated because it belongs to another execution. - calls.Record(call.Call{ + if errRecord := calls.Record(call.Call{ TestExecutionID: "execution-2", ServiceID: "http-service", HTTP: &call.HTTPCall{}, - }) + }); errRecord != nil { + t.Fatalf("failed to record call: %v", errRecord) + } gomock.InOrder( reporter.EXPECT().AddDeviation(httpEvaluator.deviation), @@ -235,13 +256,19 @@ func TestEvaluatorEvaluateActualCallsNoDeviation( reporter, ) - calls := &call.Store{} + calls := call.NewStoreFactory( + &call.Config{ + MaxCalls: 1000, + MaxRecordedBytes: 1024 * 1024, + }).New() - calls.Record(call.Call{ + if errRecord := calls.Record(call.Call{ TestExecutionID: "execution-1", ServiceID: "service-1", HTTP: &call.HTTPCall{}, - }) + }); errRecord != nil { + t.Fatalf("failed to record call: %v", errRecord) + } evaluator.evaluateActualCalls( []model.ServiceSpec{ @@ -269,13 +296,19 @@ func TestEvaluatorEvaluateActualCallsUnsupportedServiceKind( reporter, ) - calls := &call.Store{} + calls := call.NewStoreFactory( + &call.Config{ + MaxCalls: 1000, + MaxRecordedBytes: 1024 * 1024, + }).New() - calls.Record(call.Call{ + if errRecord := calls.Record(call.Call{ TestExecutionID: "execution-1", ServiceID: "unsupported-service", HTTP: &call.HTTPCall{}, - }) + }); errRecord != nil { + t.Fatalf("failed to record call: %v", errRecord) + } defer func() { if recover() == nil { @@ -399,14 +432,20 @@ func TestEvaluatorEvaluateExpectedCalls(t *testing.T) { reporter, ) - calls := &call.Store{} + calls := call.NewStoreFactory( + &call.Config{ + MaxCalls: 1000, + MaxRecordedBytes: 1024 * 1024, + }).New() for range tt.calls { - calls.Record(call.Call{ + if errRecord := calls.Record(call.Call{ TestExecutionID: "execution-1", ServiceID: "service-1", HTTP: &call.HTTPCall{}, - }) + }); errRecord != nil { + t.Fatalf("failed to record call: %v", errRecord) + } } if tt.expectedDeviation != nil { @@ -461,13 +500,19 @@ func TestEvaluatorEvaluateExpectedCallsError( reporter, ) - calls := &call.Store{} + calls := call.NewStoreFactory( + &call.Config{ + MaxCalls: 1000, + MaxRecordedBytes: 1024 * 1024, + }).New() - calls.Record(call.Call{ + if errRecord := calls.Record(call.Call{ TestExecutionID: "execution-1", ServiceID: "service-1", HTTP: &call.HTTPCall{}, - }) + }); errRecord != nil { + t.Fatalf("failed to record call: %v", errRecord) + } err := evaluator.evaluateExpectedCalls( context.Background(), @@ -643,6 +688,76 @@ func TestEvaluatorMatchesError(t *testing.T) { } } +func TestEvaluatorEvaluateCallsTruncatedHTTPBody(t *testing.T) { + expectedErr := errorsPkg.ErrHTTPRecordedRequestBodyTruncated + + ctrl := gomock.NewController(t) + reporter := NewMockdeviationReporter(ctrl) + + httpEvaluator := &testCallEvaluator{ + matchesErr: expectedErr, + } + + evaluator := New( + httpEvaluator, + &testCallEvaluator{}, + reporter, + ) + + calls := call.NewStoreFactory( + &call.Config{ + MaxCalls: 1000, + MaxRecordedBytes: 1024 * 1024, + }).New() + + if errRecord := calls.Record(call.Call{ + TestExecutionID: "execution-1", + ServiceID: "http-service", + HTTP: &call.HTTPCall{ + Request: call.HTTPRequest{ + Method: "POST", + Body: []byte("partial"), + BodyTruncated: true, + BodyComplete: true, + }, + }, + }); errRecord != nil { + t.Fatalf("failed to record call: %v", errRecord) + } + + err := evaluator.EvaluateCalls( + context.Background(), + []model.ServiceSpec{ + { + ID: "http-service", + Kind: model.ServiceKindHTTP, + }, + }, + []model.ServiceExpectedCalls{ + { + ServiceID: "http-service", + HTTP: &model.HTTPRequestPattern{}, + }, + }, + calls, + "execution-1", + ) + + if !errors.Is(err, expectedErr) { + t.Fatalf( + "expected ErrHTTPRecordedRequestBodyTruncated, got %v", + err, + ) + } + + if httpEvaluator.matchesCalls != 1 { + t.Errorf( + "expected Matches() to be called once, got %d", + httpEvaluator.matchesCalls, + ) + } +} + type testCallEvaluator struct { matches bool matchesErr error diff --git a/execute/worker/grpc/address_resolver.go b/execute/worker/grpc/address_resolver.go new file mode 100644 index 0000000..d0d0c1c --- /dev/null +++ b/execute/worker/grpc/address_resolver.go @@ -0,0 +1,7 @@ +package grpc + +type addressResolver interface { + ResolveGRPCTarget(value string) (string, error) +} + +//go:generate go run -mod=mod go.uber.org/mock/mockgen -source=address_resolver.go -destination=mock_address_resolver_test.go -package=grpc diff --git a/execute/worker/grpc/config.go b/execute/worker/grpc/config.go new file mode 100644 index 0000000..c7bdb8b --- /dev/null +++ b/execute/worker/grpc/config.go @@ -0,0 +1,5 @@ +package grpc + +type ExecutorConfig struct { + MaxMessageSize int `json:"max_message_size" yaml:"max_message_size" default:"4194304" validate:"min(1),max(67108864)"` +} diff --git a/execute/worker/grpc/evaluate.go b/execute/worker/grpc/evaluate.go index 9f8256e..dcecb59 100644 --- a/execute/worker/grpc/evaluate.go +++ b/execute/worker/grpc/evaluate.go @@ -18,7 +18,6 @@ import ( "github.com/e2engine/core/execute/match" servicegrpc "github.com/e2engine/core/execute/runtime/service/grpc" "github.com/e2engine/core/execute/worker/evaluator" - "github.com/e2engine/core/internal/util" "github.com/e2engine/core/model" "github.com/e2engine/core/pkg/keys" ) @@ -116,11 +115,14 @@ func (e *Evaluator) evaluateMetadata( } slices.Sort(expectedStrings) - e.reporter.AddDeviation(&model.TestExecutionDeviation{ - Field: "metadata." + key, - Expected: strings.Join(expectedStrings, ","), - Actual: strings.Join(sortedActual, ","), - }) + e.reporter.AddMetadataDeviation( + key, + &model.TestExecutionDeviation{ + Field: "metadata." + key, + Expected: strings.Join(expectedStrings, ","), + Actual: strings.Join(sortedActual, ","), + }, + ) } return nil @@ -293,8 +295,7 @@ func mergeMetadata( ) for key, values := range header { - result[key] = - util.CloneStringSlice(values) + result[key] = slices.Clone(values) } for key, values := range trailer { diff --git a/execute/worker/grpc/evaluate_test.go b/execute/worker/grpc/evaluate_test.go index 83c1536..44fba3e 100644 --- a/execute/worker/grpc/evaluate_test.go +++ b/execute/worker/grpc/evaluate_test.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "reflect" + "strings" "testing" "go.uber.org/mock/gomock" @@ -316,8 +317,18 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { AddGRPCResponseStatus(tt.expectedStatus) for i := range tt.expectedDeviations { - reporter.EXPECT(). - AddDeviation(&tt.expectedDeviations[i]) + deviation := &tt.expectedDeviations[i] + + if strings.HasPrefix(deviation.Field, "metadata.") { + reporter.EXPECT(). + AddMetadataDeviation( + strings.TrimPrefix(deviation.Field, "metadata."), + deviation, + ) + } else { + reporter.EXPECT(). + AddDeviation(deviation) + } } expectedMetadata := mergeMetadata( @@ -992,7 +1003,8 @@ func newTestEvaluator( func testServiceSpec() *model.ServiceSpec { return &model.ServiceSpec{ - ID: "service-1", + ID: "service-1", + Kind: model.ServiceKindGRPC, Proto: &model.GRPCProtoSpec{ Internal: &model.GRPCInternalProtoSpec{ Package: "users", diff --git a/execute/worker/grpc/executor.go b/execute/worker/grpc/executor.go index dc79ff3..cfc362b 100644 --- a/execute/worker/grpc/executor.go +++ b/execute/worker/grpc/executor.go @@ -10,6 +10,7 @@ import ( "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/metadata" "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/dynamicpb" "github.com/e2engine/core/execute" @@ -20,20 +21,26 @@ import ( ) type TestExecutor struct { - resolver servicegrpc.MethodResolver - evaluator *Evaluator - reporter executionReporter + cfg *ExecutorConfig + resolver servicegrpc.MethodResolver + evaluator *Evaluator + reporter executionReporter + addressResolver addressResolver } func NewTestExecutor( + cfg *ExecutorConfig, resolver servicegrpc.MethodResolver, evaluator *Evaluator, reporter executionReporter, + addressResolver addressResolver, ) *TestExecutor { return &TestExecutor{ - resolver: resolver, - evaluator: evaluator, - reporter: reporter, + cfg: cfg, + resolver: resolver, + evaluator: evaluator, + reporter: reporter, + addressResolver: addressResolver, } } @@ -43,17 +50,24 @@ func (e *TestExecutor) Execute( ) error { spec := job.Test.Spec.Request.GRPC - service, err := findService( - job.Environment.Spec.Services, - spec.Target, - ) - if err != nil { - return err + protoSpec := spec.Proto + + if protoSpec == nil { + // TODO: for standalone test, return an error is no proto spec is provided. + + var err error + protoSpec, err = findProtoSpec( + job.Environment.Spec.Services, + spec.Service, + ) + if err != nil { + return err + } } method, err := e.resolver.ResolveMethod( ctx, - service.Proto, + protoSpec, spec.Method, ) if err != nil { @@ -74,11 +88,24 @@ func (e *TestExecutor) Execute( ) } + if proto.Size(request) > e.cfg.MaxMessageSize { + return errors.ErrGRPCRequestMessageTooLarge + } + + resolvedTarget, err := e.addressResolver.ResolveGRPCTarget(spec.Target) + if err != nil { + return err + } + connection, err := ggrpc.NewClient( - spec.Target, + resolvedTarget, ggrpc.WithTransportCredentials( insecure.NewCredentials(), ), + ggrpc.WithDefaultCallOptions( + ggrpc.MaxCallRecvMsgSize(e.cfg.MaxMessageSize), + ggrpc.MaxCallSendMsgSize(e.cfg.MaxMessageSize), + ), ) if err != nil { return err @@ -101,7 +128,7 @@ func (e *TestExecutor) Execute( var trailer metadata.MD r := &model.GRPCRequest{ - Target: spec.Target, + Target: resolvedTarget, Service: spec.Service, Method: spec.Method, Metadata: callMetadata, @@ -110,6 +137,8 @@ func (e *TestExecutor) Execute( e.reporter.AddGRPCRequest(r) + // TODO: distinguish local gRPC receive-message size limit errors + // from ResourceExhausted status returned by the remote service. callErr := connection.Invoke( callCtx, "/"+spec.Service+"/"+spec.Method, @@ -128,20 +157,54 @@ func (e *TestExecutor) Execute( ) } -func findService( +func findProtoSpec( services []model.ServiceSpec, - target string, -) (*model.ServiceSpec, error) { + serviceName string, +) (*model.GRPCProtoSpec, error) { + var found *model.GRPCProtoSpec + for i := range services { - if services[i].Address == target { - return &services[i], nil + service := &services[i] + + if service.Kind != model.ServiceKindGRPC || service.Proto == nil { + continue + } + + var name string + + switch { + case service.Proto.External != nil: + name = service.Proto.External.Service + + case service.Proto.Internal != nil: + internal := service.Proto.Internal + + name = internal.Service + if internal.Package != "" { + name = internal.Package + "." + internal.Service + } + } + + if name != serviceName { + continue } + + if found != nil { + return nil, errorc.New( + "multiple protobuf specifications match gRPC service", + ) + } + + found = service.Proto } - return nil, errorc.With( - errors.ErrGRPCTargetServiceNotFound, - errorc.String(keys.GRPCServiceTargetAddress, target), - ) + if found == nil { + return nil, errorc.New( + "protobuf specification not found for gRPC service", + ) + } + + return found, nil } func unmarshalMap( diff --git a/execute/worker/grpc/executor_test.go b/execute/worker/grpc/executor_test.go index c4aa36f..65a92ad 100644 --- a/execute/worker/grpc/executor_test.go +++ b/execute/worker/grpc/executor_test.go @@ -6,6 +6,7 @@ import ( "errors" "net" "reflect" + "strings" "testing" e2enginegrpc "github.com/e2engine/instrumentation-go/grpc" @@ -21,58 +22,57 @@ import ( servicegrpc "github.com/e2engine/core/execute/runtime/service/grpc" "github.com/e2engine/core/model" "github.com/e2engine/core/model/matcher" - coreerrors "github.com/e2engine/core/pkg/errors" + pkgerrors "github.com/e2engine/core/pkg/errors" ) -func TestFindService(t *testing.T) { - services := []model.ServiceSpec{ +func TestFindProtoSpec(t *testing.T) { + service := testServiceSpec() + + tests := []struct { + name string + services []model.ServiceSpec + nameToFind string + wantErr bool + }{ { - ID: "service-1", - Address: "localhost:50051", + name: "found", + services: []model.ServiceSpec{*service}, + nameToFind: "users.UserService", }, { - ID: "service-2", - Address: "localhost:50052", + name: "not found", + services: []model.ServiceSpec{*service}, + nameToFind: "users.MissingService", + wantErr: true, }, - } - - tests := []struct { - name string - target string - expected *model.ServiceSpec - err error - }{ { - name: "found", - target: "localhost:50052", - expected: &services[1], + name: "ambiguous", + services: []model.ServiceSpec{*service, *service}, + nameToFind: "users.UserService", + wantErr: true, }, { - name: "not found", - target: "localhost:50053", - err: coreerrors.ErrGRPCTargetServiceNotFound, + name: "empty services", + nameToFind: "users.UserService", + wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - actual, err := findService( - services, - tt.target, + actual, err := findProtoSpec( + tt.services, + tt.nameToFind, ) - if tt.err != nil { - if !errors.Is(err, tt.err) { - t.Fatalf( - "expected error %v, got %v", - tt.err, - err, - ) + if tt.wantErr { + if err == nil { + t.Fatal("expected error") } if actual != nil { t.Errorf( - "expected nil service, got %+v", + "expected nil proto specification, got %+v", actual, ) } @@ -81,16 +81,13 @@ func TestFindService(t *testing.T) { } if err != nil { - t.Fatalf( - "findService() error = %v", - err, - ) + t.Fatalf("findProtoSpec() error = %v", err) } - if actual != tt.expected { + if !reflect.DeepEqual(actual, service.Proto) { t.Errorf( - "expected service %+v, got %+v", - tt.expected, + "expected proto specification %+v, got %+v", + service.Proto, actual, ) } @@ -143,9 +140,7 @@ func TestUnmarshalMap(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - message := dynamicpb.NewMessage( - descriptor, - ) + message := dynamicpb.NewMessage(descriptor) err := unmarshalMap( tt.value, @@ -156,15 +151,11 @@ func TestUnmarshalMap(t *testing.T) { if err == nil { t.Fatal("expected error") } - return } if err != nil { - t.Fatalf( - "unmarshalMap() error = %v", - err, - ) + t.Fatalf("unmarshalMap() error = %v", err) } if tt.value == nil { @@ -287,9 +278,9 @@ func int32Ptr(value int32) *int32 { func TestExecutorExecute(t *testing.T) { service := testServiceSpec() - resolver := servicegrpc.NewProtoMethodResolver(nil) + methodResolver := servicegrpc.NewProtoMethodResolver(nil) - method, err := resolver.ResolveMethod( + method, err := methodResolver.ResolveMethod( context.Background(), service.Proto, "Create", @@ -308,10 +299,7 @@ func TestExecutorExecute(t *testing.T) { "127.0.0.1:0", ) if err != nil { - t.Fatalf( - "listen: %v", - err, - ) + t.Fatalf("listen: %v", err) } defer listener.Close() @@ -325,9 +313,7 @@ func TestExecutorExecute(t *testing.T) { stream.Context(), ) if !ok { - t.Error( - "expected request metadata", - ) + t.Error("expected request metadata") } if id := e2enginegrpc.TestExecutionID( @@ -343,9 +329,7 @@ func TestExecutorExecute(t *testing.T) { method.Input(), ) - if err := stream.RecvMsg( - request, - ); err != nil { + if err := stream.RecvMsg(request); err != nil { return err } @@ -392,9 +376,7 @@ func TestExecutorExecute(t *testing.T) { ), ) - return stream.SendMsg( - response, - ) + return stream.SendMsg(response) }, ), ) @@ -404,20 +386,32 @@ func TestExecutorExecute(t *testing.T) { }() defer server.Stop() - service.Address = listener.Addr().String() + const logicalTarget = "gateway-host:50051" + + resolvedTarget := listener.Addr().String() ctrl := gomock.NewController(t) + reporter := NewMockexecutionReporter(ctrl) + resolver := NewMockaddressResolver(ctrl) + + resolver.EXPECT(). + ResolveGRPCTarget(logicalTarget). + Return(resolvedTarget, nil) evaluator := NewEvaluator( - resolver, + methodResolver, reporter, ) executor := NewTestExecutor( - resolver, + &ExecutorConfig{ + MaxMessageSize: 4 << 20, + }, + methodResolver, evaluator, reporter, + resolver, ) job := &execute.TestJob{ @@ -433,7 +427,7 @@ func TestExecutorExecute(t *testing.T) { Spec: model.TestSpec{ Request: model.RequestSpec{ GRPC: &model.GRPCRequest{ - Target: service.Address, + Target: logicalTarget, Service: "users.UserService", Method: "Create", Metadata: map[string][]string{ @@ -463,10 +457,10 @@ func TestExecutorExecute(t *testing.T) { reporter.EXPECT(). AddGRPCRequest(gomock.Any()). Do(func(req *model.GRPCRequest) { - if req.Target != service.Address { + if req.Target != resolvedTarget { t.Errorf( "expected target %q, got %q", - service.Address, + resolvedTarget, req.Target, ) } @@ -562,13 +556,476 @@ func TestExecutorExecute(t *testing.T) { job, ) if err != nil { - t.Fatalf( - "Execute() error = %v", + t.Fatalf("Execute() error = %v", err) + } + + // Hostname resolution must not mutate the persisted Test specification. + if job.Test.Spec.Request.GRPC.Target != logicalTarget { + t.Errorf( + "expected original target %q, got %q", + logicalTarget, + job.Test.Spec.Request.GRPC.Target, + ) + } +} + +func TestExecutorExecuteWithTestLevelProto(t *testing.T) { + service := testServiceSpec() + methodResolver := servicegrpc.NewProtoMethodResolver(nil) + + method, err := methodResolver.ResolveMethod( + context.Background(), + service.Proto, + "Create", + ) + if err != nil { + t.Fatalf("ResolveMethod() error = %v", err) + } + + listener, err := (&net.ListenConfig{}).Listen( + t.Context(), + "tcp", + "127.0.0.1:0", + ) + if err != nil { + t.Fatalf("Listen() error = %v", err) + } + defer listener.Close() + + server := ggrpc.NewServer( + ggrpc.UnknownServiceHandler( + func( + _ any, + stream ggrpc.ServerStream, + ) error { + request := dynamicpb.NewMessage(method.Input()) + + if err := stream.RecvMsg(request); err != nil { + return err + } + + name := request.Get( + method.Input().Fields().ByName("name"), + ).String() + + if name != "Yaroslav" { + t.Errorf( + "expected request name %q, got %q", + "Yaroslav", + name, + ) + } + + response := dynamicpb.NewMessage(method.Output()) + response.Set( + method.Output().Fields().ByName("id"), + protoreflect.ValueOfString("user-123"), + ) + + return stream.SendMsg(response) + }, + ), + ) + + go func() { + _ = server.Serve(listener) + }() + defer server.Stop() + + const logicalTarget = "gateway-host:50051" + resolvedTarget := listener.Addr().String() + + ctrl := gomock.NewController(t) + + reporter := NewMockexecutionReporter(ctrl) + resolver := NewMockaddressResolver(ctrl) + + resolver.EXPECT(). + ResolveGRPCTarget(logicalTarget). + Return(resolvedTarget, nil) + + reporter.EXPECT(). + AddGRPCRequest(gomock.Any()). + Do(func(request *model.GRPCRequest) { + if request.Target != resolvedTarget { + t.Errorf( + "expected resolved target %q, got %q", + resolvedTarget, + request.Target, + ) + } + }) + + reporter.EXPECT(). + AddGRPCResponseStatus("OK") + + reporter.EXPECT(). + AddGRPCResponseMetadata(gomock.Any()). + AnyTimes() + + reporter.EXPECT(). + AddGRPCResponseMessage(gomock.Any()). + AnyTimes() + + executor := NewTestExecutor( + &ExecutorConfig{ + MaxMessageSize: 4 << 20, + }, + methodResolver, + NewEvaluator(methodResolver, reporter), + reporter, + resolver, + ) + + job := &execute.TestJob{ + ExecutionID: "execution-123", + + // No matching gRPC service or protobuf specification. + Environment: model.Environment{}, + + Test: model.Test{ + Spec: model.TestSpec{ + Request: model.RequestSpec{ + GRPC: &model.GRPCRequest{ + Target: logicalTarget, + Service: "users.UserService", + Method: "Create", + + // Protobuf specification is provided by the Test. + Proto: service.Proto, + + Message: map[string]any{ + "name": "Yaroslav", + }, + }, + }, + Expect: model.ExpectSpec{ + GRPC: &model.GRPCResponsePattern{ + Status: "OK", + Message: mapPtrExecutor(map[string]any{ + "id": "user-123", + }), + }, + }, + }, + }, + } + + if err := executor.Execute(t.Context(), job); err != nil { + t.Fatalf("Execute() error = %v", err) + } + + if job.Test.Spec.Request.GRPC.Target != logicalTarget { + t.Errorf( + "expected original target %q, got %q", + logicalTarget, + job.Test.Spec.Request.GRPC.Target, + ) + } +} + +func TestExecutorExecuteAddressResolutionError(t *testing.T) { + service := testServiceSpec() + + ctrl := gomock.NewController(t) + + reporter := NewMockexecutionReporter(ctrl) + resolver := NewMockaddressResolver(ctrl) + + methodResolver := servicegrpc.NewProtoMethodResolver(nil) + + evaluator := NewEvaluator( + methodResolver, + reporter, + ) + + executor := NewTestExecutor( + &ExecutorConfig{ + MaxMessageSize: 4 << 20, + }, + methodResolver, + evaluator, + reporter, + resolver, + ) + + const logicalTarget = "gateway-host:50051" + + resolveErr := errors.New("cannot resolve gRPC target") + + resolver.EXPECT(). + ResolveGRPCTarget(logicalTarget). + Return("", resolveErr) + + job := &execute.TestJob{ + ExecutionID: "execution-123", + Environment: model.Environment{ + Spec: model.EnvironmentSpec{ + Services: []model.ServiceSpec{ + *service, + }, + }, + }, + Test: model.Test{ + Spec: model.TestSpec{ + Request: model.RequestSpec{ + GRPC: &model.GRPCRequest{ + Target: logicalTarget, + Service: "users.UserService", + Method: "Create", + Message: map[string]any{ + "name": "Yaroslav", + }, + }, + }, + }, + }, + } + + err := executor.Execute( + context.Background(), + job, + ) + + if !errors.Is(err, resolveErr) { + t.Errorf( + "expected error %v, got %v", + resolveErr, err, ) } } +func TestExecutorExecuteRequestMessageSizeLimit(t *testing.T) { + service := testServiceSpec() + methodResolver := servicegrpc.NewProtoMethodResolver(nil) + + tests := []struct { + name string + message string + maxSize int + wantErr bool + }{ + { + name: "below limit", + message: "abc", + maxSize: 100, + }, + { + name: "exceeds limit", + message: "abcdefghij", + maxSize: 5, + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ctrl := gomock.NewController(t) + + reporter := NewMockexecutionReporter(ctrl) + resolver := NewMockaddressResolver(ctrl) + + evaluator := NewEvaluator( + methodResolver, + reporter, + ) + + executor := NewTestExecutor( + &ExecutorConfig{ + MaxMessageSize: tt.maxSize, + }, + methodResolver, + evaluator, + reporter, + resolver, + ) + + job := &execute.TestJob{ + ExecutionID: "execution-123", + Environment: model.Environment{ + Spec: model.EnvironmentSpec{ + Services: []model.ServiceSpec{ + *service, + }, + }, + }, + Test: model.Test{ + Spec: model.TestSpec{ + Request: model.RequestSpec{ + GRPC: &model.GRPCRequest{ + Target: "gateway-host:50051", + Service: "users.UserService", + Method: "Create", + Message: map[string]any{ + "name": tt.message, + }, + }, + }, + }, + }, + } + + if tt.wantErr { + err := executor.Execute(t.Context(), job) + + if !errors.Is( + err, + pkgerrors.ErrGRPCRequestMessageTooLarge, + ) { + t.Fatalf( + "expected ErrGRPCRequestMessageTooLarge, got %v", + err, + ) + } + + return + } + + // A request within the limit must proceed + // to address resolution. + resolveErr := errors.New("resolution reached") + + resolver.EXPECT(). + ResolveGRPCTarget("gateway-host:50051"). + Return("", resolveErr) + + err := executor.Execute(t.Context(), job) + + if !errors.Is(err, resolveErr) { + t.Fatalf( + "expected resolution error, got %v", + err, + ) + } + }) + } +} + +func TestExecutorExecuteResponseMessageSizeLimit(t *testing.T) { + service := testServiceSpec() + methodResolver := servicegrpc.NewProtoMethodResolver(nil) + + method, err := methodResolver.ResolveMethod( + t.Context(), + service.Proto, + "Create", + ) + if err != nil { + t.Fatalf("ResolveMethod() error = %v", err) + } + + listener, err := (&net.ListenConfig{}).Listen( + t.Context(), + "tcp", + "127.0.0.1:0", + ) + if err != nil { + t.Fatalf("Listen() error = %v", err) + } + defer listener.Close() + + server := ggrpc.NewServer( + ggrpc.UnknownServiceHandler( + func(_ any, stream ggrpc.ServerStream) error { + request := dynamicpb.NewMessage(method.Input()) + + if err := stream.RecvMsg(request); err != nil { + return err + } + + response := dynamicpb.NewMessage(method.Output()) + + response.Set( + method.Output().Fields().ByName("id"), + protoreflect.ValueOfString( + strings.Repeat("x", 1024), + ), + ) + + return stream.SendMsg(response) + }, + ), + ) + + go func() { + _ = server.Serve(listener) + }() + defer server.Stop() + + const logicalTarget = "gateway-host:50051" + + ctrl := gomock.NewController(t) + + reporter := NewMockexecutionReporter(ctrl) + resolver := NewMockaddressResolver(ctrl) + + resolver.EXPECT(). + ResolveGRPCTarget(logicalTarget). + Return(listener.Addr().String(), nil) + + reporter.EXPECT(). + AddGRPCRequest(gomock.Any()) + + reporter.EXPECT(). + AddGRPCResponseStatus("ResourceExhausted") + + reporter.EXPECT(). + AddGRPCResponseMetadata(gomock.Any()). + AnyTimes() + + reporter.EXPECT(). + AddDeviation(gomock.Any()). + AnyTimes() + + // The oversized response must not be decoded and reported. + // The evaluator reports an empty message when the receive limit is exceeded. + reporter.EXPECT(). + AddGRPCResponseMessage(map[string]any{}) + + executor := NewTestExecutor( + &ExecutorConfig{ + MaxMessageSize: 32, + }, + methodResolver, + NewEvaluator(methodResolver, reporter), + reporter, + resolver, + ) + + job := &execute.TestJob{ + ExecutionID: "execution-123", + Environment: model.Environment{ + Spec: model.EnvironmentSpec{ + Services: []model.ServiceSpec{*service}, + }, + }, + Test: model.Test{ + Spec: model.TestSpec{ + Request: model.RequestSpec{ + GRPC: &model.GRPCRequest{ + Target: logicalTarget, + Service: "users.UserService", + Method: "Create", + Message: map[string]any{ + "name": "a", + }, + }, + }, + Expect: model.ExpectSpec{ + GRPC: &model.GRPCResponsePattern{ + Status: "ResourceExhausted", + }, + }, + }, + }, + } + + if err := executor.Execute(t.Context(), job); err != nil { + t.Fatalf("Execute() error = %v", err) + } +} + func mapPtrExecutor( value map[string]any, ) *matcher.GRPCMessage { diff --git a/execute/worker/grpc/mock_address_resolver_test.go b/execute/worker/grpc/mock_address_resolver_test.go new file mode 100644 index 0000000..b1a23e0 --- /dev/null +++ b/execute/worker/grpc/mock_address_resolver_test.go @@ -0,0 +1,55 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: address_resolver.go +// +// Generated by this command: +// +// mockgen -source=address_resolver.go -destination=mock_address_resolver_test.go -package=grpc +// + +// Package grpc is a generated GoMock package. +package grpc + +import ( + reflect "reflect" + + gomock "go.uber.org/mock/gomock" +) + +// MockaddressResolver is a mock of addressResolver interface. +type MockaddressResolver struct { + ctrl *gomock.Controller + recorder *MockaddressResolverMockRecorder + isgomock struct{} +} + +// MockaddressResolverMockRecorder is the mock recorder for MockaddressResolver. +type MockaddressResolverMockRecorder struct { + mock *MockaddressResolver +} + +// NewMockaddressResolver creates a new mock instance. +func NewMockaddressResolver(ctrl *gomock.Controller) *MockaddressResolver { + mock := &MockaddressResolver{ctrl: ctrl} + mock.recorder = &MockaddressResolverMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockaddressResolver) EXPECT() *MockaddressResolverMockRecorder { + return m.recorder +} + +// ResolveGRPCTarget mocks base method. +func (m *MockaddressResolver) ResolveGRPCTarget(value string) (string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ResolveGRPCTarget", value) + ret0, _ := ret[0].(string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ResolveGRPCTarget indicates an expected call of ResolveGRPCTarget. +func (mr *MockaddressResolverMockRecorder) ResolveGRPCTarget(value any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ResolveGRPCTarget", reflect.TypeOf((*MockaddressResolver)(nil).ResolveGRPCTarget), value) +} diff --git a/execute/worker/grpc/mock_reporter_test.go b/execute/worker/grpc/mock_reporter_test.go index 969d228..0a42ebc 100644 --- a/execute/worker/grpc/mock_reporter_test.go +++ b/execute/worker/grpc/mock_reporter_test.go @@ -100,6 +100,18 @@ func (mr *MockexecutionReporterMockRecorder) AddGRPCResponseStatus(status any) * return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddGRPCResponseStatus", reflect.TypeOf((*MockexecutionReporter)(nil).AddGRPCResponseStatus), status) } +// AddMetadataDeviation mocks base method. +func (m *MockexecutionReporter) AddMetadataDeviation(key string, deviation *model.TestExecutionDeviation) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddMetadataDeviation", key, deviation) +} + +// AddMetadataDeviation indicates an expected call of AddMetadataDeviation. +func (mr *MockexecutionReporterMockRecorder) AddMetadataDeviation(key, deviation any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddMetadataDeviation", reflect.TypeOf((*MockexecutionReporter)(nil).AddMetadataDeviation), key, deviation) +} + // AddPayloadDeviation mocks base method. func (m *MockexecutionReporter) AddPayloadDeviation(deviation *model.PayloadDeviation) { m.ctrl.T.Helper() diff --git a/execute/worker/grpc/reporter.go b/execute/worker/grpc/reporter.go index a2d1fd5..2a6604d 100644 --- a/execute/worker/grpc/reporter.go +++ b/execute/worker/grpc/reporter.go @@ -7,6 +7,10 @@ import ( type executionReporter interface { AddDeviation(deviation *model.TestExecutionDeviation) AddPayloadDeviation(deviation *model.PayloadDeviation) + AddMetadataDeviation( + key string, + deviation *model.TestExecutionDeviation, + ) AddGRPCRequest(req *model.GRPCRequest) AddGRPCResponseStatus(status string) AddGRPCResponseMetadata(metadata map[string][]string) diff --git a/execute/worker/http/address_resolver.go b/execute/worker/http/address_resolver.go new file mode 100644 index 0000000..dea6215 --- /dev/null +++ b/execute/worker/http/address_resolver.go @@ -0,0 +1,7 @@ +package http + +type addressResolver interface { + ResolveHTTPURL(value string) (string, error) +} + +//go:generate go run -mod=mod go.uber.org/mock/mockgen -source=address_resolver.go -destination=mock_address_resolver_test.go -package=http diff --git a/execute/worker/http/evaluate.go b/execute/worker/http/evaluate.go index 8c5a715..9e2c88a 100644 --- a/execute/worker/http/evaluate.go +++ b/execute/worker/http/evaluate.go @@ -15,19 +15,27 @@ import ( "github.com/e2engine/core/internal/util" "github.com/e2engine/core/model" "github.com/e2engine/core/model/matcher" + "github.com/e2engine/core/pkg/errors" "github.com/e2engine/core/pkg/keys" ) var _ evaluator.CallEvaluator = (*Evaluator)(nil) type Evaluator struct { + cfg *EvaluatorConfig reporter executionReporter } +type EvaluatorConfig struct { + MaxResponseBodySize int64 `json:"max_response_body_size" yaml:"max_response_body_size" default:"1048576" validate:"min(1),max(67108864)"` +} + func NewEvaluator( + cfg *EvaluatorConfig, reporter executionReporter, ) *Evaluator { return &Evaluator{ + cfg: cfg, reporter: reporter, } } @@ -40,11 +48,17 @@ func (e *Evaluator) EvaluateResponse( e.evaluateHeaders(expect.Headers, resp.Header) - actualBody, err := io.ReadAll(resp.Body) + actualBody, err := io.ReadAll( + io.LimitReader(resp.Body, e.cfg.MaxResponseBodySize+1), + ) if err != nil { return err } + if int64(len(actualBody)) > e.cfg.MaxResponseBodySize { + return errors.ErrHTTPResponseBodyTooLarge + } + if expect.Body == nil && expect.BodyJSON == nil { // nil means "do not evaluate body" // we still need to report the body we received @@ -142,11 +156,14 @@ func (e *Evaluator) evaluateHeaders( } slices.Sort(expectedStrings) - e.reporter.AddDeviation(&model.TestExecutionDeviation{ - Field: "headers." + key, - Expected: strings.Join(expectedStrings, ","), - Actual: strings.Join(sortedActual, ","), - }) + e.reporter.AddHeadersDeviation( + key, + &model.TestExecutionDeviation{ + Field: "headers." + key, + Expected: strings.Join(expectedStrings, ","), + Actual: strings.Join(sortedActual, ","), + }, + ) } } @@ -165,27 +182,27 @@ func (e *Evaluator) Matches( } return httpCallMatchesExpectation( - actual.HTTP.Request, + &actual.HTTP.Request, expected.HTTP, - ), nil + ) } func httpCallMatchesExpectation( - actual call.HTTPRequest, + actual *call.HTTPRequest, expected *model.HTTPRequestPattern, -) bool { +) (bool, error) { if expected.Method != "" && actual.Method != expected.Method { - return false + return false, nil } if expected.Path != "" && actual.Path != expected.Path { - return false + return false, nil } for key, expectedValues := range expected.Query { actualValues, ok := actual.Query[key] if !ok || !util.IsStringSlicesEqual(actualValues, expectedValues) { - return false + return false, nil } } @@ -198,12 +215,23 @@ func httpCallMatchesExpectation( exists, expectedValues, ) { - return false + return false, nil } } - if expected.Body != nil && !match.IsStringMatched(actual.Body, expected.Body) { - return false + if expected.Body != nil || expected.BodyJSON != nil { + if actual.BodyTruncated { + return false, errors.ErrHTTPRecordedRequestBodyTruncated + } + + if !actual.BodyComplete { + return false, errors.ErrHTTPRecordedRequestBodyIncomplete + } + } + + if expected.Body != nil && + !match.IsStringMatched(actual.Body, expected.Body) { + return false, nil } if expected.BodyJSON != nil { @@ -212,11 +240,11 @@ func httpCallMatchesExpectation( expected.BodyJSON, ) if err != nil || !matched { - return false + return false, nil } } - return true + return true, nil } func (e *Evaluator) Deviation( diff --git a/execute/worker/http/evaluate_test.go b/execute/worker/http/evaluate_test.go index f52b508..b7c2c3d 100644 --- a/execute/worker/http/evaluate_test.go +++ b/execute/worker/http/evaluate_test.go @@ -14,6 +14,7 @@ import ( "github.com/e2engine/core/execute/call" "github.com/e2engine/core/model" "github.com/e2engine/core/model/matcher" + errorsPkg "github.com/e2engine/core/pkg/errors" "github.com/e2engine/core/pkg/keys" ) @@ -454,7 +455,10 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { ctrl := gomock.NewController(t) reporter := NewMockexecutionReporter(ctrl) - evaluator := NewEvaluator(reporter) + evaluatorCfg := &EvaluatorConfig{ + MaxResponseBodySize: 1024 * 1024, // 1 MB + } + evaluator := NewEvaluator(evaluatorCfg, reporter) response := &nethttp.Response{ StatusCode: tt.status, @@ -471,10 +475,20 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { AddHTTPResponseHeaders(tt.headers) for _, deviation := range tt.deviations { - if deviation.payload != nil { + switch { + case deviation.payload != nil: reporter.EXPECT(). AddPayloadDeviation(deviation.payload) - } else { + + case deviation.deviation != nil && + strings.HasPrefix(deviation.deviation.Field, "headers."): + reporter.EXPECT(). + AddHeadersDeviation( + strings.TrimPrefix(deviation.deviation.Field, "headers."), + deviation.deviation, + ) + + default: reporter.EXPECT(). AddDeviation(deviation.deviation) } @@ -512,7 +526,10 @@ func TestEvaluatorEvaluateResponseReadError(t *testing.T) { ctrl := gomock.NewController(t) reporter := NewMockexecutionReporter(ctrl) - evaluator := NewEvaluator(reporter) + evaluatorCfg := &EvaluatorConfig{ + MaxResponseBodySize: 1024 * 1024, // 1 MB + } + evaluator := NewEvaluator(evaluatorCfg, reporter) response := &nethttp.Response{ StatusCode: nethttp.StatusOK, @@ -549,9 +566,10 @@ func TestEvaluatorMatches(t *testing.T) { ServiceID: "service-1", HTTP: &call.HTTPCall{ Request: call.HTTPRequest{ - Method: "POST", - Path: "/users", - Body: []byte(`{"name":"Yaroslav"}`), + Method: "POST", + Path: "/users", + Body: []byte(`{"name":"Yaroslav"}`), + BodyComplete: true, }, }, } @@ -623,7 +641,10 @@ func TestEvaluatorMatches(t *testing.T) { ctrl := gomock.NewController(t) reporter := NewMockexecutionReporter(ctrl) - evaluator := NewEvaluator(reporter) + evaluatorCfg := &EvaluatorConfig{ + MaxResponseBodySize: 1024 * 1024, // 1 MB + } + evaluator := NewEvaluator(evaluatorCfg, reporter) matched, err := evaluator.Matches( context.Background(), @@ -662,7 +683,8 @@ func TestHTTPCallMatchesExpectation(t *testing.T) { "X-Test": {"one", "two"}, "X-Empty": {""}, }, - Body: []byte(`{"name":"Yaroslav","active":true}`), + Body: []byte(`{"name":"Yaroslav","active":true}`), + BodyComplete: true, } tests := []struct { @@ -933,10 +955,16 @@ func TestHTTPCallMatchesExpectation(t *testing.T) { request.Body = tt.body } - matched := httpCallMatchesExpectation( - request, + matched, err := httpCallMatchesExpectation( + &request, &tt.expected, ) + if err != nil { + t.Fatalf( + "httpCallMatchesExpectation() error = %v", + err, + ) + } if matched != tt.match { t.Errorf( @@ -953,7 +981,10 @@ func TestEvaluatorDeviation(t *testing.T) { ctrl := gomock.NewController(t) reporter := NewMockexecutionReporter(ctrl) - evaluator := NewEvaluator(reporter) + evaluatorCfg := &EvaluatorConfig{ + MaxResponseBodySize: 1024 * 1024, // 1 MB + } + evaluator := NewEvaluator(evaluatorCfg, reporter) service := &model.ServiceSpec{ ID: "service-1", @@ -978,8 +1009,9 @@ func TestEvaluatorDeviation(t *testing.T) { ServiceID: "service-1", HTTP: &call.HTTPCall{ Request: call.HTTPRequest{ - Method: "GET", - Path: "/users", + Method: "GET", + Path: "/users", + BodyComplete: true, }, Response: call.HTTPResponse{ Headers: nethttp.Header{}, @@ -993,8 +1025,9 @@ func TestEvaluatorDeviation(t *testing.T) { ServiceID: "service-1", HTTP: &call.HTTPCall{ Request: call.HTTPRequest{ - Method: "POST", - Path: "/users", + Method: "POST", + Path: "/users", + BodyComplete: true, }, Response: call.HTTPResponse{ Headers: func() nethttp.Header { @@ -1035,6 +1068,209 @@ func TestEvaluatorDeviation(t *testing.T) { } } +func TestEvaluatorEvaluateResponseBodySizeLimit(t *testing.T) { + const limit int64 = 5 + + tests := []struct { + name string + body string + expect model.HTTPResponsePattern + wantErr bool + }{ + { + name: "below limit", + body: "abcd", + expect: model.HTTPResponsePattern{StatusCode: nethttp.StatusOK}, + }, + { + name: "exactly at limit", + body: "abcde", + expect: model.HTTPResponsePattern{StatusCode: nethttp.StatusOK}, + }, + { + name: "exceeds limit without body expectation", + body: "abcdef", + expect: model.HTTPResponsePattern{StatusCode: nethttp.StatusOK}, + wantErr: true, + }, + { + name: "exceeds limit with body expectation", + body: "abcdef", + expect: model.HTTPResponsePattern{ + StatusCode: nethttp.StatusOK, + Body: &matcher.String{Value: "abcdef"}, + }, + wantErr: true, + }, + { + name: "exceeds limit with JSON expectation", + body: `{"a":1}`, + expect: model.HTTPResponsePattern{ + StatusCode: nethttp.StatusOK, + BodyJSON: &matcher.String{ + Operator: matcher.StringMatchOperatorEquals, + Value: `{"a":1}`, + }, + }, + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ctrl := gomock.NewController(t) + reporter := NewMockexecutionReporter(ctrl) + + evaluator := NewEvaluator( + &EvaluatorConfig{MaxResponseBodySize: limit}, + reporter, + ) + + response := &nethttp.Response{ + StatusCode: nethttp.StatusOK, + Body: io.NopCloser(strings.NewReader(tt.body)), + } + + reporter.EXPECT().AddHTTPResponseStatus(nethttp.StatusOK) + reporter.EXPECT().AddHTTPResponseHeaders(nil) + + if !tt.wantErr { + reporter.EXPECT().AddHTTPResponseBody([]byte(tt.body)) + } + + err := evaluator.EvaluateResponse(response, &tt.expect) + + if tt.wantErr { + if !errors.Is(err, errorsPkg.ErrHTTPResponseBodyTooLarge) { + t.Fatalf( + "expected ErrHTTPResponseBodyTooLarge, got %v", + err, + ) + } + } else if err != nil { + t.Fatalf("unexpected error: %v", err) + } + }) + } +} + +func TestEvaluatorEvaluateResponseBodySizeLimitReadError(t *testing.T) { + expectedErr := errors.New("read error") + + ctrl := gomock.NewController(t) + reporter := NewMockexecutionReporter(ctrl) + + evaluator := NewEvaluator( + &EvaluatorConfig{MaxResponseBodySize: 5}, + reporter, + ) + + response := &nethttp.Response{ + StatusCode: nethttp.StatusOK, + Body: &failingReader{ + err: expectedErr, + }, + } + + reporter.EXPECT().AddHTTPResponseStatus(nethttp.StatusOK) + reporter.EXPECT().AddHTTPResponseHeaders(nil) + + err := evaluator.EvaluateResponse( + response, + &model.HTTPResponsePattern{ + StatusCode: nethttp.StatusOK, + }, + ) + + if !errors.Is(err, expectedErr) { + t.Fatalf("expected read error, got %v", err) + } +} + +func TestHTTPCallMatchesExpectationTruncatedBody(t *testing.T) { + tests := []struct { + name string + expected model.HTTPRequestPattern + wantMatch bool + wantErr bool + }{ + { + name: "no body expectation", + expected: model.HTTPRequestPattern{ + Method: "POST", + }, + wantMatch: true, + }, + { + name: "body expectation", + expected: model.HTTPRequestPattern{ + Body: stringMatcher("hello world"), + }, + wantErr: true, + }, + { + name: "JSON body expectation", + expected: model.HTTPRequestPattern{ + BodyJSON: stringMatcher(`{"message":"hello world"}`), + }, + wantErr: true, + }, + { + name: "method mismatch before body check", + expected: model.HTTPRequestPattern{ + Method: "GET", + Body: stringMatcher("hello world"), + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + actual := call.HTTPRequest{ + Method: "POST", + Body: []byte("hello"), + BodyTruncated: true, + BodyComplete: true, + } + + matched, err := httpCallMatchesExpectation( + &actual, + &tt.expected, + ) + + if tt.wantErr { + if !errors.Is( + err, + errorsPkg.ErrHTTPRecordedRequestBodyTruncated, + ) { + t.Fatalf( + "expected ErrHTTPRecordedRequestBodyTruncated, got %v", + err, + ) + } + + if matched { + t.Error("truncated body unexpectedly matched") + } + + return + } + + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + if matched != tt.wantMatch { + t.Errorf( + "matched = %v, want %v", + matched, + tt.wantMatch, + ) + } + }) + } +} + type errorReader struct { err error } @@ -1076,3 +1312,15 @@ func stringMatcherOperatorValue( Operator: operator, } } + +type failingReader struct { + err error +} + +func (r *failingReader) Read(_ []byte) (int, error) { + return 0, r.err +} + +func (r *failingReader) Close() error { + return nil +} diff --git a/execute/worker/http/executor.go b/execute/worker/http/executor.go index fcb5afa..8ebd08f 100644 --- a/execute/worker/http/executor.go +++ b/execute/worker/http/executor.go @@ -13,20 +13,23 @@ import ( ) type TestExecutor struct { - client *http.Client - evaluator *Evaluator - reporter executionReporter + client *http.Client + evaluator *Evaluator + reporter executionReporter + addressResolver addressResolver } func NewTestExecutor( client *http.Client, evaluator *Evaluator, reporter executionReporter, + addressResolver addressResolver, ) *TestExecutor { return &TestExecutor{ - client: client, - evaluator: evaluator, - reporter: reporter, + client: client, + evaluator: evaluator, + reporter: reporter, + addressResolver: addressResolver, } } @@ -34,8 +37,16 @@ func (e *TestExecutor) Execute( ctx context.Context, job *execute.TestJob, ) error { + resolvedURL, err := e.addressResolver.ResolveHTTPURL( + job.Test.Spec.Request.HTTP.URL, + ) + if err != nil { + return err + } + req, err := buildHTTPRequest( ctx, + resolvedURL, job.Test.Spec.Request.HTTP, job.ExecutionID, ) @@ -66,6 +77,7 @@ func (e *TestExecutor) Execute( func buildHTTPRequest( ctx context.Context, + resolvedURL string, spec *model.HTTPRequest, testExecutionID string, ) (*http.Request, error) { @@ -80,7 +92,7 @@ func buildHTTPRequest( req, err := http.NewRequestWithContext( ctx, spec.Method, - spec.URL, + resolvedURL, body, ) if err != nil { diff --git a/execute/worker/http/executor_test.go b/execute/worker/http/executor_test.go index b19ef68..4d541fc 100644 --- a/execute/worker/http/executor_test.go +++ b/execute/worker/http/executor_test.go @@ -91,6 +91,7 @@ func TestBuildHTTPRequest(t *testing.T) { t.Run(tt.name, func(t *testing.T) { req, err := buildHTTPRequest( ctx, + tt.spec.URL, tt.spec, "execution-123", ) @@ -195,6 +196,7 @@ func TestBuildHTTPRequestQuery(t *testing.T) { req, err := buildHTTPRequest( context.Background(), + spec.URL, spec, "execution-123", ) @@ -253,6 +255,7 @@ func TestBuildHTTPRequestHeaders(t *testing.T) { req, err := buildHTTPRequest( context.Background(), + spec.URL, spec, "execution-123", ) @@ -289,12 +292,15 @@ func TestBuildHTTPRequestCanceledContext(t *testing.T) { ) cancel() + spec := &model.HTTPRequest{ + Method: nethttp.MethodGet, + URL: "https://example.com", + } + req, err := buildHTTPRequest( ctx, - &model.HTTPRequest{ - Method: nethttp.MethodGet, - URL: "https://example.com", - }, + spec.URL, + spec, "execution-123", ) if err != nil { @@ -312,6 +318,40 @@ func TestBuildHTTPRequestCanceledContext(t *testing.T) { } } +func TestBuildHTTPRequestResolvedURL(t *testing.T) { + spec := &model.HTTPRequest{ + Method: nethttp.MethodGet, + URL: "http://payment-api:8080/payments", + } + + const resolvedURL = "http://127.0.0.1:8080/payments" + + req, err := buildHTTPRequest( + t.Context(), + resolvedURL, + spec, + "execution-123", + ) + if err != nil { + t.Fatalf("buildHTTPRequest() error = %v", err) + } + + if actual := req.URL.String(); actual != resolvedURL { + t.Errorf( + "expected URL %q, got %q", + resolvedURL, + actual, + ) + } + + if spec.URL != "http://payment-api:8080/payments" { + t.Errorf( + "original URL was modified: %q", + spec.URL, + ) + } +} + func TestDoHTTPRequest(t *testing.T) { server := httptest.NewServer( nethttp.HandlerFunc( @@ -450,15 +490,28 @@ func TestExecutorExecute(t *testing.T) { ) defer server.Close() + const logicalURL = "http://payment-api:8080/users" + resolvedURL := server.URL + "/users" + ctrl := gomock.NewController(t) + reporter := NewMockexecutionReporter(ctrl) + resolver := NewMockaddressResolver(ctrl) - evaluator := NewEvaluator(reporter) + resolver.EXPECT(). + ResolveHTTPURL(logicalURL). + Return(resolvedURL, nil) + + evaluatorCfg := &EvaluatorConfig{ + MaxResponseBodySize: 1024 * 1024, // 1 MB + } + evaluator := NewEvaluator(evaluatorCfg, reporter) executor := NewTestExecutor( server.Client(), evaluator, reporter, + resolver, ) job := &execute.TestJob{ @@ -468,7 +521,7 @@ func TestExecutorExecute(t *testing.T) { Request: model.RequestSpec{ HTTP: &model.HTTPRequest{ Method: nethttp.MethodGet, - URL: server.URL, + URL: logicalURL, }, }, Expect: model.ExpectSpec{ @@ -494,10 +547,10 @@ func TestExecutorExecute(t *testing.T) { ) } - if req.URL.String() != server.URL { + if req.URL.String() != resolvedURL { t.Errorf( - "expected URL %q, got %q", - server.URL, + "expected resolved URL %q, got %q", + resolvedURL, req.URL.String(), ) } @@ -544,6 +597,72 @@ func TestExecutorExecute(t *testing.T) { err, ) } + + // Resolution must not modify the original Test specification. + if job.Test.Spec.Request.HTTP.URL != logicalURL { + t.Errorf( + "expected original URL %q, got %q", + logicalURL, + job.Test.Spec.Request.HTTP.URL, + ) + } +} + +func TestExecutorExecuteAddressResolutionError(t *testing.T) { + ctrl := gomock.NewController(t) + + reporter := NewMockexecutionReporter(ctrl) + resolver := NewMockaddressResolver(ctrl) + + evaluatorCfg := &EvaluatorConfig{ + MaxResponseBodySize: 1024 * 1024, // 1 MB + } + evaluator := NewEvaluator(evaluatorCfg, reporter) + + executor := NewTestExecutor( + nethttp.DefaultClient, + evaluator, + reporter, + resolver, + ) + + const logicalURL = "http://payment-api:8080/payments" + + resolveErr := nativeerrors.New("cannot resolve HTTP URL") + + resolver.EXPECT(). + ResolveHTTPURL(logicalURL). + Return("", resolveErr) + + job := &execute.TestJob{ + ExecutionID: "execution-123", + Test: model.Test{ + Spec: model.TestSpec{ + Request: model.RequestSpec{ + HTTP: &model.HTTPRequest{ + Method: nethttp.MethodGet, + URL: logicalURL, + }, + }, + }, + }, + } + + err := executor.Execute( + context.Background(), + job, + ) + + if !nativeerrors.Is(err, resolveErr) { + t.Errorf( + "expected error %v, got %v", + resolveErr, + err, + ) + } + + // No reporter calls should occur when address resolution fails. + // gomock verifies this because no expectations were registered. } func stringPtrExecutor( diff --git a/execute/worker/http/mock_address_resolver_test.go b/execute/worker/http/mock_address_resolver_test.go new file mode 100644 index 0000000..f4b0b94 --- /dev/null +++ b/execute/worker/http/mock_address_resolver_test.go @@ -0,0 +1,55 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: address_resolver.go +// +// Generated by this command: +// +// mockgen -source=address_resolver.go -destination=mock_address_resolver_test.go -package=http +// + +// Package http is a generated GoMock package. +package http + +import ( + reflect "reflect" + + gomock "go.uber.org/mock/gomock" +) + +// MockaddressResolver is a mock of addressResolver interface. +type MockaddressResolver struct { + ctrl *gomock.Controller + recorder *MockaddressResolverMockRecorder + isgomock struct{} +} + +// MockaddressResolverMockRecorder is the mock recorder for MockaddressResolver. +type MockaddressResolverMockRecorder struct { + mock *MockaddressResolver +} + +// NewMockaddressResolver creates a new mock instance. +func NewMockaddressResolver(ctrl *gomock.Controller) *MockaddressResolver { + mock := &MockaddressResolver{ctrl: ctrl} + mock.recorder = &MockaddressResolverMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockaddressResolver) EXPECT() *MockaddressResolverMockRecorder { + return m.recorder +} + +// ResolveHTTPURL mocks base method. +func (m *MockaddressResolver) ResolveHTTPURL(value string) (string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ResolveHTTPURL", value) + ret0, _ := ret[0].(string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ResolveHTTPURL indicates an expected call of ResolveHTTPURL. +func (mr *MockaddressResolverMockRecorder) ResolveHTTPURL(value any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ResolveHTTPURL", reflect.TypeOf((*MockaddressResolver)(nil).ResolveHTTPURL), value) +} diff --git a/execute/worker/http/mock_reporter_test.go b/execute/worker/http/mock_reporter_test.go index f22fef9..651e602 100644 --- a/execute/worker/http/mock_reporter_test.go +++ b/execute/worker/http/mock_reporter_test.go @@ -113,6 +113,18 @@ func (mr *MockexecutionReporterMockRecorder) AddHTTPResponseStatus(status any) * return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddHTTPResponseStatus", reflect.TypeOf((*MockexecutionReporter)(nil).AddHTTPResponseStatus), status) } +// AddHeadersDeviation mocks base method. +func (m *MockexecutionReporter) AddHeadersDeviation(header string, deviation *model.TestExecutionDeviation) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddHeadersDeviation", header, deviation) +} + +// AddHeadersDeviation indicates an expected call of AddHeadersDeviation. +func (mr *MockexecutionReporterMockRecorder) AddHeadersDeviation(header, deviation any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddHeadersDeviation", reflect.TypeOf((*MockexecutionReporter)(nil).AddHeadersDeviation), header, deviation) +} + // AddPayloadDeviation mocks base method. func (m *MockexecutionReporter) AddPayloadDeviation(deviation *model.PayloadDeviation) { m.ctrl.T.Helper() diff --git a/execute/worker/http/reporter.go b/execute/worker/http/reporter.go index 9823cf7..8a2a67e 100644 --- a/execute/worker/http/reporter.go +++ b/execute/worker/http/reporter.go @@ -9,6 +9,10 @@ import ( type executionReporter interface { AddDeviation(deviation *model.TestExecutionDeviation) AddPayloadDeviation(deviation *model.PayloadDeviation) + AddHeadersDeviation( + header string, + deviation *model.TestExecutionDeviation, + ) AddHTTPRequest(req *http.Request) AddHTTPResponseStatus(status int) AddHTTPResponseHeaders(headers http.Header) diff --git a/execute/worker/mock_address_resolver_test.go b/execute/worker/mock_address_resolver_test.go new file mode 100644 index 0000000..ad6984f --- /dev/null +++ b/execute/worker/mock_address_resolver_test.go @@ -0,0 +1,70 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: address_resolver.go +// +// Generated by this command: +// +// mockgen -source=address_resolver.go -destination=mock_address_resolver_test.go -package=worker +// + +// Package worker is a generated GoMock package. +package worker + +import ( + reflect "reflect" + + gomock "go.uber.org/mock/gomock" +) + +// MockaddressResolver is a mock of addressResolver interface. +type MockaddressResolver struct { + ctrl *gomock.Controller + recorder *MockaddressResolverMockRecorder + isgomock struct{} +} + +// MockaddressResolverMockRecorder is the mock recorder for MockaddressResolver. +type MockaddressResolverMockRecorder struct { + mock *MockaddressResolver +} + +// NewMockaddressResolver creates a new mock instance. +func NewMockaddressResolver(ctrl *gomock.Controller) *MockaddressResolver { + mock := &MockaddressResolver{ctrl: ctrl} + mock.recorder = &MockaddressResolverMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockaddressResolver) EXPECT() *MockaddressResolverMockRecorder { + return m.recorder +} + +// ResolveGRPCTarget mocks base method. +func (m *MockaddressResolver) ResolveGRPCTarget(value string) (string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ResolveGRPCTarget", value) + ret0, _ := ret[0].(string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ResolveGRPCTarget indicates an expected call of ResolveGRPCTarget. +func (mr *MockaddressResolverMockRecorder) ResolveGRPCTarget(value any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ResolveGRPCTarget", reflect.TypeOf((*MockaddressResolver)(nil).ResolveGRPCTarget), value) +} + +// ResolveHTTPURL mocks base method. +func (m *MockaddressResolver) ResolveHTTPURL(value string) (string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ResolveHTTPURL", value) + ret0, _ := ret[0].(string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ResolveHTTPURL indicates an expected call of ResolveHTTPURL. +func (mr *MockaddressResolverMockRecorder) ResolveHTTPURL(value any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ResolveHTTPURL", reflect.TypeOf((*MockaddressResolver)(nil).ResolveHTTPURL), value) +} diff --git a/execute/worker/reporter/calls_test.go b/execute/worker/reporter/calls_test.go index fb65cd0..00f463d 100644 --- a/execute/worker/reporter/calls_test.go +++ b/execute/worker/reporter/calls_test.go @@ -26,8 +26,9 @@ func TestSummarizeCalls(t *testing.T) { ServiceID: "users", HTTP: &call.HTTPCall{ Request: call.HTTPRequest{ - Method: "GET", - Path: "/users", + Method: "GET", + Path: "/users", + BodyComplete: true, }, Response: call.HTTPResponse{ StatusCode: 200, @@ -39,8 +40,9 @@ func TestSummarizeCalls(t *testing.T) { ServiceID: "users", HTTP: &call.HTTPCall{ Request: call.HTTPRequest{ - Method: "GET", - Path: "/users", + Method: "GET", + Path: "/users", + BodyComplete: true, }, Response: call.HTTPResponse{ StatusCode: 200, @@ -68,8 +70,9 @@ func TestSummarizeCalls(t *testing.T) { ServiceID: "users", HTTP: &call.HTTPCall{ Request: call.HTTPRequest{ - Method: "GET", - Path: "/users", + Method: "GET", + Path: "/users", + BodyComplete: true, }, Response: call.HTTPResponse{ StatusCode: 200, @@ -81,8 +84,9 @@ func TestSummarizeCalls(t *testing.T) { ServiceID: "users", HTTP: &call.HTTPCall{ Request: call.HTTPRequest{ - Method: "GET", - Path: "/users", + Method: "GET", + Path: "/users", + BodyComplete: true, }, Response: call.HTTPResponse{ StatusCode: 500, @@ -119,8 +123,9 @@ func TestSummarizeCalls(t *testing.T) { ServiceID: "users", HTTP: &call.HTTPCall{ Request: call.HTTPRequest{ - Method: "GET", - Path: "/users", + Method: "GET", + Path: "/users", + BodyComplete: true, }, Response: call.HTTPResponse{ StatusCode: 200, @@ -132,8 +137,9 @@ func TestSummarizeCalls(t *testing.T) { ServiceID: "users", HTTP: &call.HTTPCall{ Request: call.HTTPRequest{ - Method: "POST", - Path: "/users", + Method: "POST", + Path: "/users", + BodyComplete: true, }, Response: call.HTTPResponse{ StatusCode: 200, @@ -145,8 +151,9 @@ func TestSummarizeCalls(t *testing.T) { ServiceID: "users", HTTP: &call.HTTPCall{ Request: call.HTTPRequest{ - Method: "GET", - Path: "/health", + Method: "GET", + Path: "/health", + BodyComplete: true, }, Response: call.HTTPResponse{ StatusCode: 200, @@ -358,8 +365,9 @@ func TestSummarizeCalls(t *testing.T) { ServiceID: "service-b", HTTP: &call.HTTPCall{ Request: call.HTTPRequest{ - Method: "GET", - Path: "/health", + Method: "GET", + Path: "/health", + BodyComplete: true, }, Response: call.HTTPResponse{ StatusCode: 200, @@ -371,8 +379,9 @@ func TestSummarizeCalls(t *testing.T) { ServiceID: "service-a", HTTP: &call.HTTPCall{ Request: call.HTTPRequest{ - Method: "GET", - Path: "/health", + Method: "GET", + Path: "/health", + BodyComplete: true, }, Response: call.HTTPResponse{ StatusCode: 200, @@ -422,8 +431,9 @@ func TestSummarizeCalls(t *testing.T) { ServiceID: "service-1", HTTP: &call.HTTPCall{ Request: call.HTTPRequest{ - Method: "GET", - Path: "/health", + Method: "GET", + Path: "/health", + BodyComplete: true, }, Response: call.HTTPResponse{ StatusCode: 200, @@ -460,8 +470,9 @@ func TestSummarizeCalls(t *testing.T) { ServiceID: "users", HTTP: &call.HTTPCall{ Request: call.HTTPRequest{ - Method: "GET", - Path: "/users", + Method: "GET", + Path: "/users", + BodyComplete: true, }, Response: call.HTTPResponse{ StatusCode: 200, @@ -474,10 +485,16 @@ func TestSummarizeCalls(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - store := &call.Store{} + store := call.NewStoreFactory( + &call.Config{ + MaxCalls: 1000, + MaxRecordedBytes: 1024 * 1024, + }).New() for _, actual := range tt.calls { - store.Record(actual) + if errRecord := store.Record(actual); errRecord != nil { + t.Fatalf("failed to record call: %v", errRecord) + } } actual := summarizeCalls( @@ -497,15 +514,20 @@ func TestSummarizeCalls(t *testing.T) { func TestSummarizeCallsDoesNotExposeCapturedData( t *testing.T, ) { - store := &call.Store{} + store := call.NewStoreFactory( + &call.Config{ + MaxCalls: 1000, + MaxRecordedBytes: 1024 * 1024, + }).New() - store.Record(call.Call{ + if errRecord := store.Record(call.Call{ TestExecutionID: "execution-1", ServiceID: "service-1", HTTP: &call.HTTPCall{ Request: call.HTTPRequest{ - Method: "POST", - Path: "/events", + Method: "POST", + Path: "/events", + BodyComplete: true, Query: map[string][]string{ "token": {"secret-query"}, }, @@ -526,9 +548,11 @@ func TestSummarizeCallsDoesNotExposeCapturedData( Body: []byte(`{"secret":"response"}`), }, }, - }) + }); errRecord != nil { + t.Fatalf("failed to record call: %v", errRecord) + } - store.Record(call.Call{ + if errRecord := store.Record(call.Call{ TestExecutionID: "execution-1", ServiceID: "grpc-service", GRPC: &call.GRPCCall{ @@ -552,7 +576,9 @@ func TestSummarizeCallsDoesNotExposeCapturedData( Message: []byte(`{"secret": "response"}`), }, }, - }) + }); errRecord != nil { + t.Fatalf("failed to record call: %v", errRecord) + } actual := summarizeCalls( "execution-1", diff --git a/execute/worker/reporter/config.go b/execute/worker/reporter/config.go new file mode 100644 index 0000000..b121d4f --- /dev/null +++ b/execute/worker/reporter/config.go @@ -0,0 +1,22 @@ +package reporter + +type Config struct { + // DumpPayload enables dumping of request and response payloads in the + // test execution report. Applies to both HTTP and gRPC requests and responses. + // When disabled, payloads are replaced with a placeholder string. + DumpPayload bool `json:"dump_payload" yaml:"dump_payload" env:"DUMP_PAYLOAD"` + + // SkipRedactingHeadersMetadata disables redaction of builtin and + // additional sensitive headers and metadata. + SkipRedactingHeadersMetadata bool `json:"skip_redacting_headers_metadata" yaml:"skip_redacting_headers_metadata" env:"SKIP_REDACTING_HEADERS_METADATA"` + // RedactHeaders contains additional sensitive headers to redact. + RedactHeaders []string `json:"redact_headers" yaml:"redact_headers" env:"REDACT_HEADERS"` + // RedactMetadata contains additional sensitive metadata to redact. + RedactMetadata []string `json:"redact_metadata" yaml:"redact_metadata" env:"REDACT_METADATA"` + + // SkipRedactingQueryParams disables redaction of builtin and + // additional request query parameters in the test execution report. + SkipRedactingQueryParams bool `json:"skip_redacting_query_params" yaml:"skip_redacting_query_params" env:"SKIP_REDACTING_QUERY_PARAMS"` + // RedactQueryParams contains additional sensitive request query parameters to redact. + RedactQueryParams []string `json:"redact_query_params" yaml:"redact_query_params" env:"REDACT_QUERY_PARAMS"` +} diff --git a/execute/worker/reporter/grpc.go b/execute/worker/reporter/grpc.go new file mode 100644 index 0000000..edc5499 --- /dev/null +++ b/execute/worker/reporter/grpc.go @@ -0,0 +1,149 @@ +package reporter + +import ( + "maps" + "slices" + "strings" + + "github.com/e2engine/core/internal/util" + "github.com/e2engine/core/model" + "github.com/e2engine/core/model/matcher" +) + +func (r *Reporter) ensureGRPCResponseSummary() { + if r.report.Summary.Response == nil { + r.report.Summary.Response = &model.TestExecutionResponseSummary{} + } + + if r.report.Summary.Response.GRPC == nil { + r.report.Summary.Response.GRPC = &model.GRPCResponse{} + } +} + +func (r *Reporter) AddGRPCRequest(req *model.GRPCRequest) { + r.ensureNotFinalized() + + request := &model.GRPCRequest{ + Target: req.Target, + Service: req.Service, + Method: req.Method, + Metadata: r.redactMetadata(req.Metadata), + } + + if req.Message != nil { + if r.cfg.DumpPayload { + request.Message = maps.Clone(req.Message) + } else { + request.Message = map[string]any{ + dumpDisabled: nil, + } + } + } + + r.report.Summary.Request = &model.TestExecutionRequestSummary{ + GRPC: request, + } +} + +func (r *Reporter) AddMetadataDeviation( + key string, + deviation *model.TestExecutionDeviation, +) { + if deviation == nil { + return + } + + if !r.cfg.SkipRedactingHeadersMetadata { + if _, ok := r.redactedMetadata[strings.ToLower(key)]; ok { + redactedDeviation := *deviation + redactedDeviation.Expected = redacted + redactedDeviation.Actual = redacted + + r.AddDeviation(&redactedDeviation) + return + } + } + + r.AddDeviation(deviation) +} + +func (r *Reporter) AddGRPCResponseStatus(status string) { + r.ensureNotFinalized() + + r.ensureGRPCResponseSummary() + r.report.Summary.Response.GRPC.Status = status +} + +func (r *Reporter) AddGRPCResponseMetadata(metadata map[string][]string) { + r.ensureNotFinalized() + + r.ensureGRPCResponseSummary() + r.report.Summary.Response.GRPC.Metadata = r.redactMetadata( + selectMetadata( + metadata, + r.testSpec.Expect.GRPC.Metadata, + ), + ) +} + +func (r *Reporter) AddGRPCResponseMessage(message map[string]any) { + r.ensureNotFinalized() + r.ensureGRPCResponseSummary() + + switch { + case len(message) == 0: + r.report.Summary.Response.GRPC.Message = map[string]any{"": nil} + case !r.cfg.DumpPayload: + r.report.Summary.Response.GRPC.Message = map[string]any{dumpDisabled: nil} + default: + m := maps.Clone(message) + r.report.Summary.Response.GRPC.Message = m + } +} + +func selectMetadata( + actual map[string][]string, + expected map[string][]matcher.String, +) map[string][]string { + if len(expected) == 0 { + return nil + } + + result := make( + map[string][]string, + len(expected), + ) + + for key := range expected { + values, ok := actual[strings.ToLower(key)] + if ok { + result[key] = slices.Clone(values) + } + } + + if len(result) == 0 { + return nil + } + + return result +} + +func (r *Reporter) redactMetadata( + md map[string][]string, +) map[string][]string { + if r.cfg.SkipRedactingHeadersMetadata { + return util.CloneStringSliceMap(md) + } + + out := make(map[string][]string, len(md)) + + for key, values := range md { + if _, ok := r.redactedMetadata[strings.ToLower(key)]; ok { + out[key] = []string{redacted} + } else { + out[key] = slices.Clone(values) + } + } + + return out +} diff --git a/execute/worker/reporter/grpc_test.go b/execute/worker/reporter/grpc_test.go new file mode 100644 index 0000000..080d915 --- /dev/null +++ b/execute/worker/reporter/grpc_test.go @@ -0,0 +1,741 @@ +package reporter + +import ( + "reflect" + "testing" + + "github.com/e2engine/core/model" + "github.com/e2engine/core/model/matcher" +) + +func TestReporterAddGRPCRequest(t *testing.T) { + tests := []struct { + name string + + dumpPayload bool + wantMessage map[string]any + }{ + { + name: "payload disabled", + wantMessage: map[string]any{ + "": nil, + }, + }, + { + name: "payload enabled", + dumpPayload: true, + wantMessage: map[string]any{ + "name": "test", + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r := newReporterForTest( + &Config{ + DumpPayload: tt.dumpPayload, + }, + &model.TestSpec{}, + ) + + req := &model.GRPCRequest{ + Target: "127.0.0.1:8080", + Service: "example.Service", + Method: "Create", + Metadata: map[string][]string{ + "x-test": {"one", "two"}, + }, + Message: map[string]any{ + "name": "test", + }, + } + + r.AddGRPCRequest(req) + + if r.Result().Summary.Request == nil { + t.Fatal("expected request summary") + } + + actual := r.Result().Summary.Request.GRPC + + if actual == nil { + t.Fatal("expected gRPC request summary") + } + + if actual.Target != req.Target { + t.Errorf( + "expected target %q, got %q", + req.Target, + actual.Target, + ) + } + + if actual.Service != req.Service { + t.Errorf( + "expected service %q, got %q", + req.Service, + actual.Service, + ) + } + + if actual.Method != req.Method { + t.Errorf( + "expected method %q, got %q", + req.Method, + actual.Method, + ) + } + + if !reflect.DeepEqual( + actual.Metadata, + req.Metadata, + ) { + t.Errorf( + "expected metadata %+v, got %+v", + req.Metadata, + actual.Metadata, + ) + } + + if !reflect.DeepEqual( + actual.Message, + tt.wantMessage, + ) { + t.Errorf( + "expected message %+v, got %+v", + tt.wantMessage, + actual.Message, + ) + } + + req.Metadata["x-test"][0] = "changed" + req.Message["name"] = "changed" + + if actual.Metadata["x-test"][0] != "one" { + t.Error("stored metadata changed with source") + } + + if tt.dumpPayload && + actual.Message["name"] != "test" { + t.Error("stored message changed with source") + } + }) + } +} + +func TestReporterAddMetadataDeviation(t *testing.T) { + tests := []struct { + name string + key string + cfg Config + wantExpected string + wantActual string + }{ + { + name: "default sensitive metadata", + key: "Authorization", + wantExpected: redacted, + wantActual: redacted, + }, + { + name: "custom sensitive metadata", + key: "X-Private", + cfg: Config{ + RedactMetadata: []string{" x-private "}, + }, + wantExpected: redacted, + wantActual: redacted, + }, + { + name: "ordinary metadata", + key: "x-public", + wantExpected: "expected-token", + wantActual: "actual-token", + }, + { + name: "redaction explicitly disabled", + key: "authorization", + cfg: Config{ + SkipRedactingHeadersMetadata: true, + }, + wantExpected: "expected-token", + wantActual: "actual-token", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r := newReporterForTest( + &tt.cfg, + &model.TestSpec{}, + ) + + original := &model.TestExecutionDeviation{ + Field: "metadata." + tt.key, + Expected: "expected-token", + Actual: "actual-token", + } + + r.AddMetadataDeviation(tt.key, original) + + deviations := r.Result().Summary.Deviations + if len(deviations) != 1 { + t.Fatalf( + "expected 1 deviation, got %d", + len(deviations), + ) + } + + got := deviations[0] + + if got.Field != original.Field || + got.Expected != tt.wantExpected || + got.Actual != tt.wantActual { + t.Errorf( + "unexpected deviation: %+v", + got, + ) + } + + // Redaction must not modify the original deviation. + if original.Expected != "expected-token" || + original.Actual != "actual-token" { + t.Errorf( + "original deviation was modified: %+v", + original, + ) + } + }) + } +} + +func TestReporterAddMetadataDeviationNil(t *testing.T) { + r := newReporterForTest( + &Config{}, + &model.TestSpec{}, + ) + + r.AddMetadataDeviation("authorization", nil) + + if len(r.Result().Summary.Deviations) != 0 { + t.Errorf( + "expected no deviations, got %+v", + r.Result().Summary.Deviations, + ) + } +} + +func TestReporterAddGRPCRequestMetadataRedaction(t *testing.T) { + tests := []struct { + name string + cfg Config + want map[string][]string + }{ + { + name: "default sensitive metadata", + want: map[string][]string{ + "authorization": {redacted}, + "Authorization": {redacted}, + "cookie": {redacted}, + "x-api-key": {redacted}, + "x-test": {"visible"}, + }, + }, + { + name: "custom metadata", + cfg: Config{ + RedactMetadata: []string{" X-Test "}, + }, + want: map[string][]string{ + "authorization": {redacted}, + "Authorization": {redacted}, + "cookie": {redacted}, + "x-api-key": {redacted}, + "x-test": {redacted}, + }, + }, + { + name: "redaction explicitly disabled", + cfg: Config{ + SkipRedactingHeadersMetadata: true, + }, + want: map[string][]string{ + "authorization": {"Bearer secret"}, + "Authorization": {"Bearer another-secret"}, + "cookie": {"sid=secret"}, + "x-api-key": {"api-secret"}, + "x-test": {"visible"}, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r := newReporterForTest( + &tt.cfg, + &model.TestSpec{}, + ) + + req := &model.GRPCRequest{ + Target: "127.0.0.1:8080", + Service: "example.Service", + Method: "Create", + Metadata: map[string][]string{ + "authorization": {"Bearer secret"}, + "Authorization": {"Bearer another-secret"}, + "cookie": {"sid=secret"}, + "x-api-key": {"api-secret"}, + "x-test": {"visible"}, + }, + } + + original := make( + map[string][]string, + len(req.Metadata), + ) + + for key, values := range req.Metadata { + original[key] = append( + []string(nil), + values..., + ) + } + + r.AddGRPCRequest(req) + + actual := r.Result().Summary.Request.GRPC + if actual == nil { + t.Fatal("expected gRPC request summary") + } + + if !reflect.DeepEqual(actual.Metadata, tt.want) { + t.Errorf( + "expected metadata %+v, got %+v", + tt.want, + actual.Metadata, + ) + } + + // Reporting must not modify the original request. + if !reflect.DeepEqual(req.Metadata, original) { + t.Error("request metadata modified by reporting") + } + + // The report must own its copy of the metadata values. + req.Metadata["x-test"][0] = "changed" + + if actual.Metadata["x-test"][0] != tt.want["x-test"][0] { + t.Error("reported metadata changed with source") + } + }) + } +} + +func TestReporterAddGRPCRequestWithoutMessage(t *testing.T) { + r := newReporterForTest( + &Config{}, + &model.TestSpec{}, + ) + + r.AddGRPCRequest(&model.GRPCRequest{ + Service: "example.Service", + Method: "Create", + }) + + actual := r.Result().Summary.Request.GRPC + + if actual.Message != nil { + t.Errorf( + "expected nil message, got %+v", + actual.Message, + ) + } +} + +func TestReporterAddGRPCResponseStatus(t *testing.T) { + r := newReporterForTest( + &Config{}, + &model.TestSpec{}, + ) + + r.AddGRPCResponseStatus("OK") + + response := r.Result().Summary.Response + + if response == nil || response.GRPC == nil { + t.Fatal("expected gRPC response summary") + } + + if response.GRPC.Status != "OK" { + t.Errorf( + "expected status %q, got %q", + "OK", + response.GRPC.Status, + ) + } +} + +func TestReporterAddGRPCResponseMetadata(t *testing.T) { + spec := &model.TestSpec{ + Expect: model.ExpectSpec{ + GRPC: &model.GRPCResponsePattern{ + Metadata: map[string][]matcher.String{ + "x-included": { + { + Operator: matcher.StringMatchOperatorEquals, + Value: "expected", + }, + }, + "x-missing": { + { + Operator: matcher.StringMatchOperatorExists, + }, + }, + }, + }, + }, + } + + r := newReporterForTest( + &Config{}, + spec, + ) + + metadata := map[string][]string{ + "x-included": {"actual-1", "actual-2"}, + "x-unrelated": {"secret"}, + } + + r.AddGRPCResponseMetadata(metadata) + + actual := r.Result(). + Summary. + Response. + GRPC. + Metadata + + expected := map[string][]string{ + "x-included": {"actual-1", "actual-2"}, + } + + if !reflect.DeepEqual(actual, expected) { + t.Errorf( + "expected metadata %+v, got %+v", + expected, + actual, + ) + } + + metadata["x-included"][0] = "changed" + + if actual["x-included"][0] != "actual-1" { + t.Error("stored metadata changed with source") + } +} + +func TestReporterAddGRPCResponseMetadataRedaction(t *testing.T) { + exists := matcher.String{ + Operator: matcher.StringMatchOperatorExists, + } + + tests := []struct { + name string + cfg Config + want map[string][]string + }{ + { + name: "default and custom redaction", + cfg: Config{ + RedactMetadata: []string{" X-Private "}, + }, + want: map[string][]string{ + "set-cookie": {redacted}, + "x-private": {redacted}, + "x-public": {"visible"}, + }, + }, + { + name: "redaction explicitly disabled", + cfg: Config{ + RedactMetadata: []string{"x-private"}, + SkipRedactingHeadersMetadata: true, + }, + want: map[string][]string{ + "set-cookie": {"sid=secret"}, + "x-private": {"private-secret"}, + "x-public": {"visible"}, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + spec := &model.TestSpec{ + Expect: model.ExpectSpec{ + GRPC: &model.GRPCResponsePattern{ + Metadata: map[string][]matcher.String{ + "set-cookie": {exists}, + "x-private": {exists}, + "x-public": {exists}, + }, + }, + }, + } + + r := newReporterForTest( + &tt.cfg, + spec, + ) + + metadata := map[string][]string{ + "set-cookie": {"sid=secret"}, + "x-private": {"private-secret"}, + "x-public": {"visible"}, + "x-unrelated": {"unselected-secret"}, + } + + original := make( + map[string][]string, + len(metadata), + ) + + for key, values := range metadata { + original[key] = append( + []string(nil), + values..., + ) + } + + r.AddGRPCResponseMetadata(metadata) + + response := r.Result().Summary.Response + if response == nil || response.GRPC == nil { + t.Fatal("expected gRPC response summary") + } + + actual := response.GRPC.Metadata + + if !reflect.DeepEqual(actual, tt.want) { + t.Errorf( + "expected metadata %+v, got %+v", + tt.want, + actual, + ) + } + + // Response reporting must not mutate source metadata. + if !reflect.DeepEqual(metadata, original) { + t.Error("response metadata modified by reporting") + } + + // Unselected metadata must not appear in the report. + if _, ok := actual["x-unrelated"]; ok { + t.Error("unselected metadata included in report") + } + + // Selected metadata must be copied. + metadata["x-public"][0] = "changed" + + if actual["x-public"][0] != "visible" { + t.Error("reported metadata changed with source") + } + }) + } +} + +func TestSelectMetadata(t *testing.T) { + equals := func(value string) matcher.String { + return matcher.String{ + Operator: matcher.StringMatchOperatorEquals, + Value: value, + } + } + + exists := matcher.String{ + Operator: matcher.StringMatchOperatorExists, + } + + nonempty := matcher.String{ + Operator: matcher.StringMatchOperatorNonEmpty, + } + + tests := []struct { + name string + + actual map[string][]string + expected map[string][]matcher.String + + want map[string][]string + }{ + { + name: "no expected metadata", + actual: map[string][]string{ + "x-test": {"value"}, + }, + }, + { + name: "expected metadata absent", + actual: map[string][]string{ + "x-test": {"value"}, + }, + expected: map[string][]matcher.String{ + "x-missing": {equals("expected")}, + }, + }, + { + name: "selected metadata", + actual: map[string][]string{ + "x-one": {"1"}, + "x-two": {"2"}, + "x-other": {"other"}, + }, + expected: map[string][]matcher.String{ + "x-one": {equals("expected")}, + "x-two": {equals("expected")}, + "x-missing": {equals("expected")}, + }, + want: map[string][]string{ + "x-one": {"1"}, + "x-two": {"2"}, + }, + }, + { + name: "exists matcher", + actual: map[string][]string{ + "x-test": {""}, + }, + expected: map[string][]matcher.String{ + "x-test": {exists}, + }, + want: map[string][]string{ + "x-test": {""}, + }, + }, + { + name: "nonempty matcher", + actual: map[string][]string{ + "x-test": {"value"}, + }, + expected: map[string][]matcher.String{ + "x-test": {nonempty}, + }, + want: map[string][]string{ + "x-test": {"value"}, + }, + }, + { + name: "expected key casing preserved", + actual: map[string][]string{ + "x-request-id": {"123"}, + }, + expected: map[string][]matcher.String{ + "X-Request-Id": {exists}, + }, + want: map[string][]string{ + "X-Request-Id": {"123"}, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + actual := selectMetadata( + tt.actual, + tt.expected, + ) + + if !reflect.DeepEqual(actual, tt.want) { + t.Errorf( + "expected %+v, got %+v", + tt.want, + actual, + ) + } + }) + } +} + +func TestReporterAddGRPCResponseMessage(t *testing.T) { + tests := []struct { + name string + + dumpPayload bool + message map[string]any + want map[string]any + }{ + { + name: "payload disabled", + message: map[string]any{ + "name": "test", + }, + want: map[string]any{ + "": nil, + }, + }, + { + name: "payload enabled", + dumpPayload: true, + message: map[string]any{ + "name": "test", + }, + want: map[string]any{ + "name": "test", + }, + }, + { + name: "empty message with dumping disabled", + message: map[string]any{}, + want: map[string]any{ + "": nil, + }, + }, + { + name: "empty message with dumping enabled", + dumpPayload: true, + message: map[string]any{}, + want: map[string]any{ + "": nil, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r := newReporterForTest( + &Config{ + DumpPayload: tt.dumpPayload, + }, + &model.TestSpec{}, + ) + + r.AddGRPCResponseMessage(tt.message) + + response := r.Result().Summary.Response + + if response == nil || response.GRPC == nil { + t.Fatal("expected gRPC response summary") + } + + if !reflect.DeepEqual( + response.GRPC.Message, + tt.want, + ) { + t.Errorf( + "expected message %+v, got %+v", + tt.want, + response.GRPC.Message, + ) + } + + if len(tt.message) > 0 { + tt.message["name"] = "changed" + + if tt.dumpPayload && + response.GRPC.Message["name"] != "test" { + t.Error("stored message changed with source") + } + } + }) + } +} diff --git a/execute/worker/reporter/http.go b/execute/worker/reporter/http.go new file mode 100644 index 0000000..e1c4e0c --- /dev/null +++ b/execute/worker/reporter/http.go @@ -0,0 +1,210 @@ +package reporter + +import ( + "encoding/json" + "net/http" + "net/url" + "slices" + "strings" + + "github.com/e2engine/core/internal/util" + "github.com/e2engine/core/model" + "github.com/e2engine/core/model/matcher" +) + +func (r *Reporter) ensureHTTPResponseSummary() { + if r.report.Summary.Response == nil { + r.report.Summary.Response = &model.TestExecutionResponseSummary{} + } + + if r.report.Summary.Response.HTTP == nil { + r.report.Summary.Response.HTTP = &model.HTTPResponse{} + } +} + +func (r *Reporter) AddHTTPRequest(req *http.Request) { + r.ensureNotFinalized() + + request := &model.HTTPRequest{ + Method: req.Method, + URL: r.redactURL(req.URL), + Headers: r.redactHeaders(req.Header), + } + + if r.testSpec.Request.HTTP.Body != "" { + switch { + case !r.cfg.DumpPayload: + request.Body = dumpDisabled + default: + request.Body = r.testSpec.Request.HTTP.Body + } + } + + if r.testSpec.Request.HTTP.BodyJSON != "" { + switch { + case !r.cfg.DumpPayload: + request.BodyJSON = dumpDisabled + default: + request.BodyJSON = string(util.CompactJSON( + json.RawMessage(r.testSpec.Request.HTTP.BodyJSON), + )) + } + } + + r.report.Summary.Request = &model.TestExecutionRequestSummary{ + HTTP: request, + } +} + +func (r *Reporter) AddHTTPResponseStatus(status int) { + r.ensureNotFinalized() + + r.ensureHTTPResponseSummary() + r.report.Summary.Response.HTTP.StatusCode = status +} + +func (r *Reporter) AddHTTPResponseHeaders(headers http.Header) { + r.ensureNotFinalized() + + r.ensureHTTPResponseSummary() + r.report.Summary.Response.HTTP.Headers = r.redactHeaders( + selectHeaders( + headers, + r.testSpec.Expect.HTTP.Headers, + ), + ) +} + +func (r *Reporter) AddHeadersDeviation( + header string, + deviation *model.TestExecutionDeviation, +) { + if deviation == nil { + return + } + + if !r.cfg.SkipRedactingHeadersMetadata { + if _, ok := r.redactedHeaders[strings.ToLower(header)]; ok { + redactedDeviation := *deviation + redactedDeviation.Expected = redacted + redactedDeviation.Actual = redacted + + r.AddDeviation(&redactedDeviation) + return + } + } + + r.AddDeviation(deviation) +} + +func (r *Reporter) AddHTTPResponseBody(body []byte) { + r.ensureNotFinalized() + r.ensureHTTPResponseSummary() + + switch { + case len(body) == 0: + case !r.cfg.DumpPayload: + r.report.Summary.Response.HTTP.Body = dumpDisabled + default: + r.report.Summary.Response.HTTP.Body = string(body) + } +} + +func (r *Reporter) AddHTTPResponseBodyJSON(body []byte) { + r.ensureNotFinalized() + r.ensureHTTPResponseSummary() + + switch { + case len(body) == 0: + case !r.cfg.DumpPayload: + r.report.Summary.Response.HTTP.BodyJSON = dumpDisabled + default: + r.report.Summary.Response.HTTP.BodyJSON = string(body) + } +} + +func selectHeaders( + actual http.Header, + expected map[string][]matcher.String, +) map[string][]string { + if len(expected) == 0 { + return nil + } + + result := make( + map[string][]string, + len(expected), + ) + + for k := range expected { + values := actual.Values(k) + if len(values) > 0 { + result[k] = slices.Clone(values) + } + } + + if len(result) == 0 { + return nil + } + + return result +} + +func (r *Reporter) redactHeaders(headers http.Header) http.Header { + if r.cfg.SkipRedactingHeadersMetadata { + return headers.Clone() + } + + out := make(http.Header, len(headers)) + for k, v := range headers { + if _, ok := r.redactedHeaders[strings.ToLower(k)]; ok { + out[k] = []string{redacted} + } else { + out[k] = slices.Clone(v) + } + } + + return out +} + +func (r *Reporter) redactURL(u *url.URL) string { + if u == nil { + return "" + } + + if r.cfg.SkipRedactingQueryParams { + return u.String() + } + + redactedURL := *u + + changed := false + + if redactedURL.User != nil { + username := redactedURL.User.Username() + + if _, hasPassword := redactedURL.User.Password(); hasPassword { + redactedURL.User = url.UserPassword(username, redacted) + changed = true + } + } + + query := redactedURL.Query() + + for key, values := range query { + if _, ok := r.redactedQueryParams[strings.ToLower(key)]; ok { + for i := range values { + values[i] = redacted + } + changed = true + } + } + + if !changed { + return u.String() + } + + redactedURL.RawQuery = query.Encode() + + return redactedURL.String() +} diff --git a/execute/worker/reporter/http_test.go b/execute/worker/reporter/http_test.go new file mode 100644 index 0000000..408a093 --- /dev/null +++ b/execute/worker/reporter/http_test.go @@ -0,0 +1,970 @@ +package reporter + +import ( + "net/http" + "net/url" + "reflect" + "testing" + + "github.com/e2engine/core/model" + "github.com/e2engine/core/model/matcher" +) + +func TestReporterAddHTTPRequest(t *testing.T) { + tests := []struct { + name string + + dumpPayload bool + + expectedBody string + expectedBodyJSON string + }{ + { + name: "payload disabled", + expectedBody: "", + expectedBodyJSON: "", + }, + { + name: "payload enabled", + dumpPayload: true, + expectedBody: "request body", + expectedBodyJSON: `{"name":"test"}`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + spec := &model.TestSpec{ + Request: model.RequestSpec{ + HTTP: &model.HTTPRequest{ + Body: "request body", + BodyJSON: `{ + "name": "test" + }`, + }, + }, + } + + r := newReporterForTest( + &Config{ + DumpPayload: tt.dumpPayload, + }, + spec, + ) + + u, err := url.Parse( + "http://example.com/resource?a=1", + ) + if err != nil { + t.Fatal(err) + } + + req := &http.Request{ + Method: http.MethodPost, + URL: u, + Header: http.Header{ + "X-Test": {"one", "two"}, + }, + } + + r.AddHTTPRequest(req) + + if r.Result().Summary.Request == nil { + t.Fatal("expected request summary") + } + + actual := r.Result().Summary.Request.HTTP + + if actual == nil { + t.Fatal("expected HTTP request summary") + } + + if actual.Method != http.MethodPost { + t.Errorf( + "expected method %q, got %q", + http.MethodPost, + actual.Method, + ) + } + + if actual.URL != u.String() { + t.Errorf( + "expected URL %q, got %q", + u.String(), + actual.URL, + ) + } + + if !reflect.DeepEqual( + actual.Headers, + map[string][]string(req.Header), + ) { + t.Errorf( + "expected headers %+v, got %+v", + req.Header, + actual.Headers, + ) + } + + if actual.Body != tt.expectedBody { + t.Errorf( + "expected body %q, got %q", + tt.expectedBody, + actual.Body, + ) + } + + if actual.BodyJSON != tt.expectedBodyJSON { + t.Errorf( + "expected JSON body %q, got %q", + tt.expectedBodyJSON, + actual.BodyJSON, + ) + } + + req.Header["X-Test"][0] = "changed" + + if actual.Headers["X-Test"][0] != "one" { + t.Error("stored headers changed with source") + } + }) + } +} + +func TestReporterAddHTTPRequestWithoutBody(t *testing.T) { + spec := &model.TestSpec{ + Request: model.RequestSpec{ + HTTP: &model.HTTPRequest{}, + }, + } + + r := newReporterForTest( + &Config{}, + spec, + ) + + req, err := http.NewRequest( + http.MethodGet, + "http://example.com/resource", + nil, + ) + if err != nil { + t.Fatal(err) + } + + r.AddHTTPRequest(req) + + actual := r.Result().Summary.Request.HTTP + + if actual.Body != "" || actual.BodyJSON != "" { + t.Errorf( + "expected omitted body fields, got body=%q body_json=%q", + actual.Body, + actual.BodyJSON, + ) + } +} + +func TestReporterAddHeadersDeviation(t *testing.T) { + tests := []struct { + name string + header string + cfg Config + wantExpected string + wantActual string + }{ + { + name: "default sensitive header", + header: "Authorization", + wantExpected: redacted, + wantActual: redacted, + }, + { + name: "custom sensitive header", + header: "X-Private", + cfg: Config{ + RedactHeaders: []string{" x-private "}, + }, + wantExpected: redacted, + wantActual: redacted, + }, + { + name: "ordinary header", + header: "X-Public", + wantExpected: "expected-token", + wantActual: "actual-token", + }, + { + name: "redaction explicitly disabled", + header: "authorization", + cfg: Config{ + SkipRedactingHeadersMetadata: true, + }, + wantExpected: "expected-token", + wantActual: "actual-token", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r := newReporterForTest( + &tt.cfg, + &model.TestSpec{}, + ) + + original := &model.TestExecutionDeviation{ + Field: "headers." + tt.header, + Expected: "expected-token", + Actual: "actual-token", + } + + r.AddHeadersDeviation(tt.header, original) + + deviations := r.Result().Summary.Deviations + if len(deviations) != 1 { + t.Fatalf( + "expected 1 deviation, got %d", + len(deviations), + ) + } + + got := deviations[0] + + if got.Field != original.Field || + got.Expected != tt.wantExpected || + got.Actual != tt.wantActual { + t.Errorf( + "unexpected deviation: %+v", + got, + ) + } + + // Redaction must not modify the original deviation. + if original.Expected != "expected-token" || + original.Actual != "actual-token" { + t.Errorf( + "original deviation was modified: %+v", + original, + ) + } + }) + } +} + +func TestReporterAddHeadersDeviationNil(t *testing.T) { + r := newReporterForTest( + &Config{}, + &model.TestSpec{}, + ) + + r.AddHeadersDeviation("Authorization", nil) + + if len(r.Result().Summary.Deviations) != 0 { + t.Errorf( + "expected no deviations, got %+v", + r.Result().Summary.Deviations, + ) + } +} + +func TestReporterAddHTTPRequestQueryRedaction(t *testing.T) { + tests := []struct { + name string + cfg Config + wantQuery url.Values + }{ + { + name: "default sensitive query parameters", + wantQuery: url.Values{ + "access_token": {redacted}, + "API_KEY": {redacted, redacted}, + "page": {"2"}, + "private": {"custom-secret"}, + }, + }, + { + name: "custom sensitive query parameter", + cfg: Config{ + RedactQueryParams: []string{" PRIVATE "}, + }, + wantQuery: url.Values{ + "access_token": {redacted}, + "API_KEY": {redacted, redacted}, + "page": {"2"}, + "private": {redacted}, + }, + }, + { + name: "redaction explicitly disabled", + cfg: Config{ + RedactQueryParams: []string{"private"}, + SkipRedactingQueryParams: true, + }, + wantQuery: url.Values{ + "access_token": {"access-secret"}, + "API_KEY": {"key-one", "key-two"}, + "page": {"2"}, + "private": {"custom-secret"}, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r := newReporterForTest( + &tt.cfg, + &model.TestSpec{ + Request: model.RequestSpec{ + HTTP: &model.HTTPRequest{}, + }, + }, + ) + + req, err := http.NewRequest( + http.MethodGet, + "http://example.com/resource?access_token=access-secret&API_KEY=key-one&API_KEY=key-two&page=2&private=custom-secret", + nil, + ) + if err != nil { + t.Fatal(err) + } + + originalURL := req.URL.String() + + r.AddHTTPRequest(req) + + // Reporting must not modify the outgoing request. + if got := req.URL.String(); got != originalURL { + t.Errorf( + "request URL modified: got %q, want %q", + got, + originalURL, + ) + } + + reportedURL, err := url.Parse( + r.Result().Summary.Request.HTTP.URL, + ) + if err != nil { + t.Fatalf("invalid reported URL: %v", err) + } + + // Redaction must preserve the URL destination and path. + if reportedURL.Scheme != "http" || + reportedURL.Host != "example.com" || + reportedURL.Path != "/resource" { + t.Errorf( + "unexpected reported URL: %q", + reportedURL.String(), + ) + } + + if got := reportedURL.Query(); !reflect.DeepEqual(got, tt.wantQuery) { + t.Errorf( + "reported query: got %#v, want %#v", + got, + tt.wantQuery, + ) + } + }) + } +} + +func TestReporterAddHTTPRequestUserinfoRedaction(t *testing.T) { + tests := []struct { + name string + cfg Config + url string + want string + }{ + { + name: "password and sensitive query", + url: "http://admin:secret123@example.com/resource?access_token=abc123&limit=10", + want: "http://admin:%3Credacted%3E@example.com/resource?access_token=%3Credacted%3E&limit=10", + }, + { + name: "password without query", + url: "http://admin:secret123@example.com/resource", + want: "http://admin:%3Credacted%3E@example.com/resource", + }, + { + name: "empty password", + url: "http://admin:@example.com/resource", + want: "http://admin:%3Credacted%3E@example.com/resource", + }, + { + name: "username only", + url: "http://admin@example.com/resource", + want: "http://admin@example.com/resource", + }, + { + name: "redaction disabled", + cfg: Config{ + SkipRedactingQueryParams: true, + }, + url: "http://admin:secret123@example.com/resource?access_token=abc123", + want: "http://admin:secret123@example.com/resource?access_token=abc123", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r := newReporterForTest( + &tt.cfg, + &model.TestSpec{ + Request: model.RequestSpec{ + HTTP: &model.HTTPRequest{}, + }, + }, + ) + + req, err := http.NewRequest( + http.MethodGet, + tt.url, + nil, + ) + if err != nil { + t.Fatal(err) + } + + originalURL := req.URL.String() + + r.AddHTTPRequest(req) + + if got := r.Result().Summary.Request.HTTP.URL; got != tt.want { + t.Errorf( + "reported URL: got %q, want %q", + got, + tt.want, + ) + } + + // Reporting must not modify the outgoing request. + if got := req.URL.String(); got != originalURL { + t.Errorf( + "request URL modified: got %q, want %q", + got, + originalURL, + ) + } + }) + } +} + +func TestReporterAddHTTPRequestURLWithoutQuery(t *testing.T) { + r := newReporterForTest( + &Config{}, + &model.TestSpec{ + Request: model.RequestSpec{ + HTTP: &model.HTTPRequest{}, + }, + }, + ) + + req, err := http.NewRequest( + http.MethodGet, + "http://example.com/resource", + nil, + ) + if err != nil { + t.Fatal(err) + } + + r.AddHTTPRequest(req) + + if got := r.Result().Summary.Request.HTTP.URL; got != req.URL.String() { + t.Errorf( + "reported URL: got %q, want %q", + got, + req.URL.String(), + ) + } +} + +func TestReporterAddHTTPResponseStatus(t *testing.T) { + r := newReporterForTest( + &Config{}, + &model.TestSpec{}, + ) + + r.AddHTTPResponseStatus(http.StatusCreated) + + response := r.Result().Summary.Response + + if response == nil || response.HTTP == nil { + t.Fatal("expected HTTP response summary") + } + + if response.HTTP.StatusCode != http.StatusCreated { + t.Errorf( + "expected status %d, got %d", + http.StatusCreated, + response.HTTP.StatusCode, + ) + } +} + +func TestReporterAddHTTPResponseHeaders(t *testing.T) { + spec := &model.TestSpec{ + Expect: model.ExpectSpec{ + HTTP: &model.HTTPResponsePattern{ + Headers: map[string][]matcher.String{ + "X-Included": { + { + Operator: matcher.StringMatchOperatorEquals, + Value: "expected", + }, + }, + "X-Missing": { + { + Operator: matcher.StringMatchOperatorExists, + }, + }, + }, + }, + }, + } + + r := newReporterForTest( + &Config{}, + spec, + ) + + headers := http.Header{ + "X-Included": {"actual-1", "actual-2"}, + "X-Unrelated": {"secret"}, + } + + r.AddHTTPResponseHeaders(headers) + + actual := r.Result().Summary.Response.HTTP.Headers + + expected := map[string][]string{ + "X-Included": {"actual-1", "actual-2"}, + } + + if !reflect.DeepEqual(actual, expected) { + t.Errorf( + "expected headers %+v, got %+v", + expected, + actual, + ) + } + + headers["X-Included"][0] = "changed" + + if actual["X-Included"][0] != "actual-1" { + t.Error("stored headers changed with source") + } +} + +func TestReporterAddHTTPRequestHeaderRedaction(t *testing.T) { + tests := []struct { + name string + cfg Config + want map[string][]string + }{ + { + name: "default sensitive headers", + want: http.Header{ + "Authorization": {redacted}, + "authorization": {redacted}, + "Cookie": {redacted}, + "X-Api-Key": {redacted}, + "X-Test": {"visible"}, + }, + }, + { + name: "custom header", + cfg: Config{ + RedactHeaders: []string{" X-Test "}, + }, + want: http.Header{ + "Authorization": {redacted}, + "authorization": {redacted}, + "Cookie": {redacted}, + "X-Api-Key": {redacted}, + "X-Test": {redacted}, + }, + }, + { + name: "redaction explicitly disabled", + cfg: Config{ + SkipRedactingHeadersMetadata: true, + }, + want: http.Header{ + "Authorization": {"Bearer secret"}, + "authorization": {"Bearer another-secret"}, + "Cookie": {"sid=secret"}, + "X-Api-Key": {"api-secret"}, + "X-Test": {"visible"}, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + spec := &model.TestSpec{ + Request: model.RequestSpec{ + HTTP: &model.HTTPRequest{}, + }, + } + + r := newReporterForTest( + &tt.cfg, + spec, + ) + + req, err := http.NewRequest( + http.MethodGet, + "http://example.com/", + nil, + ) + if err != nil { + t.Fatal(err) + } + + req.Header = http.Header{ + "Authorization": {"Bearer secret"}, + "authorization": {"Bearer another-secret"}, + "Cookie": {"sid=secret"}, + "X-Api-Key": {"api-secret"}, + "X-Test": {"visible"}, + } + + original := req.Header.Clone() + + r.AddHTTPRequest(req) + + got := r.Result().Summary.Request.HTTP.Headers + + if !reflect.DeepEqual(got, tt.want) { + t.Errorf( + "expected headers %#v, got %#v", + tt.want, + got, + ) + } + + // Reporting must not modify the outgoing request. + if !reflect.DeepEqual(req.Header, original) { + t.Error("request headers modified by reporting") + } + + // The report must own its copy of the header values. + req.Header["X-Test"][0] = "changed" + + if got["X-Test"][0] != tt.want["X-Test"][0] { + t.Error("reported headers changed with source") + } + }) + } +} + +func TestReporterAddHTTPResponseHeadersRedaction(t *testing.T) { + tests := []struct { + name string + cfg Config + want map[string][]string + }{ + { + name: "default and custom redaction", + cfg: Config{ + RedactHeaders: []string{" x-private "}, + }, + want: map[string][]string{ + "set-cookie": {redacted}, + "x-private": {redacted}, + "X-Public": {"visible"}, + }, + }, + { + name: "redaction explicitly disabled", + cfg: Config{ + RedactHeaders: []string{"x-private"}, + SkipRedactingHeadersMetadata: true, + }, + want: map[string][]string{ + "set-cookie": {"sid=secret"}, + "x-private": {"secret"}, + "X-Public": {"visible"}, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + exists := matcher.String{ + Operator: matcher.StringMatchOperatorExists, + } + + spec := &model.TestSpec{ + Expect: model.ExpectSpec{ + HTTP: &model.HTTPResponsePattern{ + Headers: map[string][]matcher.String{ + "set-cookie": {exists}, + "x-private": {exists}, + "X-Public": {exists}, + }, + }, + }, + } + + r := newReporterForTest( + &tt.cfg, + spec, + ) + + headers := http.Header{ + "Set-Cookie": {"sid=secret"}, + "X-Private": {"secret"}, + "X-Public": {"visible"}, + "X-Unselected": {"do not include"}, + } + + original := headers.Clone() + + r.AddHTTPResponseHeaders(headers) + + got := r.Result().Summary.Response.HTTP.Headers + + if !reflect.DeepEqual(got, tt.want) { + t.Errorf( + "expected headers %#v, got %#v", + tt.want, + got, + ) + } + + if !reflect.DeepEqual(headers, original) { + t.Error("response headers modified by reporting") + } + }) + } +} + +func TestSelectHeaders(t *testing.T) { + equals := func(value string) matcher.String { + return matcher.String{ + Operator: matcher.StringMatchOperatorEquals, + Value: value, + } + } + + exists := matcher.String{ + Operator: matcher.StringMatchOperatorExists, + } + + nonempty := matcher.String{ + Operator: matcher.StringMatchOperatorNonEmpty, + } + + tests := []struct { + name string + + actual http.Header + expected map[string][]matcher.String + + want map[string][]string + }{ + { + name: "no expected headers", + actual: http.Header{ + "X-Test": {"value"}, + }, + }, + { + name: "expected header absent", + actual: http.Header{ + "X-Test": {"value"}, + }, + expected: map[string][]matcher.String{ + "X-Missing": {equals("expected")}, + }, + }, + { + name: "selected headers", + actual: http.Header{ + "X-One": {"1"}, + "X-Two": {"2"}, + "X-Other": {"other"}, + }, + expected: map[string][]matcher.String{ + "X-One": {equals("expected")}, + "X-Two": {equals("expected")}, + "X-Missing": {equals("expected")}, + }, + want: map[string][]string{ + "X-One": {"1"}, + "X-Two": {"2"}, + }, + }, + { + name: "exists matcher", + actual: http.Header{ + "X-Test": {""}, + }, + expected: map[string][]matcher.String{ + "X-Test": {exists}, + }, + want: map[string][]string{ + "X-Test": {""}, + }, + }, + { + name: "nonempty matcher", + actual: http.Header{ + "X-Test": {"value"}, + }, + expected: map[string][]matcher.String{ + "X-Test": {nonempty}, + }, + want: map[string][]string{ + "X-Test": {"value"}, + }, + }, + { + name: "case insensitive header lookup", + actual: http.Header{ + "X-Request-Id": {"123"}, + }, + expected: map[string][]matcher.String{ + "x-request-id": {nonempty}, + }, + want: map[string][]string{ + "x-request-id": {"123"}, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + actual := selectHeaders( + tt.actual, + tt.expected, + ) + + if !reflect.DeepEqual(actual, tt.want) { + t.Errorf( + "expected %+v, got %+v", + tt.want, + actual, + ) + } + }) + } +} + +func TestReporterAddHTTPResponseBody(t *testing.T) { + tests := []struct { + name string + dumpPayload bool + body []byte + want string + }{ + { + name: "payload disabled", + body: []byte("body"), + want: "", + }, + { + name: "payload enabled", + dumpPayload: true, + body: []byte("body"), + want: "body", + }, + { + name: "empty body with dumping disabled", + body: []byte{}, + }, + { + name: "empty body with dumping enabled", + dumpPayload: true, + body: []byte{}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r := newReporterForTest( + &Config{ + DumpPayload: tt.dumpPayload, + }, + &model.TestSpec{}, + ) + + r.AddHTTPResponseBody(tt.body) + + response := r.Result().Summary.Response + + if response == nil || response.HTTP == nil { + t.Fatal("expected HTTP response summary") + } + + if response.HTTP.Body != tt.want { + t.Errorf( + "expected body %q, got %q", + tt.want, + response.HTTP.Body, + ) + } + }) + } +} + +func TestReporterAddHTTPResponseBodyJSON(t *testing.T) { + tests := []struct { + name string + dumpPayload bool + body []byte + want string + }{ + { + name: "payload disabled", + body: []byte(`{"name":"test"}`), + want: "", + }, + { + name: "payload enabled", + dumpPayload: true, + body: []byte(`{"name":"test"}`), + want: `{"name":"test"}`, + }, + { + name: "empty body with dumping disabled", + body: []byte{}, + }, + { + name: "empty body with dumping enabled", + dumpPayload: true, + body: []byte{}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r := newReporterForTest( + &Config{ + DumpPayload: tt.dumpPayload, + }, + &model.TestSpec{}, + ) + + r.AddHTTPResponseBodyJSON(tt.body) + + response := r.Result().Summary.Response + + if response == nil || response.HTTP == nil { + t.Fatal("expected HTTP response summary") + } + + if response.HTTP.BodyJSON != tt.want { + t.Errorf( + "expected JSON body %q, got %q", + tt.want, + response.HTTP.BodyJSON, + ) + } + }) + } +} diff --git a/execute/worker/reporter/reporter.go b/execute/worker/reporter/reporter.go index da601c7..740fddd 100644 --- a/execute/worker/reporter/reporter.go +++ b/execute/worker/reporter/reporter.go @@ -1,25 +1,21 @@ package reporter import ( - "encoding/json" - "net/http" + "strings" "time" "github.com/e2engine/core/execute" "github.com/e2engine/core/execute/call" - "github.com/e2engine/core/internal/util" "github.com/e2engine/core/model" - "github.com/e2engine/core/model/matcher" ) type Reporter struct { - cfg *Config - testSpec *model.TestSpec - report *execute.TestExecutionResult -} - -type Config struct { - DumpPayload bool `json:"dump_payload" yaml:"dump_payload" env:"DUMP_PAYLOAD"` + cfg *Config + testSpec *model.TestSpec + report *execute.TestExecutionResult + redactedHeaders map[string]struct{} + redactedMetadata map[string]struct{} + redactedQueryParams map[string]struct{} } func New( @@ -27,6 +23,54 @@ func New( testSpec *model.TestSpec, executionID, testSuiteExecutionID string, ) *Reporter { + if cfg == nil { + // because there are no defaults in config + cfg = &Config{} + } + + const ( + authorization = "authorization" + proxyAuthorization = "proxy-authorization" + cookie = "cookie" + setCookie = "set-cookie" + xAPIKey = "x-api-key" + ) + redactedHeaders := map[string]struct{}{ + authorization: {}, + proxyAuthorization: {}, + cookie: {}, + setCookie: {}, + xAPIKey: {}, + } + for _, h := range cfg.RedactHeaders { + redactedHeaders[strings.ToLower(strings.TrimSpace(h))] = struct{}{} + } + + redactedMetadata := map[string]struct{}{ + authorization: {}, + proxyAuthorization: {}, + cookie: {}, + setCookie: {}, + xAPIKey: {}, + } + for _, m := range cfg.RedactMetadata { + redactedMetadata[strings.ToLower(strings.TrimSpace(m))] = struct{}{} + } + + redactedQueryParams := map[string]struct{}{ + "access_token": {}, + "refresh_token": {}, + "id_token": {}, + "token": {}, + "api_key": {}, + "apikey": {}, + "password": {}, + "client_secret": {}, + } + for _, q := range cfg.RedactQueryParams { + redactedQueryParams[strings.ToLower(strings.TrimSpace(q))] = struct{}{} + } + return &Reporter{ cfg: cfg, testSpec: testSpec, @@ -35,6 +79,9 @@ func New( TestSuiteExecutionID: testSuiteExecutionID, Summary: &model.TestExecutionSummary{}, }, + redactedHeaders: redactedHeaders, + redactedMetadata: redactedMetadata, + redactedQueryParams: redactedQueryParams, } } @@ -86,7 +133,10 @@ func (r *Reporter) AddDeviation(deviation *model.TestExecutionDeviation) { r.report.Summary.Deviations = append(r.report.Summary.Deviations, *deviation) } -const dumpDisabled = "" +const ( + dumpDisabled = "" + redacted = "" +) func (r *Reporter) AddPayloadDeviation(deviation *model.PayloadDeviation) { if deviation == nil { @@ -118,210 +168,3 @@ func (r *Reporter) AddPayloadDeviation(deviation *model.PayloadDeviation) { r.report.Summary.Deviations = append(r.report.Summary.Deviations, d) } - -func (r *Reporter) AddHTTPRequest(req *http.Request) { - r.ensureNotFinalized() - - request := &model.HTTPRequest{ - Method: req.Method, - URL: req.URL.String(), - Headers: req.Header.Clone(), - } - - if r.testSpec.Request.HTTP.Body != "" { - switch { - case !r.cfg.DumpPayload: - request.Body = dumpDisabled - default: - request.Body = r.testSpec.Request.HTTP.Body - } - } - - if r.testSpec.Request.HTTP.BodyJSON != "" { - switch { - case !r.cfg.DumpPayload: - request.BodyJSON = dumpDisabled - default: - request.BodyJSON = string(util.CompactJSON( - json.RawMessage(r.testSpec.Request.HTTP.BodyJSON), - )) - } - } - - r.report.Summary.Request = &model.TestExecutionRequestSummary{ - HTTP: request, - } -} - -func (r *Reporter) ensureHTTPResponseSummary() { - if r.report.Summary.Response == nil { - r.report.Summary.Response = &model.TestExecutionResponseSummary{} - } - - if r.report.Summary.Response.HTTP == nil { - r.report.Summary.Response.HTTP = &model.HTTPResponse{} - } -} - -func (r *Reporter) AddHTTPResponseStatus(status int) { - r.ensureNotFinalized() - - r.ensureHTTPResponseSummary() - r.report.Summary.Response.HTTP.StatusCode = status -} - -func (r *Reporter) AddHTTPResponseHeaders(headers http.Header) { - r.ensureNotFinalized() - - r.ensureHTTPResponseSummary() - r.report.Summary.Response.HTTP.Headers = selectHeaders( - headers, - r.testSpec.Expect.HTTP.Headers, - ) -} - -func selectHeaders( - actual http.Header, - expected map[string][]matcher.String, -) map[string][]string { - if len(expected) == 0 { - return nil - } - - result := make( - map[string][]string, - len(expected), - ) - - for k := range expected { - values := actual.Values(k) - if len(values) > 0 { - result[k] = util.CloneStringSlice(values) - } - } - - if len(result) == 0 { - return nil - } - - return result -} - -func (r *Reporter) AddHTTPResponseBody(body []byte) { - r.ensureNotFinalized() - r.ensureHTTPResponseSummary() - - switch { - case len(body) == 0: - case !r.cfg.DumpPayload: - r.report.Summary.Response.HTTP.Body = dumpDisabled - default: - r.report.Summary.Response.HTTP.Body = string(body) - } -} - -func (r *Reporter) AddHTTPResponseBodyJSON(body []byte) { - r.ensureNotFinalized() - r.ensureHTTPResponseSummary() - - switch { - case len(body) == 0: - case !r.cfg.DumpPayload: - r.report.Summary.Response.HTTP.BodyJSON = dumpDisabled - default: - r.report.Summary.Response.HTTP.BodyJSON = string(body) - } -} - -func (r *Reporter) ensureGRPCResponseSummary() { - if r.report.Summary.Response == nil { - r.report.Summary.Response = &model.TestExecutionResponseSummary{} - } - - if r.report.Summary.Response.GRPC == nil { - r.report.Summary.Response.GRPC = &model.GRPCResponse{} - } -} - -func (r *Reporter) AddGRPCRequest(req *model.GRPCRequest) { - r.ensureNotFinalized() - - request := &model.GRPCRequest{ - Target: req.Target, - Service: req.Service, - Method: req.Method, - Metadata: util.CloneStringSliceMap(req.Metadata), - } - - if req.Message != nil { - if r.cfg.DumpPayload { - request.Message = util.CloneMap(req.Message) - } else { - request.Message = map[string]any{ - dumpDisabled: nil, - } - } - } - - r.report.Summary.Request = &model.TestExecutionRequestSummary{ - GRPC: request, - } -} - -func (r *Reporter) AddGRPCResponseStatus(status string) { - r.ensureNotFinalized() - - r.ensureGRPCResponseSummary() - r.report.Summary.Response.GRPC.Status = status -} - -func (r *Reporter) AddGRPCResponseMetadata(metadata map[string][]string) { - r.ensureNotFinalized() - - r.ensureGRPCResponseSummary() - r.report.Summary.Response.GRPC.Metadata = selectMetadata( - metadata, - r.testSpec.Expect.GRPC.Metadata, - ) -} - -func selectMetadata( - actual map[string][]string, - expected map[string][]matcher.String, -) map[string][]string { - if len(expected) == 0 { - return nil - } - - result := make( - map[string][]string, - len(expected), - ) - - for key := range expected { - if values, ok := actual[key]; ok { - result[key] = util.CloneStringSlice(values) - } - } - - if len(result) == 0 { - return nil - } - - return result -} - -func (r *Reporter) AddGRPCResponseMessage(message map[string]any) { - r.ensureNotFinalized() - r.ensureGRPCResponseSummary() - - switch { - case len(message) == 0: - r.report.Summary.Response.GRPC.Message = map[string]any{"": nil} - case !r.cfg.DumpPayload: - r.report.Summary.Response.GRPC.Message = map[string]any{dumpDisabled: nil} - default: - m := util.CloneMap(message) - r.report.Summary.Response.GRPC.Message = m - } -} diff --git a/execute/worker/reporter/reporter_test.go b/execute/worker/reporter/reporter_test.go index 3de64dd..d5b589b 100644 --- a/execute/worker/reporter/reporter_test.go +++ b/execute/worker/reporter/reporter_test.go @@ -2,9 +2,6 @@ package reporter import ( "errors" - "net/http" - "net/url" - "reflect" "testing" "github.com/e2engine/core/model" @@ -327,863 +324,26 @@ func TestReporterAddPayloadDeviation(t *testing.T) { } } -func TestReporterAddHTTPRequest(t *testing.T) { - tests := []struct { - name string - - dumpPayload bool - - expectedBody string - expectedBodyJSON string - }{ - { - name: "payload disabled", - expectedBody: "", - expectedBodyJSON: "", - }, - { - name: "payload enabled", - dumpPayload: true, - expectedBody: "request body", - expectedBodyJSON: `{"name":"test"}`, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - spec := &model.TestSpec{ - Request: model.RequestSpec{ - HTTP: &model.HTTPRequest{ - Body: "request body", - BodyJSON: `{ - "name": "test" - }`, - }, - }, - } - - r := newReporterForTest( - &Config{ - DumpPayload: tt.dumpPayload, - }, - spec, - ) - - u, err := url.Parse( - "http://example.com/resource?a=1", - ) - if err != nil { - t.Fatal(err) - } - - req := &http.Request{ - Method: http.MethodPost, - URL: u, - Header: http.Header{ - "X-Test": {"one", "two"}, - }, - } - - r.AddHTTPRequest(req) - - if r.Result().Summary.Request == nil { - t.Fatal("expected request summary") - } - - actual := r.Result().Summary.Request.HTTP - - if actual == nil { - t.Fatal("expected HTTP request summary") - } - - if actual.Method != http.MethodPost { - t.Errorf( - "expected method %q, got %q", - http.MethodPost, - actual.Method, - ) - } - - if actual.URL != u.String() { - t.Errorf( - "expected URL %q, got %q", - u.String(), - actual.URL, - ) - } - - if !reflect.DeepEqual( - actual.Headers, - map[string][]string(req.Header), - ) { - t.Errorf( - "expected headers %+v, got %+v", - req.Header, - actual.Headers, - ) - } - - if actual.Body != tt.expectedBody { - t.Errorf( - "expected body %q, got %q", - tt.expectedBody, - actual.Body, - ) - } - - if actual.BodyJSON != tt.expectedBodyJSON { - t.Errorf( - "expected JSON body %q, got %q", - tt.expectedBodyJSON, - actual.BodyJSON, - ) - } - - req.Header["X-Test"][0] = "changed" - - if actual.Headers["X-Test"][0] != "one" { - t.Error("stored headers changed with source") - } - }) - } -} - -func TestReporterAddHTTPRequestWithoutBody(t *testing.T) { - spec := &model.TestSpec{ - Request: model.RequestSpec{ - HTTP: &model.HTTPRequest{}, - }, - } - +func TestNewNilConfig(t *testing.T) { r := newReporterForTest( - &Config{}, - spec, - ) - - req, err := http.NewRequest( - http.MethodGet, - "http://example.com/resource", nil, - ) - if err != nil { - t.Fatal(err) - } - - r.AddHTTPRequest(req) - - actual := r.Result().Summary.Request.HTTP - - if actual.Body != "" || actual.BodyJSON != "" { - t.Errorf( - "expected omitted body fields, got body=%q body_json=%q", - actual.Body, - actual.BodyJSON, - ) - } -} - -func TestReporterAddHTTPResponseStatus(t *testing.T) { - r := newReporterForTest( - &Config{}, - &model.TestSpec{}, - ) - - r.AddHTTPResponseStatus(http.StatusCreated) - - response := r.Result().Summary.Response - - if response == nil || response.HTTP == nil { - t.Fatal("expected HTTP response summary") - } - - if response.HTTP.StatusCode != http.StatusCreated { - t.Errorf( - "expected status %d, got %d", - http.StatusCreated, - response.HTTP.StatusCode, - ) - } -} - -func TestReporterAddHTTPResponseHeaders(t *testing.T) { - spec := &model.TestSpec{ - Expect: model.ExpectSpec{ - HTTP: &model.HTTPResponsePattern{ - Headers: map[string][]matcher.String{ - "X-Included": { - { - Operator: matcher.StringMatchOperatorEquals, - Value: "expected", - }, - }, - "X-Missing": { - { - Operator: matcher.StringMatchOperatorExists, - }, - }, - }, - }, - }, - } - - r := newReporterForTest( - &Config{}, - spec, - ) - - headers := http.Header{ - "X-Included": {"actual-1", "actual-2"}, - "X-Unrelated": {"secret"}, - } - - r.AddHTTPResponseHeaders(headers) - - actual := r.Result().Summary.Response.HTTP.Headers - - expected := map[string][]string{ - "X-Included": {"actual-1", "actual-2"}, - } - - if !reflect.DeepEqual(actual, expected) { - t.Errorf( - "expected headers %+v, got %+v", - expected, - actual, - ) - } - - headers["X-Included"][0] = "changed" - - if actual["X-Included"][0] != "actual-1" { - t.Error("stored headers changed with source") - } -} - -func TestSelectHeaders(t *testing.T) { - equals := func(value string) matcher.String { - return matcher.String{ - Operator: matcher.StringMatchOperatorEquals, - Value: value, - } - } - - exists := matcher.String{ - Operator: matcher.StringMatchOperatorExists, - } - - nonempty := matcher.String{ - Operator: matcher.StringMatchOperatorNonEmpty, - } - - tests := []struct { - name string - - actual http.Header - expected map[string][]matcher.String - - want map[string][]string - }{ - { - name: "no expected headers", - actual: http.Header{ - "X-Test": {"value"}, - }, - }, - { - name: "expected header absent", - actual: http.Header{ - "X-Test": {"value"}, - }, - expected: map[string][]matcher.String{ - "X-Missing": {equals("expected")}, - }, - }, - { - name: "selected headers", - actual: http.Header{ - "X-One": {"1"}, - "X-Two": {"2"}, - "X-Other": {"other"}, - }, - expected: map[string][]matcher.String{ - "X-One": {equals("expected")}, - "X-Two": {equals("expected")}, - "X-Missing": {equals("expected")}, - }, - want: map[string][]string{ - "X-One": {"1"}, - "X-Two": {"2"}, - }, - }, - { - name: "exists matcher", - actual: http.Header{ - "X-Test": {""}, - }, - expected: map[string][]matcher.String{ - "X-Test": {exists}, - }, - want: map[string][]string{ - "X-Test": {""}, - }, - }, - { - name: "nonempty matcher", - actual: http.Header{ - "X-Test": {"value"}, - }, - expected: map[string][]matcher.String{ - "X-Test": {nonempty}, - }, - want: map[string][]string{ - "X-Test": {"value"}, - }, - }, - { - name: "case insensitive header lookup", - actual: http.Header{ - "X-Request-Id": {"123"}, - }, - expected: map[string][]matcher.String{ - "x-request-id": {nonempty}, - }, - want: map[string][]string{ - "x-request-id": {"123"}, - }, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - actual := selectHeaders( - tt.actual, - tt.expected, - ) - - if !reflect.DeepEqual(actual, tt.want) { - t.Errorf( - "expected %+v, got %+v", - tt.want, - actual, - ) - } - }) - } -} - -func TestReporterAddHTTPResponseBody(t *testing.T) { - tests := []struct { - name string - dumpPayload bool - body []byte - want string - }{ - { - name: "payload disabled", - body: []byte("body"), - want: "", - }, - { - name: "payload enabled", - dumpPayload: true, - body: []byte("body"), - want: "body", - }, - { - name: "empty body with dumping disabled", - body: []byte{}, - }, - { - name: "empty body with dumping enabled", - dumpPayload: true, - body: []byte{}, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - r := newReporterForTest( - &Config{ - DumpPayload: tt.dumpPayload, - }, - &model.TestSpec{}, - ) - - r.AddHTTPResponseBody(tt.body) - - response := r.Result().Summary.Response - - if response == nil || response.HTTP == nil { - t.Fatal("expected HTTP response summary") - } - - if response.HTTP.Body != tt.want { - t.Errorf( - "expected body %q, got %q", - tt.want, - response.HTTP.Body, - ) - } - }) - } -} - -func TestReporterAddHTTPResponseBodyJSON(t *testing.T) { - tests := []struct { - name string - dumpPayload bool - body []byte - want string - }{ - { - name: "payload disabled", - body: []byte(`{"name":"test"}`), - want: "", - }, - { - name: "payload enabled", - dumpPayload: true, - body: []byte(`{"name":"test"}`), - want: `{"name":"test"}`, - }, - { - name: "empty body with dumping disabled", - body: []byte{}, - }, - { - name: "empty body with dumping enabled", - dumpPayload: true, - body: []byte{}, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - r := newReporterForTest( - &Config{ - DumpPayload: tt.dumpPayload, - }, - &model.TestSpec{}, - ) - - r.AddHTTPResponseBodyJSON(tt.body) - - response := r.Result().Summary.Response - - if response == nil || response.HTTP == nil { - t.Fatal("expected HTTP response summary") - } - - if response.HTTP.BodyJSON != tt.want { - t.Errorf( - "expected JSON body %q, got %q", - tt.want, - response.HTTP.BodyJSON, - ) - } - }) - } -} - -func TestReporterAddGRPCRequest(t *testing.T) { - tests := []struct { - name string - - dumpPayload bool - wantMessage map[string]any - }{ - { - name: "payload disabled", - wantMessage: map[string]any{ - "": nil, - }, - }, - { - name: "payload enabled", - dumpPayload: true, - wantMessage: map[string]any{ - "name": "test", - }, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - r := newReporterForTest( - &Config{ - DumpPayload: tt.dumpPayload, - }, - &model.TestSpec{}, - ) - - req := &model.GRPCRequest{ - Target: "127.0.0.1:8080", - Service: "example.Service", - Method: "Create", - Metadata: map[string][]string{ - "x-test": {"one", "two"}, - }, - Message: map[string]any{ - "name": "test", - }, - } - - r.AddGRPCRequest(req) - - if r.Result().Summary.Request == nil { - t.Fatal("expected request summary") - } - - actual := r.Result().Summary.Request.GRPC - - if actual == nil { - t.Fatal("expected gRPC request summary") - } - - if actual.Target != req.Target { - t.Errorf( - "expected target %q, got %q", - req.Target, - actual.Target, - ) - } - - if actual.Service != req.Service { - t.Errorf( - "expected service %q, got %q", - req.Service, - actual.Service, - ) - } - - if actual.Method != req.Method { - t.Errorf( - "expected method %q, got %q", - req.Method, - actual.Method, - ) - } - - if !reflect.DeepEqual( - actual.Metadata, - req.Metadata, - ) { - t.Errorf( - "expected metadata %+v, got %+v", - req.Metadata, - actual.Metadata, - ) - } - - if !reflect.DeepEqual( - actual.Message, - tt.wantMessage, - ) { - t.Errorf( - "expected message %+v, got %+v", - tt.wantMessage, - actual.Message, - ) - } - - req.Metadata["x-test"][0] = "changed" - req.Message["name"] = "changed" - - if actual.Metadata["x-test"][0] != "one" { - t.Error("stored metadata changed with source") - } - - if tt.dumpPayload && - actual.Message["name"] != "test" { - t.Error("stored message changed with source") - } - }) - } -} - -func TestReporterAddGRPCRequestWithoutMessage(t *testing.T) { - r := newReporterForTest( - &Config{}, - &model.TestSpec{}, - ) - - r.AddGRPCRequest(&model.GRPCRequest{ - Service: "example.Service", - Method: "Create", - }) - - actual := r.Result().Summary.Request.GRPC - - if actual.Message != nil { - t.Errorf( - "expected nil message, got %+v", - actual.Message, - ) - } -} - -func TestReporterAddGRPCResponseStatus(t *testing.T) { - r := newReporterForTest( - &Config{}, &model.TestSpec{}, ) - r.AddGRPCResponseStatus("OK") - - response := r.Result().Summary.Response - - if response == nil || response.GRPC == nil { - t.Fatal("expected gRPC response summary") - } - - if response.GRPC.Status != "OK" { - t.Errorf( - "expected status %q, got %q", - "OK", - response.GRPC.Status, - ) - } -} - -func TestReporterAddGRPCResponseMetadata(t *testing.T) { - spec := &model.TestSpec{ - Expect: model.ExpectSpec{ - GRPC: &model.GRPCResponsePattern{ - Metadata: map[string][]matcher.String{ - "x-included": { - { - Operator: matcher.StringMatchOperatorEquals, - Value: "expected", - }, - }, - "x-missing": { - { - Operator: matcher.StringMatchOperatorExists, - }, - }, - }, - }, - }, - } - - r := newReporterForTest( - &Config{}, - spec, - ) - - metadata := map[string][]string{ - "x-included": {"actual-1", "actual-2"}, - "x-unrelated": {"secret"}, - } - - r.AddGRPCResponseMetadata(metadata) - - actual := r.Result(). - Summary. - Response. - GRPC. - Metadata - - expected := map[string][]string{ - "x-included": {"actual-1", "actual-2"}, - } - - if !reflect.DeepEqual(actual, expected) { - t.Errorf( - "expected metadata %+v, got %+v", - expected, - actual, - ) - } - - metadata["x-included"][0] = "changed" - - if actual["x-included"][0] != "actual-1" { - t.Error("stored metadata changed with source") - } -} - -func TestSelectMetadata(t *testing.T) { - equals := func(value string) matcher.String { - return matcher.String{ - Operator: matcher.StringMatchOperatorEquals, - Value: value, - } - } - - exists := matcher.String{ - Operator: matcher.StringMatchOperatorExists, - } - - nonempty := matcher.String{ - Operator: matcher.StringMatchOperatorNonEmpty, - } - - tests := []struct { - name string - - actual map[string][]string - expected map[string][]matcher.String - - want map[string][]string - }{ - { - name: "no expected metadata", - actual: map[string][]string{ - "x-test": {"value"}, - }, - }, - { - name: "expected metadata absent", - actual: map[string][]string{ - "x-test": {"value"}, - }, - expected: map[string][]matcher.String{ - "x-missing": {equals("expected")}, - }, - }, - { - name: "selected metadata", - actual: map[string][]string{ - "x-one": {"1"}, - "x-two": {"2"}, - "x-other": {"other"}, - }, - expected: map[string][]matcher.String{ - "x-one": {equals("expected")}, - "x-two": {equals("expected")}, - "x-missing": {equals("expected")}, - }, - want: map[string][]string{ - "x-one": {"1"}, - "x-two": {"2"}, - }, - }, - { - name: "exists matcher", - actual: map[string][]string{ - "x-test": {""}, - }, - expected: map[string][]matcher.String{ - "x-test": {exists}, - }, - want: map[string][]string{ - "x-test": {""}, - }, - }, - { - name: "nonempty matcher", - actual: map[string][]string{ - "x-test": {"value"}, - }, - expected: map[string][]matcher.String{ - "x-test": {nonempty}, - }, - want: map[string][]string{ - "x-test": {"value"}, - }, - }, + if r.cfg == nil { + t.Fatal("expected initialized configuration") } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - actual := selectMetadata( - tt.actual, - tt.expected, - ) - - if !reflect.DeepEqual(actual, tt.want) { - t.Errorf( - "expected %+v, got %+v", - tt.want, - actual, - ) - } - }) + if r.cfg.DumpPayload { + t.Error("expected payload dumping disabled by default") } -} - -func TestReporterAddGRPCResponseMessage(t *testing.T) { - tests := []struct { - name string - dumpPayload bool - message map[string]any - want map[string]any - }{ - { - name: "payload disabled", - message: map[string]any{ - "name": "test", - }, - want: map[string]any{ - "": nil, - }, - }, - { - name: "payload enabled", - dumpPayload: true, - message: map[string]any{ - "name": "test", - }, - want: map[string]any{ - "name": "test", - }, - }, - { - name: "empty message with dumping disabled", - message: map[string]any{}, - want: map[string]any{ - "": nil, - }, - }, - { - name: "empty message with dumping enabled", - dumpPayload: true, - message: map[string]any{}, - want: map[string]any{ - "": nil, - }, - }, + if r.cfg.SkipRedactingHeadersMetadata { + t.Error("expected header and metadata redaction enabled") } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - r := newReporterForTest( - &Config{ - DumpPayload: tt.dumpPayload, - }, - &model.TestSpec{}, - ) - - r.AddGRPCResponseMessage(tt.message) - - response := r.Result().Summary.Response - - if response == nil || response.GRPC == nil { - t.Fatal("expected gRPC response summary") - } - - if !reflect.DeepEqual( - response.GRPC.Message, - tt.want, - ) { - t.Errorf( - "expected message %+v, got %+v", - tt.want, - response.GRPC.Message, - ) - } - - if len(tt.message) > 0 { - tt.message["name"] = "changed" - - if tt.dumpPayload && - response.GRPC.Message["name"] != "test" { - t.Error("stored message changed with source") - } - } - }) + if r.cfg.SkipRedactingQueryParams { + t.Error("expected query parameter redaction enabled") } } diff --git a/execute/worker/worker.go b/execute/worker/worker.go index 21816c4..243abf9 100644 --- a/execute/worker/worker.go +++ b/execute/worker/worker.go @@ -3,7 +3,6 @@ package worker import ( "context" "net/http" - "time" "github.com/ygrebnov/errorc" @@ -25,19 +24,35 @@ type Worker struct { client *http.Client grpcMethodResolver grpcservice.MethodResolver -} - -type Config struct { - TestTimeout time.Duration `json:"test_timeout" yaml:"test_timeout" default:"30s" validate:"min(1s)"` - Reporter *reporterPkg.Config `json:"reporter" yaml:"reporter" validateElem:"omitempty"` + addressResolver addressResolver } func NewWorker( cfg *Config, logger log.Logger, grpcMethodResolver grpcservice.MethodResolver, + addressResolver addressResolver, ) *Worker { - client := http.DefaultClient // TODO: make it configurable. + transport := http.DefaultTransport.(*http.Transport).Clone() + + transport.MaxResponseHeaderBytes = cfg.HTTPMaxResponseHeaderBytes + + client := &http.Client{ + Transport: transport, + + CheckRedirect: func( + _ *http.Request, + via []*http.Request, + ) error { + if len(via) > cfg.HTTPMaxRedirects { + return http.ErrUseLastResponse + } + + // TODO: add outbound network restrictions. + + return nil + }, + } return &Worker{ cfg: cfg, @@ -45,6 +60,7 @@ func NewWorker( client: client, grpcMethodResolver: grpcMethodResolver, + addressResolver: addressResolver, } } @@ -58,12 +74,8 @@ func (w *Worker) Execute( ) defer cancel() - reporterCfg := w.cfg.Reporter - if reporterCfg == nil { - reporterCfg = &reporterPkg.Config{} - } reporter := reporterPkg.New( - reporterCfg, + w.cfg.Reporter, &job.Test.Spec, job.ExecutionID, job.TestSuiteExecutionID, @@ -77,7 +89,10 @@ func (w *Worker) Execute( return reporter.Result(), nil } - httpEvaluator := httpworker.NewEvaluator(reporter) + httpEvaluator := httpworker.NewEvaluator( + w.cfg.HTTPEvaluator, + reporter, + ) grpcEvaluator := grpcworker.NewEvaluator( w.grpcMethodResolver, @@ -97,13 +112,16 @@ func (w *Worker) Execute( w.client, httpEvaluator, reporter, + w.addressResolver, ) case job.Test.Spec.Request.GRPC != nil: executor = grpcworker.NewTestExecutor( + w.cfg.GRPCExecutor, w.grpcMethodResolver, grpcEvaluator, reporter, + w.addressResolver, ) default: @@ -122,29 +140,47 @@ func (w *Worker) Execute( return reporter.Result(), nil } - if err := executor.Execute( + executionErr := executor.Execute( runCtx, &job, - ); err != nil { + ) + + if err := callStore.Err(); err != nil { reporter.SummarizeCalls(callStore) reporter.SetError(err) return reporter.Result(), nil } - if err := evaluator.EvaluateCalls( + if executionErr != nil { + reporter.SummarizeCalls(callStore) + reporter.SetError(executionErr) + + return reporter.Result(), nil + } + + evaluationErr := evaluator.EvaluateCalls( runCtx, job.Environment.Spec.Services, job.Test.Spec.Expect.Calls, callStore, job.ExecutionID, - ); err != nil { + ) + + if err := callStore.Err(); err != nil { reporter.SummarizeCalls(callStore) reporter.SetError(err) return reporter.Result(), nil } + if evaluationErr != nil { + reporter.SummarizeCalls(callStore) + reporter.SetError(evaluationErr) + + return reporter.Result(), nil + } + reporter.SummarizeCalls(callStore) reporter.Finalize() diff --git a/execute/worker/worker_test.go b/execute/worker/worker_test.go index 012da56..f3a912c 100644 --- a/execute/worker/worker_test.go +++ b/execute/worker/worker_test.go @@ -5,13 +5,18 @@ import ( nativeerrors "errors" "net/http" "net/http/httptest" + "strings" "testing" "time" + "go.uber.org/mock/gomock" + "github.com/e2engine/core/execute" "github.com/e2engine/core/execute/call" + httpworker "github.com/e2engine/core/execute/worker/http" "github.com/e2engine/core/model" "github.com/e2engine/core/pkg/errors" + "github.com/e2engine/core/pkg/log" ) func TestValidateExpectedCalls(t *testing.T) { @@ -151,6 +156,7 @@ func TestWorkerExecutePassed(t *testing.T) { defer server.Close() worker := newHTTPTestWorker( + t, server.Client(), ) @@ -223,6 +229,7 @@ func TestWorkerExecuteFailed(t *testing.T) { defer server.Close() worker := newHTTPTestWorker( + t, server.Client(), ) @@ -314,6 +321,7 @@ func TestWorkerExecuteExecutorError(t *testing.T) { server.Close() worker := newHTTPTestWorker( + t, client, ) @@ -383,6 +391,7 @@ func TestWorkerExecuteInvalidExpectedCalls(t *testing.T) { defer server.Close() worker := newHTTPTestWorker( + t, server.Client(), ) @@ -465,7 +474,8 @@ func TestWorkerExecuteInvalidTest(t *testing.T) { cfg: &Config{ TestTimeout: time.Second, }, - client: http.DefaultClient, + client: http.DefaultClient, + addressResolver: newTestAddressResolver(t), } job := execute.TestJob{ @@ -533,9 +543,13 @@ func TestWorkerExecuteNilReporterConfig(t *testing.T) { worker := &Worker{ cfg: &Config{ TestTimeout: time.Second, - Reporter: nil, + HTTPEvaluator: &httpworker.EvaluatorConfig{ + MaxResponseBodySize: 1024 * 1024, // 1 MB + }, + Reporter: nil, }, - client: server.Client(), + client: server.Client(), + addressResolver: newTestAddressResolver(t), } job := newHTTPTestJob( @@ -565,16 +579,39 @@ func TestWorkerExecuteNilReporterConfig(t *testing.T) { } func newHTTPTestWorker( + t *testing.T, client *http.Client, ) *Worker { + t.Helper() + return &Worker{ cfg: &Config{ TestTimeout: time.Second, + HTTPEvaluator: &httpworker.EvaluatorConfig{ + MaxResponseBodySize: 1024 * 1024, // 1 MB + }, }, - client: client, + client: client, + addressResolver: newTestAddressResolver(t), } } +func newTestAddressResolver(t *testing.T) *MockaddressResolver { + t.Helper() + + ctrl := gomock.NewController(t) + resolver := NewMockaddressResolver(ctrl) + + resolver.EXPECT(). + ResolveHTTPURL(gomock.Any()). + DoAndReturn(func(value string) (string, error) { + return value, nil + }). + AnyTimes() + + return resolver +} + func newHTTPTestJob( callStore *call.Store, url string, @@ -605,3 +642,281 @@ func newHTTPTestJob( }, } } + +func TestWorkerExecuteCallStoreLimitExceeded(t *testing.T) { + server := httptest.NewServer( + http.HandlerFunc( + func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + }, + ), + ) + defer server.Close() + + store := call.NewStoreFactory( + &call.Config{ + MaxCalls: 1, + MaxRecordedBytes: 1024 * 1024, + }, + ).New() + + // The first call reaches the limit without exceeding it. + if err := store.Record(call.Call{ + TestExecutionID: "execution-1", + ServiceID: "service-1", + }); err != nil { + t.Fatalf( + "first Record() error = %v", + err, + ) + } + + // The second call exceeds the limit. + if err := store.Record(call.Call{ + TestExecutionID: "execution-1", + ServiceID: "service-1", + }); !nativeerrors.Is( + err, + errors.ErrCallStoreLimitExceeded, + ) { + t.Fatalf( + "second Record() error = %v, want ErrCallStoreLimitExceeded", + err, + ) + } + + worker := newHTTPTestWorker( + t, + server.Client(), + ) + + job := newHTTPTestJob( + store, + server.URL, + http.StatusOK, + ) + + result, err := worker.Execute( + context.Background(), + job, + ) + if err != nil { + t.Fatalf( + "Execute() error = %v", + err, + ) + } + + if result == nil { + t.Fatal("expected result") + } + + if result.Status != model.ExecutionStatusError { + t.Errorf( + "status = %q, want %q", + result.Status, + model.ExecutionStatusError, + ) + } + + if !strings.Contains( + result.Summary.Error, + errors.ErrCallStoreLimitExceeded.Error(), + ) { + t.Errorf( + "summary error = %q, want call store limit error", + result.Summary.Error, + ) + } + + if result.FinishedAt.IsZero() { + t.Error("expected FinishedAt") + } +} + +func TestWorkerHTTPRedirectLimit(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc( + func(w http.ResponseWriter, req *http.Request) { + switch req.URL.Path { + case "/start": + http.Redirect( + w, + req, + "/first", + http.StatusFound, + ) + + case "/first": + http.Redirect( + w, + req, + "/second", + http.StatusFound, + ) + + case "/second": + w.WriteHeader(http.StatusOK) + + default: + http.NotFound(w, req) + } + }, + )) + defer server.Close() + + tests := []struct { + name string + maxRedirects int + wantStatus int + }{ + { + name: "redirects disabled", + maxRedirects: 0, + wantStatus: http.StatusFound, + }, + { + name: "one redirect allowed", + maxRedirects: 1, + wantStatus: http.StatusFound, + }, + { + name: "two redirects allowed", + maxRedirects: 2, + wantStatus: http.StatusOK, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + logger, err := log.NewSilentLogger() + if err != nil { + t.Fatal(err) + } + + worker := NewWorker( + &Config{ + TestTimeout: 5 * time.Second, + HTTPMaxRedirects: tt.maxRedirects, + HTTPMaxResponseHeaderBytes: 1 << 20, + HTTPEvaluator: &httpworker.EvaluatorConfig{ + MaxResponseBodySize: 1 << 20, + }, + }, + logger, + nil, + newTestAddressResolver(t), + ) + + job := newHTTPTestJob( + &call.Store{}, + server.URL+"/start", + tt.wantStatus, + ) + + result, err := worker.Execute( + t.Context(), + job, + ) + if err != nil { + t.Fatalf("Execute() error = %v", err) + } + + if result.Status != model.ExecutionStatusPassed { + t.Errorf( + "status = %s, want %s (summary: %+v)", + result.Status, + model.ExecutionStatusPassed, + result.Summary, + ) + } + }) + } +} + +func TestWorkerHTTPMaxResponseHeaderBytes(t *testing.T) { + const maxHeaders int64 = 1024 + + server := httptest.NewServer(http.HandlerFunc( + func(w http.ResponseWriter, req *http.Request) { + if req.URL.Path == "/large" { + w.Header().Set( + "X-Large", + strings.Repeat("a", 4096), + ) + } else { + w.Header().Set("X-Small", "ok") + } + + w.WriteHeader(http.StatusOK) + }, + )) + defer server.Close() + + tests := []struct { + name string + path string + wantStatus model.ExecutionStatus + }{ + { + name: "response headers within limit", + path: "/small", + wantStatus: model.ExecutionStatusPassed, + }, + { + name: "response headers exceed limit", + path: "/large", + wantStatus: model.ExecutionStatusError, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + logger, err := log.NewSilentLogger() + if err != nil { + t.Fatal(err) + } + + worker := NewWorker( + &Config{ + TestTimeout: 5 * time.Second, + HTTPMaxRedirects: 0, + HTTPMaxResponseHeaderBytes: maxHeaders, + HTTPEvaluator: &httpworker.EvaluatorConfig{ + MaxResponseBodySize: 1 << 20, + }, + }, + logger, + nil, + newTestAddressResolver(t), + ) + + job := newHTTPTestJob( + &call.Store{}, + server.URL+tt.path, + http.StatusOK, + ) + + result, err := worker.Execute( + t.Context(), + job, + ) + if err != nil { + t.Fatalf("Execute() error = %v", err) + } + + if result.Status != tt.wantStatus { + t.Errorf( + "status = %s, want %s (summary: %+v)", + result.Status, + tt.wantStatus, + result.Summary, + ) + } + + if tt.wantStatus == model.ExecutionStatusError && + result.Summary.Error == "" { + t.Error("expected error summary") + } + }) + } +} diff --git a/go.sum b/go.sum index a4e77cb..8b8e805 100644 --- a/go.sum +++ b/go.sum @@ -26,6 +26,8 @@ github.com/ygrebnov/model v0.7.5 h1:9i7Xz5vxYQXeJW06gTE9/In49f0lEDhulmsBKhsQxWw= github.com/ygrebnov/model v0.7.5/go.mod h1:qYRz8F/yrt01bPyANAlN0Oqi1fwpgvvl21hjW/NK6N0= go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y= go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU= +golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c= +golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o= golang.org/x/net v0.61.0 h1:RR+6j/BTBCrggOLugxa+66R8FvoN6MHlzDlZIbN9YFw= golang.org/x/net v0.61.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= @@ -34,6 +36,8 @@ golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= +golang.org/x/tools v0.51.0 h1:k4Xc/1Om9jwkBJBo4NVLMSARBoWtK10mx+W5BnXCeAI= +golang.org/x/tools v0.51.0/go.mod h1:9eEncMayCV6zRMGhR5eZEC2iBx98qWcF1HZ9Z7wJOoA= gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= google.golang.org/genproto/googleapis/rpc v0.0.0-20261012220534-4341edf3f941 h1:QG6hS4zFplRZvOQedzei4t2pT/zkQc3VR1u+S9/rcAw= diff --git a/internal/cursor/cursor.go b/internal/cursor/cursor.go index 1525425..d069f0c 100644 --- a/internal/cursor/cursor.go +++ b/internal/cursor/cursor.go @@ -42,7 +42,16 @@ func GetBinding() (*modellib.Binding[Payload], error) { ) } +const MaxCursorLength = 4096 + func Parse(ctx context.Context, binding *modellib.Binding[Payload], opaque string) (Payload, error) { + if len(opaque) > MaxCursorLength { + return Payload{}, errorc.With( + errors.ErrInvalidCursor, + errorc.String(keys.Validation, "cursor exceeds maximum length"), + ) + } + data, err := base64.RawURLEncoding.DecodeString(opaque) if err != nil { return Payload{}, errorc.With( @@ -100,5 +109,14 @@ func Encode(ctx context.Context, binding *modellib.Binding[Payload], payload Pay ) } - return base64.RawURLEncoding.EncodeToString(data), nil + encoded := base64.RawURLEncoding.EncodeToString(data) + + if len(encoded) > MaxCursorLength { + return "", errorc.With( + errors.ErrInvalidCursor, + errorc.String(keys.Validation, "cursor exceeds maximum length"), + ) + } + + return encoded, nil } diff --git a/internal/cursor/cursor_test.go b/internal/cursor/cursor_test.go index 75da7b5..9b404b7 100644 --- a/internal/cursor/cursor_test.go +++ b/internal/cursor/cursor_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/base64" "encoding/json" + "strings" "testing" "github.com/e2engine/core/model" @@ -76,6 +77,15 @@ func TestEncode(t *testing.T) { }, expectedError: errors.ErrInvalidCursor, }, + { + name: "cursor exceeds maximum length", + payload: Payload{ + Value: strings.Repeat("a", MaxCursorLength), + ID: id1, + Position: PositionAfter, + }, + expectedError: errors.ErrInvalidCursor, + }, } for _, test := range tests { @@ -212,6 +222,16 @@ func TestParse(t *testing.T) { }), expectedError: errors.ErrInvalidCursor, }, + { + name: "cursor exceeds maximum length", + opaque: strings.Repeat("a", MaxCursorLength+1), + expectedError: errors.ErrInvalidCursor, + }, + { + name: "cursor at maximum length is decoded", + opaque: strings.Repeat("%", MaxCursorLength), + expectedError: errors.ErrCannotDecodeCursor, + }, } for _, test := range tests { @@ -335,6 +355,53 @@ func TestEncodeParse(t *testing.T) { } } +func TestEncodeParseNearMaxCursorLength(t *testing.T) { + binding, err := GetBinding() + if err != nil { + t.Fatalf("GetBinding() error = %v", err) + } + + payload := Payload{ + Value: strings.Repeat("a", 2900), + ID: id1, + Position: PositionAfter, + } + + encoded, err := Encode( + t.Context(), + binding, + payload, + ) + if err != nil { + t.Fatalf("Encode() error = %v", err) + } + + if len(encoded) > MaxCursorLength { + t.Fatalf( + "encoded cursor length = %d, maximum = %d", + len(encoded), + MaxCursorLength, + ) + } + + decoded, err := Parse( + t.Context(), + binding, + encoded, + ) + if err != nil { + t.Fatalf("Parse() error = %v", err) + } + + if decoded.Value != payload.Value { + t.Errorf( + "decoded value length = %d, want %d", + len(decoded.Value), + len(payload.Value), + ) + } +} + func encodeRawPayload(t *testing.T, payload Payload) string { t.Helper() diff --git a/internal/execute/launcher.go b/internal/execute/launcher.go index a1fb9bb..d821f8f 100644 --- a/internal/execute/launcher.go +++ b/internal/execute/launcher.go @@ -81,7 +81,7 @@ func (l *Launcher) StartTest( exe := &repository.TestExecution{ ID: id, - Status: string(model.ExecutionStatusScheduled), + Status: repository.ExecutionStatusScheduled, EnvironmentID: req.Environment.ID, EnvironmentName: req.Environment.Name, TestID: req.Test.ID, @@ -141,7 +141,7 @@ func (l *Launcher) StartTestSuite( exe := &repository.TestSuiteExecution{ ID: id, - Status: string(model.ExecutionStatusScheduled), + Status: repository.ExecutionStatusScheduled, EnvironmentID: req.Environment.ID, EnvironmentName: req.Environment.Name, TestSuiteID: req.TestSuite.ID, @@ -242,7 +242,7 @@ func (l *Launcher) createTestJobs( testExecution := &repository.TestExecution{ ID: testExecutionID, TestSuiteExecutionID: executionID, - Status: string(model.ExecutionStatusScheduled), + Status: repository.ExecutionStatusScheduled, EnvironmentID: environment.ID, EnvironmentName: environment.Name, TestID: test.ID, @@ -314,10 +314,13 @@ func (l *Launcher) completeTestExecutionAfterError( testSuiteExecutionID string, err error, ) error { + stateUpdateCtx, cancel := newStateUpdateContext(ctx) + defer cancel() + return nativeerrors.Join( err, l.completeTestExecutionWithError( - ctx, + stateUpdateCtx, executionID, testSuiteExecutionID, err, @@ -331,13 +334,16 @@ func (l *Launcher) completeTestExecutionsWithError( executionIDs []string, err error, ) error { + stateUpdateCtx, cancel := newStateUpdateContext(ctx) + defer cancel() + var completeErr error for _, executionID := range executionIDs { completeErr = nativeerrors.Join( completeErr, l.completeTestExecutionWithError( - ctx, + stateUpdateCtx, executionID, testSuiteExecutionID, err, @@ -360,6 +366,16 @@ func (r publishTestJobResult) Err() error { ) } +func newStateUpdateContext(ctx context.Context) ( + context.Context, + context.CancelFunc, +) { + return context.WithTimeout( + context.WithoutCancel(ctx), + 10*time.Second, + ) +} + func (l *Launcher) publishTestJob( ctx context.Context, job execute.TestJob, @@ -382,10 +398,14 @@ func (l *Launcher) publishTestJob( err, ) + // Finalize the persisted execution even if the caller was canceled. + stateUpdateCtx, stateUpdateCtxCancel := newStateUpdateContext(ctx) + defer stateUpdateCtxCancel() + return publishTestJobResult{ scheduleErr: scheduleErr, stateUpdateErr: l.completeTestExecutionWithError( - ctx, + stateUpdateCtx, job.ExecutionID, job.TestSuiteExecutionID, scheduleErr, @@ -422,7 +442,7 @@ func (l *Launcher) completeTestExecutionWithError( ctx context.Context, executionID string, testSuiteExecutionID string, - err error, + _ error, ) error { _, setErr := l.stateUpdater.SetTestCompleted( ctx, @@ -432,7 +452,8 @@ func (l *Launcher) completeTestExecutionWithError( Status: model.ExecutionStatusError, FinishedAt: time.Now().UTC(), Summary: &model.TestExecutionSummary{ - Error: err.Error(), + // TODO: add structured error codes + Error: "failed to prepare or schedule test execution", }, }, ) @@ -443,16 +464,20 @@ func (l *Launcher) completeTestExecutionWithError( func (l *Launcher) completeTestSuiteExecutionWithError( ctx context.Context, executionID string, - err error, + _ error, ) error { + stateUpdateCtx, cancel := newStateUpdateContext(ctx) + defer cancel() + _, setErr := l.stateUpdater.SetTestSuiteCompleted( - ctx, + stateUpdateCtx, execute.TestSuiteExecutionResult{ ExecutionID: executionID, Status: model.ExecutionStatusError, FinishedAt: time.Now().UTC(), Summary: &model.TestSuiteExecutionSummary{ - Error: err.Error(), + // TODO: add structured error codes + Error: "failed to prepare or schedule test suite execution", }, }, ) diff --git a/internal/execute/launcher_test.go b/internal/execute/launcher_test.go index 7fc2cfe..89dca40 100644 --- a/internal/execute/launcher_test.go +++ b/internal/execute/launcher_test.go @@ -140,7 +140,7 @@ func TestLauncherStartTest(t *testing.T) { _ context.Context, execution *repository.TestExecution, ) (*repository.TestExecution, error) { - if execution.Status != string(model.ExecutionStatusScheduled) { + if execution.Status != repository.ExecutionStatusScheduled { t.Errorf( "status = %q, want %q", execution.Status, @@ -535,3 +535,466 @@ func TestLauncherStartTestSuite(t *testing.T) { } } } + +func TestLauncherStartTestCanceledDuringPublishFinalizesExecution(t *testing.T) { + ctrl := gomock.NewController(t) + + testExecution := mock.NewMockTestExecutionRepository(ctrl) + + testExecution.EXPECT(). + Create(gomock.Any(), gomock.Any()). + DoAndReturn(func( + _ context.Context, + execution *repository.TestExecution, + ) (*repository.TestExecution, error) { + return execution, nil + }) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + var completed coreexecute.TestExecutionResult + cleanupCalled := false + + updater := &stateUpdaterFunc{ + setTestCompleted: func( + updateCtx context.Context, + result coreexecute.TestExecutionResult, + ) (bool, error) { + cleanupCalled = true + completed = result + + if err := updateCtx.Err(); err != nil { + t.Errorf( + "cleanup context canceled: %v", + err, + ) + } + + if _, ok := updateCtx.Deadline(); !ok { + t.Error("cleanup context has no deadline") + } + + return true, nil + }, + } + + launcher := newTestLauncher( + t, + schedulerFunc(func( + publishCtx context.Context, + _ coreexecute.TestJob, + ) error { + // Simulate caller cancellation during publishing. + cancel() + + <-publishCtx.Done() + return publishCtx.Err() + }), + updater, + testExecution, + nil, + ) + + executionID, err := launcher.StartTest( + ctx, + testRunRequest(), + ) + + if executionID == "" { + t.Fatal("StartTest() returned empty execution ID") + } + + if !errors.Is(err, context.Canceled) { + t.Fatalf( + "StartTest() error = %v, want context.Canceled", + err, + ) + } + + if !cleanupCalled { + t.Fatal("SetTestCompleted() was not called") + } + + if completed.ExecutionID != executionID { + t.Errorf( + "completed execution ID = %q, want %q", + completed.ExecutionID, + executionID, + ) + } + + if completed.Status != model.ExecutionStatusError { + t.Errorf( + "completed status = %q, want %q", + completed.Status, + model.ExecutionStatusError, + ) + } +} + +func TestLauncherStartTestSuiteCanceledDuringJobCreationFinalizesRecords(t *testing.T) { + ctrl := gomock.NewController(t) + + testExecution := mock.NewMockTestExecutionRepository(ctrl) + testSuiteExecution := mock.NewMockTestSuiteExecutionRepository(ctrl) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + testSuiteExecution.EXPECT(). + Create(gomock.Any(), gomock.Any()). + DoAndReturn(func( + _ context.Context, + execution *repository.TestSuiteExecution, + ) (*repository.TestSuiteExecution, error) { + return execution, nil + }) + + // First test execution is successfully persisted. + testExecution.EXPECT(). + Create(gomock.Any(), gomock.Any()). + DoAndReturn(func( + _ context.Context, + execution *repository.TestExecution, + ) (*repository.TestExecution, error) { + return execution, nil + }) + + // Second test execution fails because the caller is canceled. + testExecution.EXPECT(). + Create(gomock.Any(), gomock.Any()). + DoAndReturn(func( + _ context.Context, + _ *repository.TestExecution, + ) (*repository.TestExecution, error) { + cancel() + return nil, context.Canceled + }) + + completedTests := 0 + completedSuites := 0 + + updater := &stateUpdaterFunc{ + setTestCompleted: func( + updateCtx context.Context, + result coreexecute.TestExecutionResult, + ) (bool, error) { + completedTests++ + + if err := updateCtx.Err(); err != nil { + t.Errorf( + "test cleanup context canceled: %v", + err, + ) + } + + if _, ok := updateCtx.Deadline(); !ok { + t.Error("test cleanup context has no deadline") + } + + if result.Status != model.ExecutionStatusError { + t.Errorf( + "test status = %q, want %q", + result.Status, + model.ExecutionStatusError, + ) + } + + return true, nil + }, + + setTestSuiteCompleted: func( + updateCtx context.Context, + result coreexecute.TestSuiteExecutionResult, + ) (bool, error) { + completedSuites++ + + if err := updateCtx.Err(); err != nil { + t.Errorf( + "suite cleanup context canceled: %v", + err, + ) + } + + if _, ok := updateCtx.Deadline(); !ok { + t.Error("suite cleanup context has no deadline") + } + + if result.Status != model.ExecutionStatusError { + t.Errorf( + "suite status = %q, want %q", + result.Status, + model.ExecutionStatusError, + ) + } + + return true, nil + }, + } + + launcher := newTestLauncher( + t, + schedulerFunc(func( + context.Context, + coreexecute.TestJob, + ) error { + t.Error("scheduler must not be called") + return nil + }), + updater, + testExecution, + testSuiteExecution, + ) + + executionID, err := launcher.StartTestSuite( + ctx, + testSuiteRunRequest(3), + ) + + if executionID == "" { + t.Fatal("StartTestSuite() returned empty execution ID") + } + + if !errors.Is(err, context.Canceled) { + t.Fatalf( + "StartTestSuite() error = %v, want context.Canceled", + err, + ) + } + + if completedTests != 1 { + t.Errorf( + "completed tests = %d, want 1", + completedTests, + ) + } + + if completedSuites != 1 { + t.Errorf( + "completed suites = %d, want 1", + completedSuites, + ) + } +} + +func TestLauncherStartTestSuitePublishAndStateUpdateFailureFinalizesRemaining(t *testing.T) { + ctrl := gomock.NewController(t) + + testExecution := mock.NewMockTestExecutionRepository(ctrl) + testSuiteExecution := mock.NewMockTestSuiteExecutionRepository(ctrl) + + testSuiteExecution.EXPECT(). + Create(gomock.Any(), gomock.Any()). + DoAndReturn(func( + _ context.Context, + execution *repository.TestSuiteExecution, + ) (*repository.TestSuiteExecution, error) { + return execution, nil + }) + + testExecution.EXPECT(). + Create(gomock.Any(), gomock.Any()). + DoAndReturn(func( + _ context.Context, + execution *repository.TestExecution, + ) (*repository.TestExecution, error) { + return execution, nil + }). + Times(3) + + publishErr := errors.New("publishing failed") + updateErr := errors.New("state update failed") + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + var published []string + var completed []coreexecute.TestExecutionResult + var completedSuite coreexecute.TestSuiteExecutionResult + + updater := &stateUpdaterFunc{ + setTestCompleted: func( + updateCtx context.Context, + result coreexecute.TestExecutionResult, + ) (bool, error) { + if err := updateCtx.Err(); err != nil { + t.Errorf( + "test completion context canceled: %v", + err, + ) + } + + if _, ok := updateCtx.Deadline(); !ok { + t.Error("test completion context has no deadline") + } + + completed = append(completed, result) + + // Simulate failure to persist the first + // test execution's final status. + if len(completed) == 1 { + return false, updateErr + } + + return true, nil + }, + + setTestSuiteCompleted: func( + updateCtx context.Context, + result coreexecute.TestSuiteExecutionResult, + ) (bool, error) { + if err := updateCtx.Err(); err != nil { + t.Errorf( + "suite completion context canceled: %v", + err, + ) + } + + if _, ok := updateCtx.Deadline(); !ok { + t.Error("suite completion context has no deadline") + } + + completedSuite = result + + return true, nil + }, + } + + launcher := newTestLauncher( + t, + schedulerFunc(func( + _ context.Context, + job coreexecute.TestJob, + ) error { + published = append( + published, + job.ExecutionID, + ) + + // Cancel the caller while publishing. + cancel() + + return publishErr + }), + updater, + testExecution, + testSuiteExecution, + ) + + suiteID, err := launcher.StartTestSuite( + ctx, + testSuiteRunRequest(3), + ) + + if suiteID == "" { + t.Fatal("StartTestSuite() returned empty suite execution ID") + } + + // Both the publishing failure and the state-update + // failure must be preserved in the returned error. + if !errors.Is(err, coreerrors.ErrFailedToScheduleJob) { + t.Errorf( + "error = %v, want ErrFailedToScheduleJob", + err, + ) + } + + if !errors.Is(err, publishErr) { + t.Errorf( + "error = %v, want publishing error", + err, + ) + } + + if !errors.Is(err, updateErr) { + t.Errorf( + "error = %v, want state update error", + err, + ) + } + + // Publishing must stop after the first job because + // its execution state could not be updated. + if len(published) != 1 { + t.Fatalf( + "published jobs = %d, want 1", + len(published), + ) + } + + // The launcher must attempt finalization of all + // three executions, including the failed job. + if len(completed) != 3 { + t.Fatalf( + "test completion attempts = %d, want 3", + len(completed), + ) + } + + if completed[0].ExecutionID != published[0] { + t.Errorf( + "first completed execution ID = %q, want %q", + completed[0].ExecutionID, + published[0], + ) + } + + seen := make(map[string]bool) + + for _, result := range completed { + if seen[result.ExecutionID] { + t.Errorf( + "execution %q finalized twice", + result.ExecutionID, + ) + } + + seen[result.ExecutionID] = true + + if result.TestSuiteExecutionID != suiteID { + t.Errorf( + "test suite execution ID = %q, want %q", + result.TestSuiteExecutionID, + suiteID, + ) + } + + if result.Status != model.ExecutionStatusError { + t.Errorf( + "execution %q status = %q, want %q", + result.ExecutionID, + result.Status, + model.ExecutionStatusError, + ) + } + + if result.Summary == nil { + t.Errorf( + "execution %q summary is nil", + result.ExecutionID, + ) + } + } + + // Verify that the parent test suite is finalized. + if completedSuite.ExecutionID != suiteID { + t.Errorf( + "completed suite ID = %q, want %q", + completedSuite.ExecutionID, + suiteID, + ) + } + + if completedSuite.Status != model.ExecutionStatusError { + t.Errorf( + "suite status = %q, want %q", + completedSuite.Status, + model.ExecutionStatusError, + ) + } + + if completedSuite.Summary == nil { + t.Error("completed suite summary is nil") + } +} diff --git a/internal/resource/paging.go b/internal/resource/paging.go index 2768553..71fd432 100644 --- a/internal/resource/paging.go +++ b/internal/resource/paging.go @@ -129,8 +129,7 @@ func decodePagingAnchor( return nil, errorc.With( errors.ErrInvalidCursor, errorc.String(keys.RequestKind, requestKind), - errorc.String(keys.CursorTimestampValue, payload.Value), - errorc.Error(keys.Validation, err), + errorc.String(keys.Validation, "invalid cursor timestamp"), ) } diff --git a/internal/resource/resource.go b/internal/resource/resource.go index 784664b..ed04df7 100644 --- a/internal/resource/resource.go +++ b/internal/resource/resource.go @@ -2,7 +2,6 @@ package resource import ( "context" - "strings" "github.com/ygrebnov/errorc" @@ -52,7 +51,6 @@ func resolveResourceID( errors.ErrEntityPrefixAmbiguous, errorc.String(keys.EntityID, ref), errorc.String(keys.EntityKind, string(kind)), - errorc.String(keys.EntityIDs, strings.Join(ids, ",")), ) } @@ -61,7 +59,6 @@ func resolveResourceID( errors.ErrEntityPrefixAmbiguous, errorc.String(keys.EntityName, ref), errorc.String(keys.EntityKind, string(kind)), - errorc.String(keys.EntityIDs, strings.Join(nameIDs, ",")), ) } @@ -106,7 +103,6 @@ func resolveEntityID( errors.ErrEntityPrefixAmbiguous, errorc.String(keys.EntityID, ref), errorc.String(keys.EntityKind, string(kind)), - errorc.String(keys.EntityIDs, strings.Join(ids, ",")), ) } } diff --git a/internal/resource/test.go b/internal/resource/test.go index 8fa3d39..716421b 100644 --- a/internal/resource/test.go +++ b/internal/resource/test.go @@ -144,8 +144,8 @@ func (s *Controller) getTestID( ) } -func (s *Controller) GetTestsByTag(ctx context.Context, tag string) ([]model.Test, error) { - tests, err := s.test.GetByTag(ctx, tag) +func (s *Controller) GetTestsByTag(ctx context.Context, tag string, limit int) ([]model.Test, error) { + tests, err := s.test.GetByTag(ctx, tag, limit) if err != nil { return nil, err } diff --git a/internal/resource/test_test.go b/internal/resource/test_test.go index 60636b8..3478af1 100644 --- a/internal/resource/test_test.go +++ b/internal/resource/test_test.go @@ -840,7 +840,8 @@ func TestControllerGetTestsByTag(t *testing.T) { errGetByTag := errors.New("get by tag error") tests := []struct { - name string + name string + limit int repositoryTests []repository.Test repositoryError error @@ -849,7 +850,8 @@ func TestControllerGetTestsByTag(t *testing.T) { expectedError error }{ { - name: "success", + name: "success", + limit: 10, repositoryTests: []repository.Test{ { ID: "test-001", @@ -873,16 +875,19 @@ func TestControllerGetTestsByTag(t *testing.T) { }, { name: "empty", + limit: 10, repositoryTests: []repository.Test{}, expectedIDs: []string{}, }, { name: "repository error", + limit: 10, repositoryError: errGetByTag, expectedError: errGetByTag, }, { - name: "conversion error", + name: "conversion error", + limit: 10, repositoryTests: []repository.Test{ { ID: "test-001", @@ -891,6 +896,18 @@ func TestControllerGetTestsByTag(t *testing.T) { }, expectedError: coreerrors.ErrCannotParseSpec, }, + { + name: "custom limit", + limit: 1, + repositoryTests: []repository.Test{ + { + ID: "test-001", + Version: InitialVersion, + Spec: specJSON, + }, + }, + expectedIDs: []string{"test-001"}, + }, } for _, tt := range tests { @@ -902,6 +919,7 @@ func TestControllerGetTestsByTag(t *testing.T) { GetByTag( gomock.Any(), "smoke", + tt.limit, ). Return( tt.repositoryTests, @@ -915,6 +933,7 @@ func TestControllerGetTestsByTag(t *testing.T) { actual, err := controller.GetTestsByTag( t.Context(), "smoke", + tt.limit, ) if tt.expectedError != nil { diff --git a/internal/resource/testexecution_test.go b/internal/resource/testexecution_test.go index 6d5f789..b37b569 100644 --- a/internal/resource/testexecution_test.go +++ b/internal/resource/testexecution_test.go @@ -532,7 +532,7 @@ func TestControllerGetTestExecutionStatus(t *testing.T) { repo.EXPECT(). GetStatus(gomock.Any(), id). - Return(string(model.ExecutionStatusPassed), nil) + Return(repository.ExecutionStatusPassed, nil) }, expectedStatus: model.ExecutionStatusPassed, }, @@ -575,7 +575,7 @@ func TestControllerGetTestExecutionStatus(t *testing.T) { repo.EXPECT(). GetStatus(gomock.Any(), id). - Return("", repository.ErrNotFound) + Return(repository.ExecutionStatus(""), repository.ErrNotFound) }, expectedError: coreerrors.ErrEntityNotFound, }, @@ -590,7 +590,7 @@ func TestControllerGetTestExecutionStatus(t *testing.T) { repo.EXPECT(). GetStatus(gomock.Any(), id). - Return("", errGetTestExecutionStatus) + Return(repository.ExecutionStatus(""), errGetTestExecutionStatus) }, expectedError: errGetTestExecutionStatus, }, diff --git a/internal/resource/testsuiteexecution.go b/internal/resource/testsuiteexecution.go index d9a7156..5d2966d 100644 --- a/internal/resource/testsuiteexecution.go +++ b/internal/resource/testsuiteexecution.go @@ -93,6 +93,7 @@ func (s *Controller) GetTestSuiteExecution(ctx context.Context, prefix string) ( return nil, err } + // TODO: Paginate child test executions instead of loading the entire suite at once. dbTests, err := s.testExecution.GetByTestSuiteExecutionID( ctx, testSuiteExecution.ID, diff --git a/internal/resource/testsuiteexecution_test.go b/internal/resource/testsuiteexecution_test.go index 3a3d425..8a9e7b4 100644 --- a/internal/resource/testsuiteexecution_test.go +++ b/internal/resource/testsuiteexecution_test.go @@ -645,7 +645,7 @@ func TestControllerGetTestSuiteExecutionStatus(t *testing.T) { repo.EXPECT(). GetStatus(gomock.Any(), id). - Return(string(model.ExecutionStatusPassed), nil) + Return(repository.ExecutionStatusPassed, nil) }, expectedStatus: model.ExecutionStatusPassed, }, @@ -688,7 +688,7 @@ func TestControllerGetTestSuiteExecutionStatus(t *testing.T) { repo.EXPECT(). GetStatus(gomock.Any(), id). - Return("", repository.ErrNotFound) + Return(repository.ExecutionStatus(""), repository.ErrNotFound) }, expectedError: coreerrors.ErrEntityNotFound, }, @@ -703,7 +703,7 @@ func TestControllerGetTestSuiteExecutionStatus(t *testing.T) { repo.EXPECT(). GetStatus(gomock.Any(), id). - Return("", errGetStatus) + Return(repository.ExecutionStatus(""), errGetStatus) }, expectedError: errGetStatus, }, diff --git a/internal/util/clone.go b/internal/util/clone.go index 91f90ab..d9f14b3 100644 --- a/internal/util/clone.go +++ b/internal/util/clone.go @@ -2,10 +2,8 @@ package util import ( "encoding/json" - "net/http" - "net/url" - - "github.com/e2engine/core/model/matcher" + "maps" + "slices" ) func CloneStruct[T any](src T) (T, error) { @@ -23,104 +21,12 @@ func CloneStruct[T any](src T) (T, error) { return dst, nil } -func CloneHTTPHeader(header http.Header) http.Header { - if header == nil { - return nil - } - - result := make(http.Header, len(header)) - - for key, values := range header { - result[key] = append([]string(nil), values...) - } - - return result -} - -func CloneQuery(values url.Values) map[string][]string { - if values == nil { - return nil - } - - result := make(map[string][]string, len(values)) - - for key, value := range values { - result[key] = append([]string(nil), value...) - } - - return result -} - -func CloneBytes(value []byte) []byte { - if value == nil { - return nil - } - - return append([]byte(nil), value...) -} - -func CloneStringMap(value map[string]string) map[string]string { - if value == nil { - return nil - } - - result := make(map[string]string, len(value)) - - for key, item := range value { - result[key] = item - } - - return result -} - func CloneStringSliceMap(value map[string][]string) map[string][]string { - if value == nil { - return nil - } - - result := make(map[string][]string, len(value)) - - for key, item := range value { - cloned := make([]string, len(item)) - copy(cloned, item) - result[key] = cloned - } - - return result -} - -func CloneMap(value map[string]any) map[string]any { - if value == nil { - return nil - } - - result := make(map[string]any, len(value)) + result := maps.Clone(value) - for key, item := range value { - result[key] = item + for key, items := range result { + result[key] = slices.Clone(items) } return result } - -func CloneStringSlice(value []string) []string { - if value == nil { - return nil - } - - result := make([]string, len(value)) - copy(result, value) - - return result -} - -func CloneStringMatcherSlice(value []matcher.String) []matcher.String { - if value == nil { - return nil - } - - result := make([]matcher.String, len(value)) - copy(result, value) - - return result -} diff --git a/internal/util/clone_test.go b/internal/util/clone_test.go index a551cab..78bed0d 100644 --- a/internal/util/clone_test.go +++ b/internal/util/clone_test.go @@ -1,8 +1,6 @@ package util import ( - "net/http" - "net/url" "reflect" "testing" ) @@ -71,173 +69,6 @@ func TestCloneStructMarshalError(t *testing.T) { } } -func TestCloneHTTPHeader(t *testing.T) { - tests := []struct { - name string - input http.Header - }{ - { - name: "nil", - }, - { - name: "empty", - input: http.Header{}, - }, - { - name: "values", - input: http.Header{ - "Content-Type": {"application/json"}, - "Accept": {"application/json", "text/plain"}, - }, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - cloned := CloneHTTPHeader(tt.input) - - if !reflect.DeepEqual(cloned, tt.input) { - t.Fatalf( - "expected %v, got %v", - tt.input, - cloned, - ) - } - - if tt.input == nil { - if cloned != nil { - t.Fatal("expected nil") - } - return - } - - cloned.Set("X-Test", "value") - - if tt.input.Get("X-Test") != "" { - t.Fatal("map was not cloned") - } - - if len(tt.input["Accept"]) > 0 { - cloned["Accept"][0] = "changed" - - if tt.input["Accept"][0] == "changed" { - t.Fatal("header values were not cloned") - } - } - }) - } -} - -func TestCloneQuery(t *testing.T) { - tests := []struct { - name string - input url.Values - }{ - { - name: "nil", - }, - { - name: "empty", - input: url.Values{}, - }, - { - name: "values", - input: url.Values{ - "key": {"one", "two"}, - }, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - cloned := CloneQuery(tt.input) - - if !reflect.DeepEqual(cloned, map[string][]string(tt.input)) { - t.Fatalf( - "expected %v, got %v", - tt.input, - cloned, - ) - } - - if tt.input == nil { - if cloned != nil { - t.Fatal("expected nil") - } - return - } - - cloned["new"] = []string{"value"} - - if _, ok := tt.input["new"]; ok { - t.Fatal("map was not cloned") - } - - if len(tt.input["key"]) > 0 { - cloned["key"][0] = "changed" - - if tt.input["key"][0] == "changed" { - t.Fatal("query values were not cloned") - } - } - }) - } -} - -func TestCloneBytes(t *testing.T) { - if CloneBytes(nil) != nil { - t.Fatal("expected nil") - } - - original := []byte{1, 2, 3} - cloned := CloneBytes(original) - - if !reflect.DeepEqual(cloned, original) { - t.Fatalf( - "expected %v, got %v", - original, - cloned, - ) - } - - cloned[0] = 9 - - if original[0] == 9 { - t.Fatal("bytes were not cloned") - } -} - -func TestCloneStringMap(t *testing.T) { - if CloneStringMap(nil) != nil { - t.Fatal("expected nil") - } - - original := map[string]string{ - "one": "1", - "two": "2", - } - cloned := CloneStringMap(original) - - if !reflect.DeepEqual(cloned, original) { - t.Fatalf( - "expected %v, got %v", - original, - cloned, - ) - } - - cloned["one"] = "changed" - cloned["three"] = "3" - - if original["one"] != "1" { - t.Fatal("map value was not cloned") - } - - if _, ok := original["three"]; ok { - t.Fatal("map was not cloned") - } -} - func TestCloneStringSliceMap(t *testing.T) { if CloneStringSliceMap(nil) != nil { t.Fatal("expected nil") @@ -269,62 +100,3 @@ func TestCloneStringSliceMap(t *testing.T) { t.Fatal("map slice value was not cloned") } } - -func TestCloneMap(t *testing.T) { - if CloneMap(nil) != nil { - t.Fatal("expected nil") - } - - nested := []string{"one"} - - original := map[string]any{ - "name": "test", - "nested": nested, - } - cloned := CloneMap(original) - - if !reflect.DeepEqual(cloned, original) { - t.Fatalf( - "expected %v, got %v", - original, - cloned, - ) - } - - cloned["name"] = "changed" - - if original["name"] != "test" { - t.Fatal("map was not cloned") - } - - // CloneMap intentionally performs a shallow clone. - clonedNested := cloned["nested"].([]string) - clonedNested[0] = "changed" - - if nested[0] != "changed" { - t.Fatal("expected nested value to remain shared") - } -} - -func TestCloneStringSlice(t *testing.T) { - if CloneStringSlice(nil) != nil { - t.Fatal("expected nil") - } - - original := []string{"one", "two"} - cloned := CloneStringSlice(original) - - if !reflect.DeepEqual(cloned, original) { - t.Fatalf( - "expected %v, got %v", - original, - cloned, - ) - } - - cloned[0] = "changed" - - if original[0] == "changed" { - t.Fatal("slice was not cloned") - } -} diff --git a/mock/Repository.go b/mock/Repository.go index d78d478..5f0ff26 100644 --- a/mock/Repository.go +++ b/mock/Repository.go @@ -300,18 +300,18 @@ func (mr *MockTestRepositoryMockRecorder) Get(ctx, id any) *gomock.Call { } // GetByTag mocks base method. -func (m *MockTestRepository) GetByTag(ctx context.Context, tag string) ([]repository.Test, error) { +func (m *MockTestRepository) GetByTag(ctx context.Context, tag string, limit int) ([]repository.Test, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetByTag", ctx, tag) + ret := m.ctrl.Call(m, "GetByTag", ctx, tag, limit) ret0, _ := ret[0].([]repository.Test) ret1, _ := ret[1].(error) return ret0, ret1 } // GetByTag indicates an expected call of GetByTag. -func (mr *MockTestRepositoryMockRecorder) GetByTag(ctx, tag any) *gomock.Call { +func (mr *MockTestRepositoryMockRecorder) GetByTag(ctx, tag, limit any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByTag", reflect.TypeOf((*MockTestRepository)(nil).GetByTag), ctx, tag) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByTag", reflect.TypeOf((*MockTestRepository)(nil).GetByTag), ctx, tag, limit) } // GetIDsByID mocks base method. @@ -459,10 +459,10 @@ func (mr *MockTestExecutionRepositoryMockRecorder) GetIDsByID(ctx, id any) *gomo } // GetStatus mocks base method. -func (m *MockTestExecutionRepository) GetStatus(ctx context.Context, id string) (string, error) { +func (m *MockTestExecutionRepository) GetStatus(ctx context.Context, id string) (repository.ExecutionStatus, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetStatus", ctx, id) - ret0, _ := ret[0].(string) + ret0, _ := ret[0].(repository.ExecutionStatus) ret1, _ := ret[1].(error) return ret0, ret1 } @@ -473,6 +473,22 @@ func (mr *MockTestExecutionRepositoryMockRecorder) GetStatus(ctx, id any) *gomoc return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStatus", reflect.TypeOf((*MockTestExecutionRepository)(nil).GetStatus), ctx, id) } +// GetTestSuiteExecutionStates mocks base method. +func (m *MockTestExecutionRepository) GetTestSuiteExecutionStates(ctx context.Context, testSuiteExecutionID string) ([]repository.TestSuiteExecutionState, bool, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetTestSuiteExecutionStates", ctx, testSuiteExecutionID) + ret0, _ := ret[0].([]repository.TestSuiteExecutionState) + ret1, _ := ret[1].(bool) + ret2, _ := ret[2].(error) + return ret0, ret1, ret2 +} + +// GetTestSuiteExecutionStates indicates an expected call of GetTestSuiteExecutionStates. +func (mr *MockTestExecutionRepositoryMockRecorder) GetTestSuiteExecutionStates(ctx, testSuiteExecutionID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTestSuiteExecutionStates", reflect.TypeOf((*MockTestExecutionRepository)(nil).GetTestSuiteExecutionStates), ctx, testSuiteExecutionID) +} + // List mocks base method. func (m *MockTestExecutionRepository) List(ctx context.Context, params *repository.ListParams) ([]repository.TestExecution, error) { m.ctrl.T.Helper() @@ -601,10 +617,10 @@ func (mr *MockTestSuiteExecutionRepositoryMockRecorder) GetIDsByID(ctx, id any) } // GetStatus mocks base method. -func (m *MockTestSuiteExecutionRepository) GetStatus(ctx context.Context, id string) (string, error) { +func (m *MockTestSuiteExecutionRepository) GetStatus(ctx context.Context, id string) (repository.ExecutionStatus, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetStatus", ctx, id) - ret0, _ := ret[0].(string) + ret0, _ := ret[0].(repository.ExecutionStatus) ret1, _ := ret[1].(error) return ret0, ret1 } diff --git a/model/environment.go b/model/environment.go index 18c2a11..99d4437 100644 --- a/model/environment.go +++ b/model/environment.go @@ -2,7 +2,7 @@ package model import ( "context" - nativeerrors "errors" + "strconv" "github.com/ygrebnov/errorc" modellib "github.com/ygrebnov/model" @@ -20,30 +20,26 @@ func (e *Environment) Validate(ctx context.Context) error { return errorc.With( errors.ErrInvalidSpec, errorc.String(keys.SpecKind, string(EntityKindEnvironment)), - errorc.String(keys.Validation, "invalid resource kind"), + errorc.String(keys.Fields, "Kind"), + errorc.String(keys.Validation, "invalid kind"), ) } if err := environmentBinding.Validate(ctx, e); err != nil { - return nativeerrors.Join( - errorc.With( - errors.ErrInvalidSpec, - errorc.String(keys.SpecKind, string(EntityKindEnvironment)), - ), - err, - ) + return handleValidationError(err, EntityKindEnvironment) } if len(e.Spec.Services) == 0 { return errorc.With( errors.ErrInvalidSpec, errorc.String(keys.SpecKind, string(EntityKindEnvironment)), + errorc.String(keys.Fields, "Spec.Services"), errorc.String(keys.Validation, "environment spec must contain at least one service"), ) } serviceIDs := make(map[string]struct{}, len(e.Spec.Services)) - addresses := make(map[string]struct{}, len(e.Spec.Services)) + ports := make(map[int]struct{}, len(e.Spec.Services)) for i := range e.Spec.Services { service := &e.Spec.Services[i] @@ -52,24 +48,27 @@ func (e *Environment) Validate(ctx context.Context) error { return errorc.With( errors.ErrInvalidSpec, errorc.String(keys.SpecKind, string(EntityKindEnvironment)), - errorc.String(keys.EnvironmentServiceID, service.ID), + errorc.String(keys.Fields, "Spec.Services["+strconv.Itoa(i)+"].ID"), errorc.String(keys.Validation, "service ids must be unique"), ) } serviceIDs[service.ID] = struct{}{} - if _, ok := addresses[service.Address]; ok { + if _, ok := ports[service.E2EnginePort]; ok { return errorc.With( errors.ErrInvalidSpec, errorc.String(keys.SpecKind, string(EntityKindEnvironment)), - errorc.String(keys.EnvironmentServiceID, service.ID), - errorc.String(keys.EnvironmentServiceListenAddress, service.Address), - errorc.String(keys.Validation, "service addresses must be unique"), + errorc.String(keys.Fields, "Spec.Services["+strconv.Itoa(i)+"].E2EnginePort"), + errorc.String( + keys.Validation, + "E2Engine ports must be unique within an environment", + ), ) } - addresses[service.Address] = struct{}{} - if err := service.Validate(); err != nil { + ports[service.E2EnginePort] = struct{}{} + + if err := service.Validate(i); err != nil { return err } } @@ -99,34 +98,40 @@ type ServiceSpec struct { ID string `json:"id" yaml:"id" validate:"min(3),max(200)"` Kind ServiceKind `json:"kind" yaml:"kind" validate:"oneof(http,grpc)"` Mode ServiceMode `json:"mode" yaml:"mode" validate:"oneof(real,mocked)"` - // Stable logical address used inside the environment. - Address string `json:"address" yaml:"address" validate:"networkaddress"` - - // Actual destination of a real service. - HTTPTarget string `json:"http_target,omitempty" yaml:"http_target,omitempty" validate:"omitempty,httpurl"` - GRPCTarget string `json:"grpc_target,omitempty" yaml:"grpc_target,omitempty" validate:"omitempty,networkaddress"` - RequestDefaults *RequestDefaults `json:"request_defaults,omitempty" yaml:"request_defaults,omitempty" validateElem:"omitempty,dive"` + E2EnginePort int `json:"e2engine_port" yaml:"e2engine_port" validate:"min(1),max(65535)"` - Fixtures []FixtureSpec `json:"fixtures,omitempty" yaml:"fixtures,omitempty" validateElem:"dive"` + // Required for real services, forbidden for mocked services. + // The hostname may be overridden by runtime hostname mappings. + Target string `json:"target,omitempty" yaml:"target,omitempty"` - // gRPC-only - Proto *GRPCProtoSpec `json:"proto,omitempty" yaml:"proto,omitempty" validateElem:"omitempty,dive"` + RequestDefaults *RequestDefaults `json:"request_defaults,omitempty" yaml:"request_defaults,omitempty" validateElem:"omitempty,dive"` + Fixtures []FixtureSpec `json:"fixtures,omitempty" yaml:"fixtures,omitempty" validateElem:"dive"` + Proto *GRPCProtoSpec `json:"proto,omitempty" yaml:"proto,omitempty" validateElem:"omitempty,dive"` } -func (s *ServiceSpec) Validate() error { +func (s *ServiceSpec) Validate(index int) error { if s.Kind == ServiceKindHTTP { if s.Proto != nil { return errorc.With( errors.ErrInvalidSpec, errorc.String(keys.SpecKind, string(EntityKindEnvironment)), + errorc.String( + keys.Fields, + "Spec.Services["+strconv.Itoa(index)+"].Proto", + ), errorc.String(keys.Validation, "proto spec is not allowed for HTTP service"), ) } + if s.RequestDefaults != nil && len(s.RequestDefaults.Metadata) > 0 { return errorc.With( errors.ErrInvalidSpec, errorc.String(keys.SpecKind, string(EntityKindEnvironment)), + errorc.String( + keys.Fields, + "Spec.Services["+strconv.Itoa(index)+"].RequestDefaults.Metadata", + ), errorc.String(keys.Validation, "metadata is not allowed for HTTP service"), ) } @@ -137,6 +142,10 @@ func (s *ServiceSpec) Validate() error { return errorc.With( errors.ErrInvalidSpec, errorc.String(keys.SpecKind, string(EntityKindEnvironment)), + errorc.String( + keys.Fields, + "Spec.Services["+strconv.Itoa(index)+"].RequestDefaults.Headers", + ), errorc.String(keys.Validation, "headers are not allowed for GRPC service"), ) } @@ -145,6 +154,10 @@ func (s *ServiceSpec) Validate() error { return errorc.With( errors.ErrInvalidSpec, errorc.String(keys.SpecKind, string(EntityKindEnvironment)), + errorc.String( + keys.Fields, + "Spec.Services["+strconv.Itoa(index)+"].Proto", + ), errorc.String(keys.Validation, "proto spec is required for GRPC service"), ) } @@ -153,6 +166,11 @@ func (s *ServiceSpec) Validate() error { return errorc.With( errors.ErrInvalidSpec, errorc.String(keys.SpecKind, string(EntityKindEnvironment)), + errorc.String( + keys.Fields, + "Spec.Services["+strconv.Itoa(index)+"].Proto.External, "+ + "Spec.Services["+strconv.Itoa(index)+"].Proto.Internal", + ), errorc.String( keys.Validation, "exactly one of external or internal proto spec must be provided for GRPC service", @@ -164,6 +182,11 @@ func (s *ServiceSpec) Validate() error { return errorc.With( errors.ErrInvalidSpec, errorc.String(keys.SpecKind, string(EntityKindEnvironment)), + errorc.String( + keys.Fields, + "Spec.Services["+strconv.Itoa(index)+"].Mode, "+ + "Spec.Services["+strconv.Itoa(index)+"].Proto.Internal", + ), errorc.String( keys.Validation, "internal proto spec is not allowed for real GRPC service", @@ -176,6 +199,10 @@ func (s *ServiceSpec) Validate() error { return errorc.With( errors.ErrInvalidSpec, errorc.String(keys.SpecKind, string(EntityKindEnvironment)), + errorc.String( + keys.Fields, + "Spec.Services["+strconv.Itoa(index)+"].Proto.Internal.Methods", + ), errorc.String( keys.Validation, "internal proto spec must contain at least one method", @@ -191,6 +218,11 @@ func (s *ServiceSpec) Validate() error { return errorc.With( errors.ErrInvalidSpec, errorc.String(keys.SpecKind, string(EntityKindEnvironment)), + errorc.String( + keys.Fields, + "Spec.Services["+strconv.Itoa(index)+"].Proto.External.File, "+ + "Spec.Services["+strconv.Itoa(index)+"].Proto.External.BufModule", + ), errorc.String( keys.Validation, "exactly one of file or buf_module must be provided for external GRPC proto spec", @@ -201,56 +233,85 @@ func (s *ServiceSpec) Validate() error { } if s.Mode == ServiceModeMocked { - if len(s.Fixtures) == 0 { + if s.Target != "" { return errorc.With( errors.ErrInvalidSpec, errorc.String(keys.SpecKind, string(EntityKindEnvironment)), - errorc.String(keys.Validation, "mocked service must have at least one fixture"), + errorc.String( + keys.Fields, + "Spec.Services["+strconv.Itoa(index)+"].Mode, "+ + "Spec.Services["+strconv.Itoa(index)+"].Target", + ), + errorc.String(keys.Validation, "target is not allowed for mocked service"), ) } - if s.HTTPTarget != "" || s.GRPCTarget != "" { + if len(s.Fixtures) == 0 { return errorc.With( errors.ErrInvalidSpec, errorc.String(keys.SpecKind, string(EntityKindEnvironment)), - errorc.String(keys.Validation, "mocked service must not have a target"), + errorc.String( + keys.Fields, + "Spec.Services["+strconv.Itoa(index)+"].Mode, "+ + "Spec.Services["+strconv.Itoa(index)+"].Fixtures", + ), + errorc.String(keys.Validation, "mocked service must contain at least one fixture"), ) } } if s.Mode == ServiceModeReal { - if (s.Kind == ServiceKindHTTP && s.HTTPTarget == "") || - (s.Kind == ServiceKindGRPC && s.GRPCTarget == "") { + if s.Target == "" { return errorc.With( errors.ErrInvalidSpec, errorc.String(keys.SpecKind, string(EntityKindEnvironment)), + errorc.String( + keys.Fields, + "Spec.Services["+strconv.Itoa(index)+"].Target", + ), errorc.String(keys.Validation, "target is required for real service"), ) } - if s.Kind == ServiceKindHTTP && s.GRPCTarget != "" { - return errorc.With( - errors.ErrInvalidSpec, - errorc.String(keys.SpecKind, string(EntityKindEnvironment)), - errorc.String(keys.Validation, "GRPC target is not allowed for HTTP service"), - ) - } - - if s.Kind == ServiceKindGRPC && s.HTTPTarget != "" { - return errorc.With( - errors.ErrInvalidSpec, - errorc.String(keys.SpecKind, string(EntityKindEnvironment)), - errorc.String(keys.Validation, "HTTP target is not allowed for GRPC service"), - ) - } - if len(s.Fixtures) > 0 { return errorc.With( errors.ErrInvalidSpec, errorc.String(keys.SpecKind, string(EntityKindEnvironment)), + errorc.String( + keys.Fields, + "Spec.Services["+strconv.Itoa(index)+"].Mode, "+ + "Spec.Services["+strconv.Itoa(index)+"].Fixtures", + ), errorc.String(keys.Validation, "fixtures are not allowed for real service"), ) } + + switch s.Kind { + case ServiceKindHTTP: + if err := validateHTTPURL(s.Target); err != nil { + return errorc.With( + errors.ErrInvalidSpec, + errorc.String(keys.SpecKind, string(EntityKindEnvironment)), + errorc.String( + keys.Fields, + "Spec.Services["+strconv.Itoa(index)+"].Target", + ), + errorc.String(keys.Validation, err.Error()), + ) + } + case ServiceKindGRPC: + if err := validateNetworkAddress(s.Target); err != nil { + return errorc.With( + errors.ErrInvalidSpec, + errorc.String(keys.SpecKind, string(EntityKindEnvironment)), + errorc.String( + keys.Fields, + "Spec.Services["+strconv.Itoa(index)+"].Target", + ), + errorc.String(keys.Validation, err.Error()), + ) + } + } } for i := range s.Fixtures { @@ -262,33 +323,49 @@ func (s *ServiceSpec) Validate() error { return errorc.With( errors.ErrInvalidSpec, errorc.String(keys.SpecKind, string(EntityKindEnvironment)), + errorc.String( + keys.Fields, + "Spec.Services["+strconv.Itoa(index)+"].Fixtures["+strconv.Itoa(i)+"].When.HTTP, "+ + "Spec.Services["+strconv.Itoa(index)+"].Fixtures["+strconv.Itoa(i)+"].Then.HTTP", + ), errorc.String(keys.Validation, "HTTP service fixture must contain HTTP when and then"), ) } + if fixture.When.GRPC != nil || fixture.Then.GRPC != nil { return errorc.With( errors.ErrInvalidSpec, errorc.String(keys.SpecKind, string(EntityKindEnvironment)), + errorc.String( + keys.Fields, + "Spec.Services["+strconv.Itoa(index)+"].Fixtures["+strconv.Itoa(i)+"].When.GRPC, "+ + "Spec.Services["+strconv.Itoa(index)+"].Fixtures["+strconv.Itoa(i)+"].Then.GRPC", + ), errorc.String(keys.Validation, "gRPC fixture is not allowed for HTTP service"), ) } if err := fixture.When.HTTP.Validate(); err != nil { - return nativeerrors.Join( - errorc.With( - errors.ErrInvalidSpec, - errorc.String(keys.SpecKind, string(EntityKindEnvironment)), + return errorc.With( + errors.ErrInvalidSpec, + errorc.String(keys.SpecKind, string(EntityKindEnvironment)), + errorc.String( + keys.Fields, + "Spec.Services["+strconv.Itoa(index)+"].Fixtures["+strconv.Itoa(i)+"].When.HTTP", ), - err, + errorc.String(keys.Validation, err.Error()), ) } + if err := fixture.Then.HTTP.Validate(); err != nil { - return nativeerrors.Join( - errorc.With( - errors.ErrInvalidSpec, - errorc.String(keys.SpecKind, string(EntityKindEnvironment)), + return errorc.With( + errors.ErrInvalidSpec, + errorc.String(keys.SpecKind, string(EntityKindEnvironment)), + errorc.String( + keys.Fields, + "Spec.Services["+strconv.Itoa(index)+"].Fixtures["+strconv.Itoa(i)+"].Then.HTTP", ), - err, + errorc.String(keys.Validation, err.Error()), ) } @@ -297,13 +374,23 @@ func (s *ServiceSpec) Validate() error { return errorc.With( errors.ErrInvalidSpec, errorc.String(keys.SpecKind, string(EntityKindEnvironment)), + errorc.String( + keys.Fields, + "Spec.Services["+strconv.Itoa(index)+"].Fixtures["+strconv.Itoa(i)+"].When.GRPC, "+ + "Spec.Services["+strconv.Itoa(index)+"].Fixtures["+strconv.Itoa(i)+"].Then.GRPC"), errorc.String(keys.Validation, "gRPC service fixture must contain gRPC when and then"), ) } + if fixture.When.HTTP != nil || fixture.Then.HTTP != nil { return errorc.With( errors.ErrInvalidSpec, errorc.String(keys.SpecKind, string(EntityKindEnvironment)), + errorc.String( + keys.Fields, + "Spec.Services["+strconv.Itoa(index)+"].Fixtures["+strconv.Itoa(i)+"].When.HTTP, "+ + "Spec.Services["+strconv.Itoa(index)+"].Fixtures["+strconv.Itoa(i)+"].Then.HTTP", + ), errorc.String(keys.Validation, "HTTP fixture is not allowed for gRPC service"), ) } diff --git a/model/grpc.go b/model/grpc.go index 6da7837..08682e5 100644 --- a/model/grpc.go +++ b/model/grpc.go @@ -3,7 +3,12 @@ package model import "github.com/e2engine/core/model/matcher" type GRPCRequest struct { - Target string `json:"target" yaml:"target" validate:"networkaddress"` + // Target is the gRPC server address to connect to. + Target string `json:"target" yaml:"target" validate:"networkaddress"` + + // Proto is the gRPC proto specification used to encode and decode messages. + Proto *GRPCProtoSpec `json:"proto,omitempty" yaml:"proto,omitempty" validateElem:"omitempty,dive"` + Service string `json:"service" yaml:"service" validate:"min(1)"` Method string `json:"method" yaml:"method" validate:"min(1)"` Metadata map[string][]string `json:"metadata,omitempty" yaml:"metadata,omitempty"` diff --git a/model/http.go b/model/http.go index 4726598..77d2cc2 100644 --- a/model/http.go +++ b/model/http.go @@ -9,13 +9,11 @@ import ( modellib "github.com/ygrebnov/model" "github.com/e2engine/core/model/matcher" - "github.com/e2engine/core/pkg/errors" - "github.com/e2engine/core/pkg/keys" ) type HTTPRequest struct { Method string `json:"method" yaml:"method" validate:"oneof(GET,POST,PUT,DELETE,PATCH,OPTIONS,HEAD)"` - URL string `json:"url" yaml:"url" validate:"min(1)"` + URL string `json:"url" yaml:"url" validate:"httpurl"` Query map[string][]string `json:"query,omitempty" yaml:"query,omitempty"` Headers map[string][]string `json:"headers,omitempty" yaml:"headers,omitempty"` Body string `json:"body,omitempty" yaml:"body,omitempty"` @@ -23,26 +21,6 @@ type HTTPRequest struct { } func (h *HTTPRequest) Validate() error { - u, err := url.ParseRequestURI(h.URL) - if err != nil { - return errorc.With( - errorc.New("invalid HTTP request URL"), - errorc.Error(keys.Cause, err), - ) - } - - if u.Scheme != "http" && u.Scheme != "https" { - return errorc.New( - "HTTP request URL scheme must be http or https", - ) - } - - if strings.TrimSpace(u.Host) == "" { - return errorc.New( - "HTTP request URL must contain a host", - ) - } - if h.Body != "" && h.BodyJSON != "" { return errorc.New( "HTTP request cannot have both body and body_json set", @@ -59,22 +37,20 @@ type HTTPRequestPattern struct { Path string `json:"path" yaml:"path" validate:"min(1)"` Query map[string][]string `json:"query,omitempty" yaml:"query,omitempty"` Headers map[string][]matcher.String `json:"headers,omitempty" yaml:"headers,omitempty" validateElem:"stringmatchers"` + // Body is nil when body matching should be skipped. // A non-nil matcher defines how the body is matched, including explicit // matching of an empty body. Body *matcher.String `json:"body,omitempty" yaml:"body,omitempty" validate:"stringmatcher"` + // BodyJSON matches the response body as JSON. For the equals operator, // Value must contain valid JSON and comparison is JSON-semantic. BodyJSON *matcher.String `json:"body_json,omitempty" yaml:"body_json,omitempty" validate:"stringmatcher,validjson"` } func (h *HTTPRequestPattern) Validate() error { - u, err := url.ParseRequestURI(h.Path) - if err != nil || - u.Path == "" || - !strings.HasPrefix(u.Path, "/") || - u.RawQuery != "" { - return errorc.New("invalid HTTP request path") + if err := validateHTTPPath(h.Path); err != nil { + return err } if h.Body != nil && h.BodyJSON != nil { @@ -86,6 +62,19 @@ func (h *HTTPRequestPattern) Validate() error { return nil } +func validateHTTPPath(path string) error { + u, err := url.ParseRequestURI(path) + if err != nil || + u.Path == "" || + !strings.HasPrefix(u.Path, "/") || + u.RawQuery != "" || + u.Fragment != "" { + return errorc.New("invalid HTTP request path") + } + + return nil +} + // HTTPResponse describes HTTP response observed during execution or a Fixture Then response. // Validation is needed for Fixture.Then validation. type HTTPResponse struct { @@ -109,10 +98,12 @@ func (h *HTTPResponse) Validate() error { type HTTPResponsePattern struct { StatusCode int `json:"status_code" yaml:"status_code" validate:"min(100),max(599)"` Headers map[string][]matcher.String `json:"headers,omitempty" yaml:"headers,omitempty" validateElem:"stringmatchers"` + // Body is nil when body matching should be skipped. // A non-nil matcher defines how the body is matched, including explicit // matching of an empty body. Body *matcher.String `json:"body,omitempty" yaml:"body,omitempty" validate:"stringmatcher"` + // BodyJSON matches the response body as JSON. For the equals operator, // Value must contain valid JSON and comparison is JSON-semantic. BodyJSON *matcher.String `json:"body_json,omitempty" yaml:"body_json,omitempty" validate:"stringmatcher,validjson"` @@ -133,15 +124,10 @@ func getStringMatcherValidJSONRule() (modellib.Rule, error) { if value == nil { return nil } + if value.Operator == matcher.StringMatchOperatorEquals { if !json.Valid([]byte(value.Value)) { - return errorc.With( - errors.ErrInvalidSpec, - errorc.String( - keys.Validation, - "value must contain valid JSON", - ), - ) + return errorc.New("value must contain valid JSON") } } diff --git a/model/matcher/grpc_message.go b/model/matcher/grpc_message.go index 243cbb0..b9ffa23 100644 --- a/model/matcher/grpc_message.go +++ b/model/matcher/grpc_message.go @@ -56,7 +56,6 @@ func (m *GRPCMessage) UnmarshalJSON(data []byte) error { return errorc.With( errors.ErrInvalidGRPCMessageMatcher, errorc.String(keys.Validation, "gRPC message matcher must be a string or object"), - errorc.Error(keys.Cause, err), ) } diff --git a/model/matcher/string.go b/model/matcher/string.go index 5bbbd54..7369ba9 100644 --- a/model/matcher/string.go +++ b/model/matcher/string.go @@ -2,7 +2,6 @@ package matcher import ( "encoding/json" - "fmt" "github.com/ygrebnov/errorc" modellib "github.com/ygrebnov/model" @@ -55,9 +54,12 @@ func (m *String) UnmarshalJSON(data []byte) error { type alias String var matcher alias if err := json.Unmarshal(data, &matcher); err != nil { - return fmt.Errorf( - "string matcher must be a string or object: %w", - err, + return errorc.With( + errors.ErrInvalidStringMatcher, + errorc.String( + keys.Validation, + "string matcher must be a string or object", + ), ) } @@ -85,8 +87,12 @@ func (m *String) UnmarshalYAML(node *yaml.Node) error { } if node.Kind != yaml.MappingNode { - return fmt.Errorf( - "string matcher must be a string or object", + return errorc.With( + errors.ErrInvalidStringMatcher, + errorc.String( + keys.Validation, + "string matcher must be a string or object", + ), ) } diff --git a/model/test.go b/model/test.go index bca218e..674e869 100644 --- a/model/test.go +++ b/model/test.go @@ -2,7 +2,7 @@ package model import ( "context" - nativeerrors "errors" + "strconv" "github.com/ygrebnov/errorc" modellib "github.com/ygrebnov/model" @@ -17,46 +17,37 @@ var testBinding *modellib.Binding[Test] func (t *Test) Validate(ctx context.Context) error { if t.Kind != ResourceKindTest { - return errorc.With( - errors.ErrInvalidSpec, - errorc.String(keys.SpecKind, string(EntityKindTest)), - errorc.String(keys.Validation, "invalid resource kind"), - ) + return invalidTestSpec(errorc.New("invalid kind"), "Kind") } if err := testBinding.Validate(ctx, t); err != nil { - return nativeerrors.Join( - errorc.With( - errors.ErrInvalidSpec, - errorc.String(keys.SpecKind, string(EntityKindTest)), - ), - err, - ) + return handleValidationError(err, EntityKindTest) } - if err := t.Spec.validateTags(); err != nil { - return invalidTestSpec(err) + if index, err := t.Spec.validateTags(); err != nil { + return invalidTestSpec(err, "Spec.Tags["+strconv.Itoa(index)+"]") } - if err := t.Spec.validateProtocol(); err != nil { - return invalidTestSpec(err) + fields, err := t.Spec.validateProtocol() + if err != nil { + return invalidTestSpec(err, fields) } if t.Spec.Request.HTTP != nil { if err := t.Spec.Request.HTTP.Validate(); err != nil { - return invalidTestSpec(err) + return invalidTestSpec(err, "Spec.Request.HTTP") } } if t.Spec.Expect.HTTP != nil { if err := t.Spec.Expect.HTTP.Validate(); err != nil { - return invalidTestSpec(err) + return invalidTestSpec(err, "Spec.Expect.HTTP") } } for i := range t.Spec.Expect.Calls { if err := t.Spec.Expect.Calls[i].Validate(); err != nil { - return invalidTestSpec(err) + return invalidTestSpec(err, "Spec.Expect.Calls["+strconv.Itoa(i)+"]") } } @@ -69,12 +60,12 @@ type TestSpec struct { Expect ExpectSpec `json:"expect" yaml:"expect"` } -func (s *TestSpec) validateTags() error { +func (s *TestSpec) validateTags() (int, error) { tags := make(map[string]struct{}, len(s.Tags)) - for _, tag := range s.Tags { + for i, tag := range s.Tags { if _, ok := tags[tag]; ok { - return errorc.With( + return i, errorc.With( errorc.New("test tags must be unique"), errorc.String(keys.TestTag, tag), ) @@ -83,18 +74,17 @@ func (s *TestSpec) validateTags() error { tags[tag] = struct{}{} } - return nil + return 0, nil } -func (s *TestSpec) validateProtocol() error { +func (s *TestSpec) validateProtocol() (string, error) { requestHTTP := s.Request.HTTP != nil requestGRPC := s.Request.GRPC != nil // Both nil or both non-nil are invalid. if requestHTTP == requestGRPC { - return errorc.New( - "request must contain exactly one of http or grpc", - ) + return "Spec.Request.HTTP, Spec.Request.GRPC", + errorc.New("request must contain exactly one of http or grpc") } expectHTTP := s.Expect.HTTP != nil @@ -102,28 +92,29 @@ func (s *TestSpec) validateProtocol() error { // Both nil or both non-nil are invalid. if expectHTTP == expectGRPC { - return errorc.New( - "expect must contain exactly one of http or grpc", - ) + return "Spec.Expect.HTTP, Spec.Expect.GRPC", + errorc.New("expect must contain exactly one of http or grpc") } - if requestHTTP != expectHTTP || - requestGRPC != expectGRPC { - return errorc.New( - "request and expect protocols must match", - ) + if requestHTTP != expectHTTP { + return "Spec.Request.HTTP, Spec.Expect.HTTP", + errorc.New("request and expect protocols must match") } - return nil + if requestGRPC != expectGRPC { + return "Spec.Request.GRPC, Spec.Expect.GRPC", + errorc.New("request and expect protocols must match") + } + + return "", nil } -func invalidTestSpec(validation error) error { - return nativeerrors.Join( - errorc.With( - errors.ErrInvalidSpec, - errorc.String(keys.SpecKind, string(EntityKindTest)), - ), - validation, +func invalidTestSpec(validation error, fields string) error { + return errorc.With( + errors.ErrInvalidSpec, + errorc.String(keys.SpecKind, string(EntityKindTest)), + errorc.String(keys.Fields, fields), + errorc.String(keys.Validation, validation.Error()), ) } diff --git a/model/testsuite.go b/model/testsuite.go index 6db674f..5624645 100644 --- a/model/testsuite.go +++ b/model/testsuite.go @@ -3,6 +3,7 @@ package model import ( "context" nativeerrors "errors" + "strconv" "github.com/ygrebnov/errorc" modellib "github.com/ygrebnov/model" @@ -17,25 +18,15 @@ var testSuiteBinding *modellib.Binding[TestSuite] func (t *TestSuite) Validate(ctx context.Context) error { if t.Kind != ResourceKindTestSuite { - return errorc.With( - errors.ErrInvalidSpec, - errorc.String(keys.SpecKind, string(EntityKindTestSuite)), - errorc.String(keys.Validation, "invalid resource kind"), - ) + return invalidTestSuiteSpec(nativeerrors.New("invalid kind"), "Kind") } if err := testSuiteBinding.Validate(ctx, t); err != nil { - return nativeerrors.Join( - errorc.With( - errors.ErrInvalidSpec, - errorc.String(keys.SpecKind, string(EntityKindTestSuite)), - ), - err, - ) + return handleValidationError(err, EntityKindTestSuite) } - if err := t.Spec.Selectors.Validate(ctx); err != nil { - return invalidTestSuiteSpec(err) + if fields, err := t.Spec.Selectors.Validate(); err != nil { + return invalidTestSuiteSpec(err, fields) } return nil @@ -45,48 +36,50 @@ type TestSuiteSpec struct { Selectors TestSelectorsSpec `json:"selectors" yaml:"selectors"` } -func invalidTestSuiteSpec(validation error) error { - return nativeerrors.Join( - errorc.With( - errors.ErrInvalidSpec, - errorc.String(keys.SpecKind, string(EntityKindTestSuite)), - ), - validation, +func invalidTestSuiteSpec(validation error, fields string) error { + return errorc.With( + errors.ErrInvalidSpec, + errorc.String(keys.SpecKind, string(EntityKindTestSuite)), + errorc.String(keys.Fields, fields), + errorc.String(keys.Validation, validation.Error()), ) } type TestSelectorsSpec struct { - IDs []string `json:"ids,omitempty" yaml:"ids,omitempty" validateElem:"min(1),max(200)"` + IDs []string `json:"ids,omitempty" yaml:"ids,omitempty" validateElem:"id"` Names []string `json:"names,omitempty" yaml:"names,omitempty" validateElem:"min(1),max(200)"` Tags []string `json:"tags,omitempty" yaml:"tags,omitempty" validateElem:"min(1),max(200)"` } -func (s *TestSelectorsSpec) Validate(_ context.Context) error { +func (s *TestSelectorsSpec) Validate() (string, error) { if len(s.IDs) == 0 && len(s.Names) == 0 && len(s.Tags) == 0 { - return errorc.New("test selectors spec must contain at least one of ids, names, or tags") + return "Spec.Selectors.IDs, Spec.Selectors.Names, Spec.Selectors.Tags", + errorc.New("test selectors spec must contain at least one of ids, names, or tags") } - if err := validateUniqueSelectors(s.IDs, "ids"); err != nil { - return err + + if index, err := validateUniqueSelectors(s.IDs, "ids"); err != nil { + return "Spec.Selectors.IDs[" + strconv.Itoa(index) + "]", err } - if err := validateUniqueSelectors(s.Names, "names"); err != nil { - return err + if index, err := validateUniqueSelectors(s.Names, "names"); err != nil { + return "Spec.Selectors.Names[" + strconv.Itoa(index) + "]", err } - if err := validateUniqueSelectors(s.Tags, "tags"); err != nil { - return err + if index, err := validateUniqueSelectors(s.Tags, "tags"); err != nil { + return "Spec.Selectors.Tags[" + strconv.Itoa(index) + "]", err } - return nil + + return "", nil } type TestSuitesPage = Page[TestSuite] -func validateUniqueSelectors(values []string, selector string) error { +func validateUniqueSelectors(values []string, selector string) (int, error) { seen := make(map[string]struct{}, len(values)) - for _, value := range values { + for i, value := range values { if _, ok := seen[value]; ok { - return errorc.With( + return i, errorc.With( errorc.New("test selectors must be unique"), errorc.String(keys.TestSuiteSelector, selector), errorc.String(keys.Value, value), @@ -96,5 +89,5 @@ func validateUniqueSelectors(values []string, selector string) error { seen[value] = struct{}{} } - return nil + return 0, nil } diff --git a/model/validation.go b/model/validation.go index fa5dca8..ff0fc28 100644 --- a/model/validation.go +++ b/model/validation.go @@ -2,6 +2,7 @@ package model import ( "encoding/json" + nativeerrors "errors" "net" "net/url" "regexp" @@ -11,6 +12,7 @@ import ( "github.com/ygrebnov/errorc" modellib "github.com/ygrebnov/model" + "github.com/ygrebnov/model/validation" "github.com/e2engine/core/model/matcher" "github.com/e2engine/core/pkg/errors" @@ -20,7 +22,7 @@ import ( var validationRules []modellib.Rule func init() { - validationRules = make([]modellib.Rule, 8) + validationRules = make([]modellib.Rule, 9) idRule, err := getIDRule() if err != nil { @@ -62,6 +64,11 @@ func init() { panic(err) } + ipRule, err := getIPRule() + if err != nil { + panic(err) + } + validationRules[0] = idRule validationRules[1] = networkAddressRule validationRules[2] = httpURLRule @@ -70,6 +77,7 @@ func init() { validationRules[5] = stringMatchersRule validationRules[6] = stringMatcherValidJSONRule validationRules[7] = grpcMessageMatcherRule + validationRules[8] = ipRule environmentBinding, err = modellib.NewBinding[Environment](modellib.WithRules(validationRules...)) if err != nil { @@ -104,132 +112,117 @@ func getIDRule() (modellib.Rule, error) { func getNetworkAddressRule() (modellib.Rule, error) { return modellib.NewRule[string]("networkaddress", func(address string, _ ...string) error { - if address == "" { - return errorc.New("network address must not be empty") - } + return validateNetworkAddress(address) + }) +} - host, portRaw, err := net.SplitHostPort(address) - if err != nil { - return errorc.With( - errors.ErrInvalidSpec, - errorc.String(keys.Validation, "network address must be in host:port form"), - errorc.Error(keys.Cause, err), - ) - } +func validateNetworkAddress(address string) error { + if address == "" { + return errorc.New("network address must not be empty") + } - if strings.TrimSpace(host) == "" { - return errorc.With( - errors.ErrInvalidSpec, - errorc.String(keys.Validation, "network address host must not be empty"), - ) - } + host, portRaw, err := net.SplitHostPort(address) + if err != nil { + return errorc.New("network address must be in host:port form") + } - port, err := strconv.ParseUint(portRaw, 10, 16) - if err != nil || port == 0 { - return errorc.With( - errors.ErrInvalidSpec, - errorc.String( - keys.Validation, - "network address port must be an integer between 1 and 65535", - ), - ) - } + if strings.TrimSpace(host) == "" { + return errorc.New("network address host must not be empty") + } - return nil - }) + port, err := strconv.ParseUint(portRaw, 10, 16) + if err != nil || port == 0 { + return errorc.New("network address port must be an integer between 1 and 65535") + } + + return nil } func getHTTPURLRule() (modellib.Rule, error) { return modellib.NewRule[string]( "httpurl", func(value string, _ ...string) error { - u, err := url.ParseRequestURI(value) - if err != nil { - return errorc.With( - errors.ErrInvalidSpec, - errorc.String( - keys.Validation, - "target must be a valid HTTP URL", - ), - errorc.Error(keys.Cause, err), - ) - } + return validateHTTPURL(value) + }, + ) +} - if u.Scheme != "http" && - u.Scheme != "https" { - return errorc.With( - errors.ErrInvalidSpec, - errorc.String( - keys.Validation, - "target URL scheme must be http or https", - ), - ) - } +func validateHTTPURL(value string) error { + u, err := url.ParseRequestURI(value) + if err != nil { + return errorc.New("target must be a valid HTTP URL") + } - if u.Host == "" { - return errorc.With( - errors.ErrInvalidSpec, - errorc.String( - keys.Validation, - "target URL host must not be empty", - ), - ) - } + if u.Scheme != "http" && u.Scheme != "https" { + return errorc.New("target URL scheme must be http or https") + } - if u.User != nil { - return errorc.With( - errors.ErrInvalidSpec, - errorc.String( - keys.Validation, - "target URL must not contain user info", - ), - ) - } + if u.Hostname() == "" { + return errorc.New("target URL host must not be empty") + } - if u.RawQuery != "" || u.Fragment != "" { - return errorc.With( - errors.ErrInvalidSpec, - errorc.String( - keys.Validation, - "target URL must not contain query parameters or fragment", - ), - ) - } + if u.User != nil { + return errorc.New("target URL must not contain user info") + } - if portRaw := u.Port(); portRaw != "" { - port, err := strconv.ParseUint( - portRaw, - 10, - 16, - ) - if err != nil || port == 0 { - return errorc.With( - errors.ErrInvalidSpec, - errorc.String( - keys.Validation, - "target URL port must be an integer between 1 and 65535", - ), - ) - } - } + if u.RawQuery != "" || u.Fragment != "" { + return errorc.New("target URL must not contain query parameters or fragment") + } - return nil - }, - ) + if portRaw := u.Port(); portRaw != "" { + port, err := strconv.ParseUint(portRaw, 10, 16) + if err != nil || port == 0 { + return errorc.New("target URL port must be an integer between 1 and 65535") + } + } + + return nil } func getValidJSONRule() (modellib.Rule, error) { return modellib.NewRule[string]("validjson", func(value string, _ ...string) error { if !json.Valid([]byte(value)) { - return errorc.With( - errors.ErrInvalidSpec, - errorc.String( - keys.Validation, - "value must contain valid JSON", - ), - ) + return errorc.New("value must contain valid JSON") } return nil }) } + +func getIPRule() (modellib.Rule, error) { + return modellib.NewRule[string]("ip", func(ip string, _ ...string) error { + if net.ParseIP(ip) == nil { + return errorc.New("invalid E2Engine listen interface IP address") + } + return nil + }) +} + +func handleValidationError(err error, specKind EntityKind) error { + var fields string + + if validationErr, ok := nativeerrors.AsType[*validation.Error](err); ok { + fields = strings.Join(validationErr.Fields(), ", ") + + validationErrs := make([]string, 0, validationErr.Len()) + for _, path := range validationErr.Fields() { + for _, fieldErr := range validationErr.ForField(path) { + validationErrs = append(validationErrs, fieldErr.Err.Error()) + } + } + combinedErr := strings.Join(validationErrs, ", ") + + return errorc.With( + errors.ErrInvalidSpec, + errorc.String(keys.SpecKind, string(specKind)), + errorc.String(keys.Fields, fields), + errorc.String(keys.Validation, combinedErr), + ) + } + + return errorc.With( + errors.ErrInvalidSpec, + errorc.String(keys.SpecKind, string(specKind)), + errorc.String(keys.Validation, err.Error()), + ) +} diff --git a/pkg/errors/errors.go b/pkg/errors/errors.go index 037eafe..2a7d87b 100644 --- a/pkg/errors/errors.go +++ b/pkg/errors/errors.go @@ -59,7 +59,20 @@ var ( ErrUnsupportedFileType = errorc.New("unsupported file type") + ErrInvalidStringMatcher = errorc.New("invalid string matcher") ErrInvalidGRPCMessageMatcher = errorc.New("invalid gRPC message matcher") + + ErrInvalidHTTPURL = errorc.New("invalid HTTP URL") + ErrInvalidHostnameMapping = errorc.New("invalid hostname mapping") + ErrInvalidGRPCTarget = errorc.New("invalid gRPC target") + ErrHTTPRequestBodyTooLarge = errorc.New("HTTP request body too large") + ErrHTTPResponseBodyTooLarge = errorc.New("HTTP response body too large") + ErrHTTPRecordedRequestBodyTruncated = errorc.New("recorded HTTP request body is truncated") + ErrHTTPRecordedRequestBodyIncomplete = errorc.New("recorded HTTP request body is incomplete") + + ErrGRPCRequestMessageTooLarge = errorc.New("gRPC request message too large") + + ErrCallStoreLimitExceeded = errorc.New("call store maximum number of calls exceeded") ) // Is wraps native errors package Is. diff --git a/pkg/keys/keys.go b/pkg/keys/keys.go index 33bab6b..c1ccf14 100644 --- a/pkg/keys/keys.go +++ b/pkg/keys/keys.go @@ -41,8 +41,11 @@ var ( MatcherOperator = keys.New("matcher.operator") - RequestMethod = request("method") - RequestURLPath = request("url.path") + URL = keys.New("url") + HostnameMappingFrom = keys.New("hostname.mapping.from") + HostnameMappingTo = keys.New("hostname.mapping.to") + RequestMethod = request("method") + RequestURLPath = request("url.path") HTTPStatusCode = http("status.code") HTTPResponseBody = http("response.body") @@ -90,4 +93,6 @@ var ( OrderBy = keys.New("OrderBy") OrderDirection = keys.New("OrderDirection") + + Fields = keys.New("fields") ) diff --git a/repository/repository.go b/repository/repository.go index 8a87a31..b6e9ba9 100644 --- a/repository/repository.go +++ b/repository/repository.go @@ -9,12 +9,16 @@ import ( ) var ( - ErrNotFound = errorc.New("not found") - ErrConflict = errorc.New("conflict") - ErrAlreadyExists = errorc.New("already exists") - ErrInvalidPayload = errorc.New("invalid payload") - ErrInvalidPageTraversal = errorc.New("invalid page traversal") - ErrInvalidPageLimit = errorc.New("invalid page limit") + ErrNotFound = errorc.New("not found") + ErrConflict = errorc.New("conflict") + ErrAlreadyExists = errorc.New("already exists") + ErrInvalidPayload = errorc.New("invalid payload") + ErrInvalidPageTraversal = errorc.New("invalid page traversal") + ErrInvalidPageLimit = errorc.New("invalid page limit") + ErrInvalidExecutionStateTransition = errorc.New("invalid execution state transition") + ErrInvalidExecutionStatus = errorc.New("invalid execution status") + ErrTooManyResults = errorc.New("too many results") + ErrInvalidType = errorc.New("invalid type") ) type EntityRepository[E Entity] interface { @@ -35,7 +39,7 @@ type TestSuiteRepository = ResourceRepository[TestSuite] type TestRepository interface { ResourceRepository[Test] - GetByTag(ctx context.Context, tag string) ([]Test, error) + GetByTag(ctx context.Context, tag string, limit int) ([]Test, error) } type SetRunningParams struct { @@ -46,23 +50,40 @@ type SetRunningParams struct { type SetCompletedParams struct { ID string `json:"id"` FinishedAt time.Time `json:"finished_at"` - Status string `json:"status"` + Status ExecutionStatus `json:"status"` Summary json.RawMessage `json:"summary"` } +type TestSuiteExecutionState struct { + Status ExecutionStatus + Count int + LastTestFinishedAt time.Time +} + type TestExecutionRepository interface { EntityRepository[TestExecution] + GetByTestSuiteExecutionID(ctx context.Context, id string) ([]TestExecution, error) + // GetTestSuiteExecutionStates returns aggregated child execution states + // unless the parent suite execution is already completed. + // + // The boolean indicates whether the parent is in a terminal state. + // Returns ErrNotFound if the parent does not exist. + GetTestSuiteExecutionStates( + ctx context.Context, + testSuiteExecutionID string, + ) ([]TestSuiteExecutionState, bool, error) + SetRunning(ctx context.Context, params *SetRunningParams) error SetCompleted(ctx context.Context, params *SetCompletedParams) error - GetStatus(ctx context.Context, id string) (string, error) + GetStatus(ctx context.Context, id string) (ExecutionStatus, error) } type TestSuiteExecutionRepository interface { EntityRepository[TestSuiteExecution] SetRunning(ctx context.Context, params *SetRunningParams) error SetCompleted(ctx context.Context, params *SetCompletedParams) error - GetStatus(ctx context.Context, id string) (string, error) + GetStatus(ctx context.Context, id string) (ExecutionStatus, error) } type ListParams struct { @@ -99,11 +120,11 @@ type Resource struct { } type TestExecution struct { - ID string `json:"id" yaml:"id"` - TestSuiteExecutionID string `json:"test_suite_execution_id" yaml:"testsuite_execution_id"` - StartedAt time.Time `json:"started_at" yaml:"started_at"` - FinishedAt time.Time `json:"finished_at,omitzero" yaml:"finished_at,omitzero"` - Status string `json:"status" yaml:"status"` + ID string `json:"id" yaml:"id"` + TestSuiteExecutionID string `json:"test_suite_execution_id" yaml:"testsuite_execution_id"` + StartedAt time.Time `json:"started_at" yaml:"started_at"` + FinishedAt time.Time `json:"finished_at,omitzero" yaml:"finished_at,omitzero"` + Status ExecutionStatus `json:"status" yaml:"status"` EnvironmentID string `json:"environment_id" yaml:"environment_id"` EnvironmentName string `json:"environment_name,omitempty" yaml:"environment_name,omitempty"` @@ -115,10 +136,10 @@ type TestExecution struct { } type TestSuiteExecution struct { - ID string `json:"id" yaml:"id"` - StartedAt time.Time `json:"started_at" yaml:"started_at"` - FinishedAt time.Time `json:"finished_at,omitzero" yaml:"finished_at,omitzero"` - Status string `json:"status" yaml:"status"` + ID string `json:"id" yaml:"id"` + StartedAt time.Time `json:"started_at" yaml:"started_at"` + FinishedAt time.Time `json:"finished_at,omitzero" yaml:"finished_at,omitzero"` + Status ExecutionStatus `json:"status" yaml:"status"` EnvironmentID string `json:"environment_id" yaml:"environment_id"` EnvironmentName string `json:"environment_name,omitempty" yaml:"environment_name,omitempty"` @@ -157,3 +178,13 @@ const ( PositionAfter Position = "after" PositionBefore Position = "before" ) + +type ExecutionStatus string + +const ( + ExecutionStatusScheduled ExecutionStatus = "scheduled" + ExecutionStatusRunning ExecutionStatus = "running" + ExecutionStatusPassed ExecutionStatus = "passed" + ExecutionStatusFailed ExecutionStatus = "failed" + ExecutionStatusError ExecutionStatus = "error" +) diff --git a/tests/call_store_limit_test.go b/tests/call_store_limit_test.go new file mode 100644 index 0000000..f5265e9 --- /dev/null +++ b/tests/call_store_limit_test.go @@ -0,0 +1,366 @@ +package tests + +import ( + "context" + "net" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" + "time" + + "github.com/e2engine/core/execute" + "github.com/e2engine/core/execute/address" + "github.com/e2engine/core/execute/call" + "github.com/e2engine/core/execute/runtime" + "github.com/e2engine/core/execute/runtime/config" + "github.com/e2engine/core/execute/runtime/router" + "github.com/e2engine/core/execute/runtime/service" + httpservice "github.com/e2engine/core/execute/runtime/service/http" + "github.com/e2engine/core/execute/worker" + grpcworker "github.com/e2engine/core/execute/worker/grpc" + httpworker "github.com/e2engine/core/execute/worker/http" + "github.com/e2engine/core/model" + "github.com/e2engine/core/pkg/errors" + "github.com/e2engine/core/pkg/log" +) + +func TestCallStoreLimitPropagation(t *testing.T) { + tests := []struct { + name string + maxCalls int + maxRecordedBytes int64 + wantRecordedCalls int + wantStatus model.ExecutionStatus + wantError bool + }{ + { + name: "below both limits", + maxCalls: 3, + maxRecordedBytes: 1 << 20, + wantRecordedCalls: 2, + wantStatus: model.ExecutionStatusPassed, + }, + { + name: "call count exactly at limit", + maxCalls: 2, + maxRecordedBytes: 1 << 20, + wantRecordedCalls: 2, + wantStatus: model.ExecutionStatusPassed, + }, + { + name: "call count exceeded", + maxCalls: 1, + maxRecordedBytes: 1 << 20, + wantRecordedCalls: 1, + wantStatus: model.ExecutionStatusError, + wantError: true, + }, + { + name: "recorded bytes exceeded", + maxCalls: 3, + maxRecordedBytes: 1, + wantRecordedCalls: 0, + wantStatus: model.ExecutionStatusError, + wantError: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ctx, cancel := context.WithTimeout( + context.Background(), + 10*time.Second, + ) + defer cancel() + + logger, err := log.NewSilentLogger() + if err != nil { + t.Fatalf("NewSilentLogger() error = %v", err) + } + + resolver, err := address.NewResolver(nil) + if err != nil { + t.Fatalf("NewResolver() error = %v", err) + } + + // The actual service behind E2Engine's HTTP router. + upstream := httptest.NewServer( + http.HandlerFunc( + func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + }, + ), + ) + defer upstream.Close() + + // Allocate a port for the environment router. + routerPort := reserveTCPPort(t) + + environment := model.Environment{ + Kind: model.ResourceKindEnvironment, + ID: "7398ab887149ec5aa583c564a659a0b0a933ef27bacb675b081a2a752d8a3896", + Name: "test-environment", + Version: "1.0.0", + Spec: model.EnvironmentSpec{ + Services: []model.ServiceSpec{ + { + ID: "service-1", + Kind: model.ServiceKindHTTP, + Mode: model.ServiceModeReal, + E2EnginePort: routerPort, + Target: upstream.URL, + }, + }, + }, + } + + runtimeCfg := &config.Config{ + E2EngineListenInterface: "127.0.0.1", + EnvironmentCleanupTimeout: 5 * time.Second, + } + + serviceProvider := service.NewProvider( + &config.ServiceConfig{ + RealHTTP: &httpservice.RealHTTPServiceConfig{ + ReadHeaderTimeout: 5 * time.Second, + IdleTimeout: 30 * time.Second, + MaxRequestHeaderBytes: 1 << 20, + }, + }, + logger, + resolver, + ) + + routerProvider := router.NewProvider( + &config.RouterConfig{ + HTTP: &config.HTTPRouterConfig{ + MaxRecordedBodySize: 1 << 20, + }, + GRPC: &config.GRPCRouterConfig{ + MaxMessageSize: 4 << 20, + }, + }, + ) + + storeFactory := call.NewStoreFactory( + &call.Config{ + MaxCalls: tt.maxCalls, + MaxRecordedBytes: tt.maxRecordedBytes, + }, + ) + + controller := runtime.NewEnvironmentController( + runtimeCfg, + logger, + serviceProvider, + routerProvider, + storeFactory, + ) + + const executionID = "execution-1" + + instance, created, err := controller.Acquire( + ctx, + executionID, + &environment, + ) + if err != nil { + t.Fatalf("Acquire() error = %v", err) + } + + if !created { + t.Fatal("expected a new environment instance") + } + + defer func() { + cleanupCtx, cleanupCancel := context.WithTimeout( + context.Background(), + 5*time.Second, + ) + defer cleanupCancel() + + if err := controller.ReleaseAll(cleanupCtx); err != nil { + t.Errorf("ReleaseAll() error = %v", err) + } + }() + + routerURL := "http://" + net.JoinHostPort( + "127.0.0.1", + strconv.Itoa(routerPort), + ) + + // The SUT makes two requests through the environment + // router before responding to the worker. + sut := httptest.NewServer( + http.HandlerFunc( + func(w http.ResponseWriter, r *http.Request) { + for range 2 { + req, err := http.NewRequestWithContext( + r.Context(), + http.MethodGet, + routerURL+"/downstream", + nil, + ) + if err != nil { + t.Errorf("NewRequestWithContext() error = %v", err) + w.WriteHeader(http.StatusInternalServerError) + return + } + + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Errorf("downstream request error = %v", err) + w.WriteHeader(http.StatusBadGateway) + return + } + + _ = resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Errorf( + "downstream status = %d, want %d", + resp.StatusCode, + http.StatusOK, + ) + + w.WriteHeader(http.StatusBadGateway) + return + } + } + + w.WriteHeader(http.StatusOK) + }, + ), + ) + defer sut.Close() + + test := model.Test{ + Kind: model.ResourceKindTest, + ID: "ae619f9418f89041a5f6e0e952eae9fb9495e2c271b66739ffd6fae46f9ff30a", + Name: "test-1", + Version: "1.0.0", + Spec: model.TestSpec{ + Request: model.RequestSpec{ + HTTP: &model.HTTPRequest{ + Method: http.MethodGet, + URL: sut.URL + "/execute", + }, + }, + Expect: model.ExpectSpec{ + HTTP: &model.HTTPResponsePattern{ + StatusCode: http.StatusOK, + }, + }, + }, + } + + testWorker := worker.NewWorker( + &worker.Config{ + TestTimeout: 5 * time.Second, + HTTPEvaluator: &httpworker.EvaluatorConfig{ + MaxResponseBodySize: 1 << 20, + }, + GRPCExecutor: &grpcworker.ExecutorConfig{ + MaxMessageSize: 4 << 20, + }, + }, + logger, + serviceProvider.GetGRPCMethodResolver(), + resolver, + ) + + job := execute.TestJob{ + ExecutionID: executionID, + Environment: environment, + Test: test, + Runtime: execute.TestExecutionRuntime{ + Calls: instance.Calls, + }, + } + + result, err := testWorker.Execute(ctx, job) + if err != nil { + t.Fatalf("Worker.Execute() error = %v", err) + } + + if result == nil { + t.Fatal("expected execution result") + } + + if result.Status != tt.wantStatus { + t.Errorf( + "execution status = %q, want %q", + result.Status, + tt.wantStatus, + ) + } + + if result.Summary == nil { + t.Fatal("expected execution summary") + } + + if tt.wantError { + if !strings.Contains( + result.Summary.Error, + errors.ErrCallStoreLimitExceeded.Error(), + ) { + t.Errorf( + "execution error = %q, want call store limit error", + result.Summary.Error, + ) + } + } else { + if result.Summary.Error != "" { + t.Errorf( + "unexpected execution error = %q", + result.Summary.Error, + ) + } + } + + if got := len(instance.Calls.Get(call.Filter{})); got != tt.wantRecordedCalls { + t.Errorf( + "recorded calls = %d, want %d", + got, + tt.wantRecordedCalls, + ) + } + + if tt.wantError { + if err := instance.Calls.Err(); err != errors.ErrCallStoreLimitExceeded { + t.Errorf( + "call store error = %v, want %v", + err, + errors.ErrCallStoreLimitExceeded, + ) + } + } else { + if err := instance.Calls.Err(); err != nil { + t.Errorf( + "unexpected call store error = %v", + err, + ) + } + } + }) + } +} + +func reserveTCPPort(t *testing.T) int { + t.Helper() + + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("Listen() error = %v", err) + } + + port := listener.Addr().(*net.TCPAddr).Port + + if err := listener.Close(); err != nil { + t.Fatalf("Close() error = %v", err) + } + + return port +} diff --git a/tests/environment_test.go b/tests/environment_test.go index 402b2c3..42f907d 100644 --- a/tests/environment_test.go +++ b/tests/environment_test.go @@ -470,11 +470,11 @@ func validEnvironmentSpec() model.EnvironmentSpec { return model.EnvironmentSpec{ Services: []model.ServiceSpec{ { - ID: "api", - Kind: model.ServiceKindHTTP, - Mode: model.ServiceModeReal, - Address: "api:8080", - HTTPTarget: "http://localhost:8080", + ID: "api", + Kind: model.ServiceKindHTTP, + Mode: model.ServiceModeReal, + E2EnginePort: 8080, + Target: "http://localhost:8080", }, }, } diff --git a/tests/testexecution_test.go b/tests/testexecution_test.go index e261dab..3bcda45 100644 --- a/tests/testexecution_test.go +++ b/tests/testexecution_test.go @@ -395,7 +395,7 @@ func repositoryTestExecution() *repository.TestExecution { ID: "execution-001", StartedAt: startedAt, FinishedAt: finishedAt, - Status: string(model.ExecutionStatusPassed), + Status: repository.ExecutionStatusPassed, EnvironmentID: "environment-001", EnvironmentName: "local", TestID: "test-001", diff --git a/tests/testsuiteexecution_test.go b/tests/testsuiteexecution_test.go index 66f6ba2..471dfd8 100644 --- a/tests/testsuiteexecution_test.go +++ b/tests/testsuiteexecution_test.go @@ -460,7 +460,7 @@ func repositoryTestSuiteExecution() *repository.TestSuiteExecution { ID: "suite-execution-001", StartedAt: startedAt, FinishedAt: finishedAt, - Status: string(model.ExecutionStatusPassed), + Status: repository.ExecutionStatusPassed, EnvironmentID: "environment-001", EnvironmentName: "local", TestSuiteID: "testsuite-001", @@ -488,7 +488,7 @@ func repositorySuiteChildTestExecution() *repository.TestExecution { TestSuiteExecutionID: "suite-execution-001", StartedAt: startedAt, FinishedAt: finishedAt, - Status: string(model.ExecutionStatusPassed), + Status: repository.ExecutionStatusPassed, EnvironmentID: "environment-001", EnvironmentName: "local", TestID: "test-001", diff --git a/tools/go.mod b/tools/go.mod index ea2320a..0ae7a0e 100644 --- a/tools/go.mod +++ b/tools/go.mod @@ -5,6 +5,7 @@ go 1.27 require ( github.com/golangci/golangci-lint/v2 v2.14.0 go.uber.org/mock v0.6.0 + golang.org/x/vuln v1.9.0 ) require ( @@ -206,11 +207,12 @@ require ( go.uber.org/zap v1.27.0 // indirect go.yaml.in/yaml/v3 v3.0.5 // indirect golang.org/x/exp/typeparams v0.0.0-20260811152304-ee035b5b010f // indirect - golang.org/x/mod v0.41.0 // indirect - golang.org/x/sync v0.23.0 // indirect - golang.org/x/sys v0.48.0 // indirect + golang.org/x/mod v0.42.0 // indirect + golang.org/x/sync v0.24.0 // indirect + golang.org/x/sys v0.49.0 // indirect + golang.org/x/telemetry v0.0.0-20261010193011-f71dc92da45e // indirect golang.org/x/text v0.41.0 // indirect - golang.org/x/tools v0.50.0 // indirect + golang.org/x/tools v0.52.0 // indirect google.golang.org/protobuf v1.36.12 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect diff --git a/tools/go.sum b/tools/go.sum index f58cb33..ebc81a7 100644 --- a/tools/go.sum +++ b/tools/go.sum @@ -299,6 +299,8 @@ github.com/golangci/unconvert v0.0.0-20250410112200-a129a6e6413e h1:gD6P7NEo7Eqt github.com/golangci/unconvert v0.0.0-20250410112200-a129a6e6413e/go.mod h1:h+wZwLjUTJnm/P2rwlbJdRPZXOzaT36/FwnPnY2inzc= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/go-cmdtest v0.4.1-0.20220921163831-55ab3332a786 h1:rcv+Ippz6RAtvaGgKxc+8FQIpxHgsF+HBzPyYL2cyVU= +github.com/google/go-cmdtest v0.4.1-0.20220921163831-55ab3332a786/go.mod h1:apVn/GCasLZUVpAJ6oWAuyP7Ne7CEsQbTnc0plM3m+o= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= @@ -324,6 +326,7 @@ github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hf github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo= github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk= +github.com/google/renameio v0.1.0 h1:GOZbcHa3HfsPKPlmyPyN2KEohoMXOhdMbHrvbpl2QaA= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= @@ -690,8 +693,8 @@ golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c= -golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o= +golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg= +golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -726,8 +729,8 @@ golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qx golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues= -golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= +golang.org/x/net v0.61.0 h1:RR+6j/BTBCrggOLugxa+66R8FvoN6MHlzDlZIbN9YFw= +golang.org/x/net v0.61.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -747,8 +750,8 @@ golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= -golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= +golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -792,8 +795,10 @@ golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= -golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/telemetry v0.0.0-20261010193011-f71dc92da45e h1:P6NGsugec4oASJ+yKMNgTndeo0h2CbixZLvQIe9h5R4= +golang.org/x/telemetry v0.0.0-20261010193011-f71dc92da45e/go.mod h1:GNu+nb+E5axfGmP+Uu3ZVQu5lE/Xk42MjZOHWUD94/o= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= @@ -857,12 +862,14 @@ golang.org/x/tools v0.1.1-0.20210302220138-2ac05c832e1a/go.mod h1:9bzcO0MWcOuT0t golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/tools v0.50.0 h1:c2ifzfcuY7L90lZ2aKd8S4K2NpASF08SZx9ZuJkHmSU= -golang.org/x/tools v0.50.0/go.mod h1:7ulVMw3831Mwi5EZD6RomGyffr4VFjuNYXf2BbCEAV0= +golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs= +golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs= golang.org/x/tools/go/expect v0.1.1-deprecated h1:jpBZDwmgPhXsKZC6WhL20P4b/wmnpsEAGHaNy0n/rJM= golang.org/x/tools/go/expect v0.1.1-deprecated/go.mod h1:eihoPOH+FgIqa3FpoTwguz/bVUSGBlGQU67vpBeOrBY= golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated h1:1h2MnaIAIXISqTFKdENegdpAgUXz6NrPEsbIeWaBRvM= golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated/go.mod h1:RVAQXBGNv1ib0J382/DPCRS/BPnsGebyM1Gj5VSDpG8= +golang.org/x/vuln v1.9.0 h1:12VaqnI9kJfqwRoPptxoqsUhQtdfrSbdksT7X/KY/sc= +golang.org/x/vuln v1.9.0/go.mod h1:E/Frwm0xp49fTyBW+6CQHdkvobknbwUM49yEpMGUauw= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/tools/tools.go b/tools/tools.go index 5bf83cf..2b8f58d 100644 --- a/tools/tools.go +++ b/tools/tools.go @@ -8,4 +8,5 @@ package tools import ( _ "github.com/golangci/golangci-lint/v2/cmd/golangci-lint" _ "go.uber.org/mock/mockgen" + _ "golang.org/x/vuln/cmd/govulncheck" ) diff --git a/tools/tools.mk b/tools/tools.mk index 6a40451..04c10e1 100644 --- a/tools/tools.mk +++ b/tools/tools.mk @@ -10,12 +10,15 @@ ARCH := $(shell uname -m) GOLANGCI_LINT_VERSION ?= $(shell go -C $(TOOLS_DIR) list -m -f '{{.Version}}' github.com/golangci/golangci-lint/v2) MOCKGEN_VERSION ?= $(shell go -C $(TOOLS_DIR) list -m -f '{{.Version}}' go.uber.org/mock) +GOVULNCHECK_VERSION ?= $(shell go -C $(TOOLS_DIR) list -m -f '{{.Version}}' golang.org/x/vuln) GOLANGCI_LINT := $(BIN_DIR)/golangci-lint-$(OS)-$(ARCH)-$(GOLANGCI_LINT_VERSION) MOCKGEN := $(BIN_DIR)/mockgen-$(OS)-$(ARCH)-$(MOCKGEN_VERSION) +GOVULNCHECK := $(BIN_DIR)/govulncheck-$(OS)-$(ARCH)-$(GOVULNCHECK_VERSION) GOLANGCI_LINT_LINK := $(BIN_DIR)/golangci-lint MOCKGEN_LINK := $(BIN_DIR)/mockgen +GOVULNCHECK_LINK := $(BIN_DIR)/govulncheck $(GOLANGCI_LINT): $(call go-install-tool,$@,github.com/golangci/golangci-lint/v2/cmd/golangci-lint,$(GOLANGCI_LINT_VERSION)) @@ -23,6 +26,9 @@ $(GOLANGCI_LINT): $(MOCKGEN): $(call go-install-tool,$@,go.uber.org/mock/mockgen,$(MOCKGEN_VERSION)) +$(GOVULNCHECK): + $(call go-install-tool,$@,golang.org/x/vuln/cmd/govulncheck,$(GOVULNCHECK_VERSION)) + .PHONY: $(GOLANGCI_LINT_LINK) $(GOLANGCI_LINT_LINK): $(GOLANGCI_LINT) $(call create-symlink,$(GOLANGCI_LINT),$(GOLANGCI_LINT_LINK)) @@ -31,7 +37,11 @@ $(GOLANGCI_LINT_LINK): $(GOLANGCI_LINT) $(MOCKGEN_LINK): $(MOCKGEN) $(call create-symlink,$(MOCKGEN),$(MOCKGEN_LINK)) -TOOLS := install-golangci-lint install-mockgen +.PHONY: $(GOVULNCHECK_LINK) +$(GOVULNCHECK_LINK): $(GOVULNCHECK) + $(call create-symlink,$(GOVULNCHECK),$(GOVULNCHECK_LINK)) + +TOOLS := install-golangci-lint install-mockgen install-govulncheck .PHONY: install-tools install-tools: $(TOOLS) @@ -42,6 +52,9 @@ install-golangci-lint: $(GOLANGCI_LINT) $(GOLANGCI_LINT_LINK) .PHONY: install-mockgen install-mockgen: $(MOCKGEN) $(MOCKGEN_LINK) +.PHONY: install-govulncheck +install-govulncheck: $(GOVULNCHECK) $(GOVULNCHECK_LINK) + .PHONY: clean-tools clean-tools: rm -rf $(BIN_DIR)/* diff --git a/transport/config.go b/transport/config.go index 6d05b64..4ff4a3d 100644 --- a/transport/config.go +++ b/transport/config.go @@ -1,6 +1,9 @@ package transport import ( + "net" + "time" + "github.com/ygrebnov/errorc" "github.com/e2engine/core/pkg/keys" @@ -9,20 +12,70 @@ import ( type Config struct { Kind Kind `json:"kind" yaml:"kind" default:"direct" validate:"oneof(direct,socket)"` Address string `json:"address,omitempty" yaml:"address,omitempty" validate:"omitempty,networkaddress"` + + Socket *SocketConfig `json:"socket,omitempty" yaml:"socket,omitempty" default:"dive" validateElem:"omitempty,dive"` } func (c *Config) Validate() error { - if c.Kind == KindSocket && c.Address == "" { - return errorc.With( - ErrInvalidConfig, - errorc.String(keys.Validation, "transport address must be provided for socket transport"), - ) - } + switch c.Kind { + case KindDirect: + if c.Address != "" { + return errorc.With( + ErrInvalidConfig, + errorc.String( + keys.Validation, + "transport address is not allowed for direct transport", + ), + ) + } + + case KindSocket: + if c.Address == "" { + return errorc.With( + ErrInvalidConfig, + errorc.String( + keys.Validation, + "transport address must be provided for socket transport", + ), + ) + } - if c.Kind == KindDirect && c.Address != "" { + if c.Socket == nil { + return errorc.With( + ErrInvalidConfig, + errorc.String( + keys.Validation, + "socket configuration must be provided for socket transport", + ), + ) + } + + host, _, err := net.SplitHostPort(c.Address) + if err != nil { + return errorc.With( + ErrInvalidConfig, + errorc.String( + keys.Validation, + "invalid socket transport address", + ), + ) + } + + ip := net.ParseIP(host) + if ip == nil || !ip.IsLoopback() { + return errorc.With( + ErrInvalidConfig, + errorc.String( + keys.Validation, + "socket transport address must use a loopback IP", + ), + ) + } + + default: return errorc.With( ErrInvalidConfig, - errorc.String(keys.Validation, "transport address is not allowed for direct transport"), + errorc.String(keys.Validation, "invalid transport kind"), ) } @@ -35,3 +88,10 @@ const ( KindDirect Kind = "direct" KindSocket Kind = "socket" ) + +type SocketConfig struct { + MaxMessageSize int64 `json:"max_message_size" yaml:"max_message_size" env:"MAX_MESSAGE_SIZE" default:"67108864" validate:"min(1024),max(268435456)"` + + ReadTimeout time.Duration `json:"read_timeout" yaml:"read_timeout" env:"READ_TIMEOUT" default:"30s" validate:"min(1s)"` + WriteTimeout time.Duration `json:"write_timeout" yaml:"write_timeout" env:"WRITE_TIMEOUT" default:"30s" validate:"min(1s)"` +} diff --git a/transport/socket/errors.go b/transport/socket/errors.go index c4fc4aa..3017fa3 100644 --- a/transport/socket/errors.go +++ b/transport/socket/errors.go @@ -3,11 +3,13 @@ package socket import "github.com/ygrebnov/errorc" var ( - ErrCannotListen = errorc.New("cannot listen") - ErrCannotAccept = errorc.New("cannot accept connection") - ErrCannotConnect = errorc.New("cannot connect") - ErrCannotSetReadDeadline = errorc.New("cannot set read deadline") - ErrCannotSetWriteDeadline = errorc.New("cannot set write deadline") - ErrCannotReceiveMessage = errorc.New("cannot receive message") - ErrCannotSendMessage = errorc.New("cannot send message") + ErrCannotListen = errorc.New("cannot listen") + ErrCannotAccept = errorc.New("cannot accept connection") + ErrCannotConnect = errorc.New("cannot connect") + ErrCannotSetReadDeadline = errorc.New("cannot set read deadline") + ErrCannotSetWriteDeadline = errorc.New("cannot set write deadline") + ErrCannotReceiveMessage = errorc.New("cannot receive message") + ErrCannotSendMessage = errorc.New("cannot send message") + ErrMessageSizeLimitExceeded = errorc.New("socket message exceeds maximum size") + ErrInvalidListenAddress = errorc.New("invalid listen address") ) diff --git a/transport/socket/receiver.go b/transport/socket/receiver.go index 2606be3..3780af4 100644 --- a/transport/socket/receiver.go +++ b/transport/socket/receiver.go @@ -3,9 +3,9 @@ package socket import ( "context" "encoding/json" - "errors" "io" "net" + "time" "github.com/ygrebnov/errorc" @@ -14,12 +14,18 @@ import ( ) type Receiver struct { + cfg *transport.SocketConfig address string listener net.Listener } -func NewReceiver(address string) *Receiver { +func NewReceiver( + cfg *transport.SocketConfig, + address string, +) *Receiver { + // TODO: address local peer authentication return &Receiver{ + cfg: cfg, address: address, } } @@ -38,64 +44,137 @@ func (t *Receiver) Listen() error { errorc.Error(keys.Cause, err), ) } - t.listener = listener - return nil } func (t *Receiver) Receive( ctx context.Context, ) (transport.Message, error) { + var zero transport.Message + + if err := ctx.Err(); err != nil { + return zero, err + } + + // Cancellation terminates the receiver by closing + // its listener and interrupting any blocked Accept(). + stopAccept := context.AfterFunc(ctx, func() { + _ = t.listener.Close() + }) + defer stopAccept() + for { - var message transport.Message + if err := ctx.Err(); err != nil { + return zero, err + } connection, err := t.listener.Accept() if err != nil { if ctx.Err() != nil { - return message, ctx.Err() + return zero, ctx.Err() } - return message, errorc.With( + return zero, errorc.With( ErrCannotAccept, errorc.String(keys.SocketAddress, t.address), errorc.Error(keys.Cause, err), ) } - if deadline, ok := ctx.Deadline(); ok { - if errSetDeadline := connection.SetReadDeadline(deadline); errSetDeadline != nil { - _ = connection.Close() - - return message, errorc.With( - ErrCannotSetReadDeadline, - errorc.String(keys.SocketAddress, t.address), - errorc.String(keys.SocketReadDeadline, deadline.String()), - errorc.Error(keys.Cause, errSetDeadline), - ) - } + message, empty, err := t.readMessage( + ctx, + connection, + ) + if err != nil { + return zero, err } - err = json.NewDecoder(connection).Decode(&message) - _ = connection.Close() - - if errors.Is(err, io.EOF) { + if empty { // Empty connection, e.g. readiness probe. continue } - if err != nil { - return message, errorc.With( - ErrCannotReceiveMessage, - errorc.String(keys.SocketAddress, t.address), - errorc.Error(keys.Cause, err), - ) - } - return message, nil } } +func (t *Receiver) readMessage( + ctx context.Context, + connection net.Conn, +) (transport.Message, bool, error) { + var message transport.Message + + defer connection.Close() + + deadline := time.Now().Add( + t.cfg.ReadTimeout, + ) + + if ctxDeadline, ok := ctx.Deadline(); ok && + ctxDeadline.Before(deadline) { + deadline = ctxDeadline + } + + if err := connection.SetReadDeadline(deadline); err != nil { + return message, false, errorc.With( + ErrCannotSetReadDeadline, + errorc.String(keys.SocketAddress, t.address), + errorc.String( + keys.SocketReadDeadline, + deadline.String(), + ), + errorc.Error(keys.Cause, err), + ) + } + + // Interrupt an active read on context cancellation. + stopRead := context.AfterFunc(ctx, func() { + _ = connection.Close() + }) + defer stopRead() + + // Read at most MaxMessageSize+1 bytes. + // The extra byte allows us to distinguish a message + // exactly at the limit from an oversized message. + data, err := io.ReadAll( + io.LimitReader( + connection, + t.cfg.MaxMessageSize+1, + ), + ) + + if ctx.Err() != nil { + return message, false, ctx.Err() + } + + if err != nil { + return message, false, errorc.With( + ErrCannotReceiveMessage, + errorc.String(keys.SocketAddress, t.address), + errorc.Error(keys.Cause, err), + ) + } + + if int64(len(data)) > t.cfg.MaxMessageSize { + return message, false, ErrMessageSizeLimitExceeded + } + + if len(data) == 0 { + return message, true, nil + } + + if errUnmarshal := json.Unmarshal(data, &message); errUnmarshal != nil { + return message, false, errorc.With( + ErrCannotReceiveMessage, + errorc.String(keys.SocketAddress, t.address), + errorc.Error(keys.Cause, errUnmarshal), + ) + } + + return message, false, nil +} + func (t *Receiver) Close() error { if t.listener == nil { return nil diff --git a/transport/socket/receiver_test.go b/transport/socket/receiver_test.go index 8aea316..951a6b1 100644 --- a/transport/socket/receiver_test.go +++ b/transport/socket/receiver_test.go @@ -13,7 +13,7 @@ import ( func TestReceiverReceive(t *testing.T) { ctx := t.Context() - receiver := NewReceiver("127.0.0.1:0") + receiver := newTestReceiver(t, "127.0.0.1:0") if err := receiver.Listen(); err != nil { t.Fatal(err) @@ -53,7 +53,7 @@ func TestReceiverReceive(t *testing.T) { func TestReceiverReceiveIgnoresEmptyConnection(t *testing.T) { ctx := t.Context() - receiver := NewReceiver("127.0.0.1:0") + receiver := newTestReceiver(t, "127.0.0.1:0") if err := receiver.Listen(); err != nil { t.Fatal(err) @@ -100,7 +100,7 @@ func TestReceiverReceiveIgnoresEmptyConnection(t *testing.T) { func TestReceiverReceiveInvalidJSON(t *testing.T) { ctx := t.Context() - receiver := NewReceiver("127.0.0.1:0") + receiver := newTestReceiver(t, "127.0.0.1:0") if err := receiver.Listen(); err != nil { t.Fatal(err) @@ -132,7 +132,7 @@ func TestReceiverReceiveInvalidJSON(t *testing.T) { } func TestReceiverReceiveCannotAccept(t *testing.T) { - receiver := NewReceiver("127.0.0.1:0") + receiver := newTestReceiver(t, "127.0.0.1:0") if err := receiver.Listen(); err != nil { t.Fatal(err) @@ -153,13 +153,15 @@ func TestReceiverReceiveCannotAccept(t *testing.T) { } func TestReceiverReceiveCancelledContext(t *testing.T) { - receiver := NewReceiver("127.0.0.1:0") + receiver := newTestReceiver(t, "127.0.0.1:0") if err := receiver.Listen(); err != nil { t.Fatal(err) } + defer receiver.Close() ctx, cancel := context.WithCancel(context.Background()) + defer cancel() errorsCh := make(chan error, 1) @@ -170,10 +172,6 @@ func TestReceiverReceiveCancelledContext(t *testing.T) { cancel() - if err := receiver.Close(); err != nil { - t.Fatal(err) - } - select { case err := <-errorsCh: if !errors.Is(err, context.Canceled) { @@ -188,3 +186,219 @@ func TestReceiverReceiveCancelledContext(t *testing.T) { t.Fatal("receiver did not stop after context cancellation") } } + +func TestReceiverReceiveMessageSizeLimit(t *testing.T) { + message := transport.NewEndMessage() + + data, err := json.Marshal(message) + if err != nil { + t.Fatal(err) + } + + // Match the sender's newline-terminated JSON format. + data = append(data, '\n') + + tests := []struct { + name string + limit int64 + wantError error + }{ + { + name: "exactly at limit", + limit: int64(len(data)), + }, + { + name: "exceeds limit", + limit: int64(len(data)) - 1, + wantError: ErrMessageSizeLimitExceeded, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + receiver := newTestReceiver(t, "127.0.0.1:0") + receiver.cfg.MaxMessageSize = tt.limit + + if err := receiver.Listen(); err != nil { + t.Fatal(err) + } + defer receiver.Close() + + conn, err := net.Dial( + "tcp", + receiver.listener.Addr().String(), + ) + if err != nil { + t.Fatal(err) + } + + if _, err := conn.Write(data); err != nil { + _ = conn.Close() + t.Fatal(err) + } + + if err := conn.Close(); err != nil { + t.Fatal(err) + } + + actual, err := receiver.Receive(t.Context()) + + if tt.wantError != nil { + if !errors.Is(err, tt.wantError) { + t.Fatalf( + "Receive() error = %v, want %v", + err, + tt.wantError, + ) + } + return + } + + if err != nil { + t.Fatalf("Receive() error = %v", err) + } + + if actual.Type != message.Type { + t.Errorf( + "message type = %q, want %q", + actual.Type, + message.Type, + ) + } + }) + } +} + +func TestReceiverReceiveCancelledDuringRead(t *testing.T) { + receiver := newTestReceiver(t, "127.0.0.1:0") + + if err := receiver.Listen(); err != nil { + t.Fatal(err) + } + defer receiver.Close() + + conn, err := net.Dial( + "tcp", + receiver.listener.Addr().String(), + ) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + + // Send an incomplete JSON message. + if _, err := conn.Write([]byte(`{"type":`)); err != nil { + t.Fatal(err) + } + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + errorsCh := make(chan error, 1) + + go func() { + _, err := receiver.Receive(ctx) + errorsCh <- err + }() + + cancel() + + select { + case err := <-errorsCh: + if !errors.Is(err, context.Canceled) { + t.Fatalf( + "Receive() error = %v, want context.Canceled", + err, + ) + } + + case <-time.After(2 * time.Second): + t.Fatal("Receive() did not stop after cancellation") + } +} + +func TestReceiverReceiveReadTimeout(t *testing.T) { + receiver := newTestReceiver(t, "127.0.0.1:0") + receiver.cfg.ReadTimeout = 50 * time.Millisecond + + if err := receiver.Listen(); err != nil { + t.Fatal(err) + } + defer receiver.Close() + + conn, err := net.Dial( + "tcp", + receiver.listener.Addr().String(), + ) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + + // The client sends incomplete JSON and keeps + // the connection open. + if _, err := conn.Write([]byte(`{"type":`)); err != nil { + t.Fatal(err) + } + + _, err = receiver.Receive(t.Context()) + + if !errors.Is(err, ErrCannotReceiveMessage) { + t.Fatalf( + "Receive() error = %v, want %v", + err, + ErrCannotReceiveMessage, + ) + } +} + +func TestReceiverReceiveTrailingData(t *testing.T) { + receiver := newTestReceiver(t, "127.0.0.1:0") + + if err := receiver.Listen(); err != nil { + t.Fatal(err) + } + defer receiver.Close() + + conn, err := net.Dial( + "tcp", + receiver.listener.Addr().String(), + ) + if err != nil { + t.Fatal(err) + } + + _, err = conn.Write( + []byte(`{"type":"end"} {"type":"end"}`), + ) + if err != nil { + _ = conn.Close() + t.Fatal(err) + } + + if err := conn.Close(); err != nil { + t.Fatal(err) + } + + _, err = receiver.Receive(t.Context()) + + if !errors.Is(err, ErrCannotReceiveMessage) { + t.Fatalf( + "Receive() error = %v, want %v", + err, + ErrCannotReceiveMessage, + ) + } +} + +func newTestReceiver(t *testing.T, address string) *Receiver { + t.Helper() + receiver := NewReceiver( + &transport.SocketConfig{ + MaxMessageSize: 1 << 20, + ReadTimeout: 5 * time.Second, + }, + address, + ) + return receiver +} diff --git a/transport/socket/sender.go b/transport/socket/sender.go index 0a95bc8..2336f18 100644 --- a/transport/socket/sender.go +++ b/transport/socket/sender.go @@ -1,9 +1,12 @@ package socket import ( + "bytes" "context" "encoding/json" + "io" "net" + "time" "github.com/ygrebnov/errorc" @@ -12,11 +15,16 @@ import ( ) type Sender struct { + cfg *transport.SocketConfig address string } -func NewSender(address string) *Sender { +func NewSender( + cfg *transport.SocketConfig, + address string, +) *Sender { return &Sender{ + cfg: cfg, address: address, } } @@ -25,6 +33,22 @@ func (s *Sender) Send( ctx context.Context, message transport.Message, ) error { + // Serialize before establishing the connection. + data, err := json.Marshal(message) + if err != nil { + return errorc.With( + ErrCannotSendMessage, + errorc.Error(keys.Cause, err), + ) + } + + // Account for the newline appended by json.Encoder.Encode. + if int64(len(data)) >= s.cfg.MaxMessageSize { + return ErrMessageSizeLimitExceeded + } + + data = append(data, '\n') + connection, err := (&net.Dialer{}).DialContext( ctx, "tcp", @@ -39,18 +63,38 @@ func (s *Sender) Send( } defer connection.Close() - if deadline, ok := ctx.Deadline(); ok { - if err := connection.SetWriteDeadline(deadline); err != nil { - return errorc.With( - ErrCannotSetWriteDeadline, - errorc.String(keys.SocketAddress, s.address), - errorc.String(keys.SocketWriteDeadline, deadline.String()), - errorc.Error(keys.Cause, err), - ) - } + // Apply an independent write timeout, respecting an + // earlier deadline supplied by the caller. + deadline := time.Now().Add(s.cfg.WriteTimeout) + + if ctxDeadline, ok := ctx.Deadline(); ok && + ctxDeadline.Before(deadline) { + deadline = ctxDeadline } - if err := json.NewEncoder(connection).Encode(message); err != nil { + if err := connection.SetWriteDeadline(deadline); err != nil { + return errorc.With( + ErrCannotSetWriteDeadline, + errorc.String(keys.SocketAddress, s.address), + errorc.String( + keys.SocketWriteDeadline, + deadline.String(), + ), + errorc.Error(keys.Cause, err), + ) + } + + // Context cancellation must interrupt an active write, + // even when the caller has no deadline. + stop := context.AfterFunc(ctx, func() { + _ = connection.Close() + }) + defer stop() + + if _, err := io.Copy( + connection, + bytes.NewReader(data), + ); err != nil { return errorc.With( ErrCannotSendMessage, errorc.String(keys.SocketAddress, s.address), diff --git a/transport/socket/sender_test.go b/transport/socket/sender_test.go index 70fcecf..9a25b87 100644 --- a/transport/socket/sender_test.go +++ b/transport/socket/sender_test.go @@ -6,6 +6,7 @@ import ( "errors" "net" "testing" + "time" "github.com/e2engine/core/transport" ) @@ -44,7 +45,10 @@ func TestSenderSend(t *testing.T) { received <- message }() - sender := NewSender(listener.Addr().String()) + sender := NewSender( + newTestSenderConfig(), + listener.Addr().String(), + ) if err := sender.Send(context.Background(), message); err != nil { t.Fatal(err) @@ -82,7 +86,10 @@ func TestSenderSendCannotConnect(t *testing.T) { t.Fatal(err) } - sender := NewSender(address) + sender := NewSender( + newTestSenderConfig(), + address, + ) err = sender.Send( context.Background(), @@ -97,7 +104,10 @@ func TestSenderSendCancelledContext(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() - sender := NewSender("127.0.0.1:1") + sender := NewSender( + newTestSenderConfig(), + "127.0.0.1:1", + ) err := sender.Send( ctx, @@ -111,3 +121,119 @@ func TestSenderSendCancelledContext(t *testing.T) { t.Fatalf("expected context to be canceled, got %v", ctx.Err()) } } + +func TestSenderSendMessageSizeLimit(t *testing.T) { + message := transport.NewEndMessage() + + data, err := json.Marshal(message) + if err != nil { + t.Fatal(err) + } + + tests := []struct { + name string + limit int64 + wantError error + }{ + { + name: "message exceeds limit", + limit: int64(len(data)), + wantError: ErrMessageSizeLimitExceeded, + }, + { + name: "message exactly at limit", + limit: int64(len(data)) + 1, + }, + { + name: "message below limit", + limit: int64(len(data)) + 2, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + listenerConfig := net.ListenConfig{} + + listener, err := listenerConfig.Listen( + t.Context(), + "tcp", + "127.0.0.1:0", + ) + if err != nil { + t.Fatal(err) + } + defer listener.Close() + + sender := NewSender( + &transport.SocketConfig{ + MaxMessageSize: tt.limit, + WriteTimeout: 5 * time.Second, + }, + listener.Addr().String(), + ) + + if tt.wantError != nil { + err := sender.Send(t.Context(), message) + + if !errors.Is(err, tt.wantError) { + t.Fatalf( + "Send() error = %v, want %v", + err, + tt.wantError, + ) + } + + return + } + + received := make(chan transport.Message, 1) + receiveErrors := make(chan error, 1) + + go func() { + connection, err := listener.Accept() + if err != nil { + receiveErrors <- err + return + } + defer connection.Close() + + var actual transport.Message + + if err := json.NewDecoder(connection).Decode(&actual); err != nil { + receiveErrors <- err + return + } + + received <- actual + }() + + if err := sender.Send(t.Context(), message); err != nil { + t.Fatalf("Send() error = %v", err) + } + + select { + case err := <-receiveErrors: + t.Fatal(err) + + case actual := <-received: + if actual.Type != message.Type { + t.Errorf( + "message type = %q, want %q", + actual.Type, + message.Type, + ) + } + + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for message") + } + }) + } +} + +func newTestSenderConfig() *transport.SocketConfig { + return &transport.SocketConfig{ + MaxMessageSize: 64 << 20, + WriteTimeout: 5 * time.Second, + } +} diff --git a/util/file.go b/util/file.go index 9a89d01..5b75972 100644 --- a/util/file.go +++ b/util/file.go @@ -3,6 +3,7 @@ package util import ( "io" "os" + "path/filepath" "github.com/ygrebnov/errorc" @@ -10,37 +11,47 @@ import ( "github.com/e2engine/core/pkg/keys" ) -// ValidateFilePath performs basic path validation. -// It is not a security boundary. -func ValidateFilePath(path string) error { - if path == "" { +// MaxFileSize limits files loaded into memory through this package. +const MaxFileSize int64 = 16 << 20 // 16 MiB + +// validateRegularFile checks the opened file rather than a separate path lookup. +func validateRegularFile(file *os.File, path string) error { + info, err := file.Stat() + if err != nil { return errorc.With( errors.ErrInaccessiblePath, errorc.String(keys.FilePath, path), + errorc.Error(keys.Cause, err), ) } - info, err := os.Stat(path) - if err != nil { + + if !info.Mode().IsRegular() { return errorc.With( errors.ErrInaccessiblePath, errorc.String(keys.FilePath, path), - errorc.Error(keys.Cause, err), + errorc.String(keys.Validation, "not a regular file"), ) } - if !info.Mode().IsRegular() { + if info.Size() > MaxFileSize { return errorc.With( errors.ErrInaccessiblePath, errorc.String(keys.FilePath, path), + errorc.String(keys.Validation, "file size exceeds maximum allowed"), ) } return nil } -// ReadFile opens, validates, and reads the same filesystem object. -func ReadFile(path string) ([]byte, error) { - file, err := os.Open(path) +func readOpenedFile(file *os.File, path string) ([]byte, error) { + if err := validateRegularFile(file, path); err != nil { + return nil, err + } + + data, err := io.ReadAll( + io.LimitReader(file, MaxFileSize+1), + ) if err != nil { return nil, errorc.With( errors.ErrInaccessiblePath, @@ -48,9 +59,42 @@ func ReadFile(path string) ([]byte, error) { errorc.Error(keys.Cause, err), ) } + + if int64(len(data)) > MaxFileSize { + return nil, errorc.With( + errors.ErrInaccessiblePath, + errorc.String(keys.FilePath, path), + errorc.String(keys.Validation, "file size exceeds maximum allowed"), + ) + } + + return data, nil +} + +// ValidateFilePath checks that path names an accessible, regular file +// of bounded size. +// +// It does not restrict the file to a particular directory. +func ValidateFilePath(path string) error { + file, err := os.Open(path) + if err != nil { + return errorc.With( + errors.ErrInaccessiblePath, + errorc.String(keys.FilePath, path), + errorc.Error(keys.Cause, err), + ) + } defer file.Close() - info, err := file.Stat() + return validateRegularFile(file, path) +} + +// ReadFile reads an accessible, regular file up to MaxFileSize. +// +// It is not a directory confinement boundary. +// Use ReadFileWithinRoot when directory confinement is required. +func ReadFile(path string) ([]byte, error) { + file, err := os.Open(path) if err != nil { return nil, errorc.With( errors.ErrInaccessiblePath, @@ -58,15 +102,35 @@ func ReadFile(path string) ([]byte, error) { errorc.Error(keys.Cause, err), ) } + defer file.Close() - if !info.Mode().IsRegular() { + return readOpenedFile(file, path) +} + +// ReadFileWithinRoot reads a file confined to root. +// +// The path must be relative to root. os.Root prevents traversal +// outside root through '..' or symlinks. +func ReadFileWithinRoot(root, path string) ([]byte, error) { + if filepath.IsAbs(path) || path == "" { return nil, errorc.With( errors.ErrInaccessiblePath, errorc.String(keys.FilePath, path), + errorc.String(keys.Validation, "path must be non-empty and relative to root"), ) } - data, err := io.ReadAll(file) + dir, err := os.OpenRoot(root) + if err != nil { + return nil, errorc.With( + errors.ErrInaccessiblePath, + errorc.String(keys.FilePath, root), + errorc.Error(keys.Cause, err), + ) + } + defer dir.Close() + + file, err := dir.Open(path) if err != nil { return nil, errorc.With( errors.ErrInaccessiblePath, @@ -74,8 +138,7 @@ func ReadFile(path string) ([]byte, error) { errorc.Error(keys.Cause, err), ) } + defer file.Close() - return data, nil + return readOpenedFile(file, path) } - -// TODO: add FilePolicy with MaxSize, AllowSymlinks etc. diff --git a/util/file_test.go b/util/file_test.go index c487fe3..132e05b 100644 --- a/util/file_test.go +++ b/util/file_test.go @@ -1,6 +1,7 @@ package util import ( + "bytes" "errors" "os" "path/filepath" @@ -26,6 +27,12 @@ func TestValidateFilePath(t *testing.T) { "missing.txt", ) + exactSize := filepath.Join(tempDir, "exact.txt") + writeSizedTestFile(t, exactSize, MaxFileSize) + + oversized := filepath.Join(tempDir, "oversized.txt") + writeSizedTestFile(t, oversized, MaxFileSize+1) + tests := []struct { name string path string @@ -51,6 +58,15 @@ func TestValidateFilePath(t *testing.T) { name: "regular file", path: filePath, }, + { + name: "exact size limit", + path: exactSize, + }, + { + name: "oversized file", + path: oversized, + expectedError: coreerrors.ErrInaccessiblePath, + }, } for _, tt := range tests { @@ -78,3 +94,276 @@ func TestValidateFilePath(t *testing.T) { }) } } + +func TestReadFile(t *testing.T) { + dir := t.TempDir() + + regular := filepath.Join(dir, "file.txt") + writeTestFile(t, regular, []byte("hello")) + + empty := filepath.Join(dir, "empty.txt") + writeTestFile(t, empty, nil) + + exact := filepath.Join(dir, "exact.txt") + writeSizedTestFile(t, exact, MaxFileSize) + + oversized := filepath.Join(dir, "oversized.txt") + writeSizedTestFile(t, oversized, MaxFileSize+1) + + tests := []struct { + name string + path string + expected []byte + expectedSize int + expectedError error + }{ + { + name: "regular file", + path: regular, + expected: []byte("hello"), + }, + { + name: "empty file", + path: empty, + }, + { + name: "exact size limit", + path: exact, + expectedSize: int(MaxFileSize), + }, + { + name: "oversized file", + path: oversized, + expectedError: coreerrors.ErrInaccessiblePath, + }, + { + name: "directory", + path: dir, + expectedError: coreerrors.ErrInaccessiblePath, + }, + { + name: "missing file", + path: filepath.Join(dir, "missing.txt"), + expectedError: coreerrors.ErrInaccessiblePath, + }, + { + name: "empty path", + path: "", + expectedError: coreerrors.ErrInaccessiblePath, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + actual, err := ReadFile(tt.path) + + if !errors.Is(err, tt.expectedError) { + t.Fatalf( + "expected error %v, got %v", + tt.expectedError, + err, + ) + } + + if tt.expectedError != nil { + if actual != nil { + t.Fatalf( + "expected nil data on error, got %d bytes", + len(actual), + ) + } + return + } + + if tt.expectedSize != 0 { + if len(actual) != tt.expectedSize { + t.Fatalf( + "expected %d bytes, got %d", + tt.expectedSize, + len(actual), + ) + } + } else if !bytes.Equal(actual, tt.expected) { + t.Fatalf( + "expected %q, got %q", + tt.expected, + actual, + ) + } + }) + } +} + +func TestReadFileWithinRoot(t *testing.T) { + parent := t.TempDir() + root := filepath.Join(parent, "allowed") + + if err := os.MkdirAll( + filepath.Join(root, "nested"), + 0o700, + ); err != nil { + t.Fatal(err) + } + + writeTestFile( + t, + filepath.Join(root, "nested", "file.txt"), + []byte("inside"), + ) + + writeTestFile( + t, + filepath.Join(parent, "outside.txt"), + []byte("outside"), + ) + + writeSizedTestFile( + t, + filepath.Join(root, "oversized.txt"), + MaxFileSize+1, + ) + + if err := os.Symlink( + "nested/file.txt", + filepath.Join(root, "inside-link"), + ); err != nil { + t.Fatal(err) + } + + if err := os.Symlink( + "../outside.txt", + filepath.Join(root, "outside-link"), + ); err != nil { + t.Fatal(err) + } + + tests := []struct { + name string + root string + path string + expected []byte + expectedError error + }{ + { + name: "nested file", + root: root, + path: "nested/file.txt", + expected: []byte("inside"), + }, + { + name: "internal symlink", + root: root, + path: "inside-link", + expected: []byte("inside"), + }, + { + name: "parent traversal", + root: root, + path: "../outside.txt", + expectedError: coreerrors.ErrInaccessiblePath, + }, + { + name: "escaping symlink", + root: root, + path: "outside-link", + expectedError: coreerrors.ErrInaccessiblePath, + }, + { + name: "absolute path", + root: root, + path: filepath.Join(root, "nested", "file.txt"), + expectedError: coreerrors.ErrInaccessiblePath, + }, + { + name: "empty path", + root: root, + path: "", + expectedError: coreerrors.ErrInaccessiblePath, + }, + { + name: "directory", + root: root, + path: "nested", + expectedError: coreerrors.ErrInaccessiblePath, + }, + { + name: "missing file", + root: root, + path: "missing.txt", + expectedError: coreerrors.ErrInaccessiblePath, + }, + { + name: "oversized file", + root: root, + path: "oversized.txt", + expectedError: coreerrors.ErrInaccessiblePath, + }, + { + name: "missing root", + root: filepath.Join(parent, "missing-root"), + path: "file.txt", + expectedError: coreerrors.ErrInaccessiblePath, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + actual, err := ReadFileWithinRoot( + tt.root, + tt.path, + ) + + if !errors.Is(err, tt.expectedError) { + t.Fatalf( + "expected error %v, got %v", + tt.expectedError, + err, + ) + } + + if tt.expectedError != nil { + if actual != nil { + t.Fatalf( + "expected nil data on error, got %d bytes", + len(actual), + ) + } + return + } + + if !bytes.Equal(actual, tt.expected) { + t.Fatalf( + "expected %q, got %q", + tt.expected, + actual, + ) + } + }) + } +} + +func writeTestFile(t *testing.T, path string, data []byte) { + t.Helper() + + if err := os.WriteFile(path, data, 0o600); err != nil { + t.Fatalf("write %s: %v", path, err) + } +} + +func writeSizedTestFile(t *testing.T, path string, size int64) { + t.Helper() + + file, err := os.Create(path) + if err != nil { + t.Fatal(err) + } + + if err := file.Truncate(size); err != nil { + _ = file.Close() + t.Fatal(err) + } + + if err := file.Close(); err != nil { + t.Fatal(err) + } +}