From 055ee168f22da602cb2cafaf924899f816f984cb Mon Sep 17 00:00:00 2001 From: Shawn Burke Date: Wed, 2 Dec 2026 07:29:39 +0000 Subject: [PATCH 1/2] Remove snyk-broker; the gRPC tunnel is the only relay transport The agent now always relays through the gRPC tunnel. - Remove the snyk-broker package: supervisor, relay instance manager, reflector, WebSocket proxy, event tracker and watchdog. - Remove the relay mode switch at startup: relaymode, the registration-driven restart, ForcedRelayMode, and the AXON_RELAY_TRANSPORT / RELAY_MODE, ENABLE_RELAY_REFLECTOR, REFLECTOR_WEBSOCKET_UPGRADE, RELAY_IDLE_TIMEOUT and SNYK_BROKER_PORT settings. - Move agent/server/snykbroker/acceptfile to agent/server/acceptfile, with accept_files/ and plugins/ as children. - Move Registration into grpctunnel, which is its only user. - Build one go-only image: no Node, no snyk-broker, no VARIANT. Stop publishing the -grpc tags. - Run the relay E2E suite (formerly relay_test.grpc.sh) as relay-test. - /__axon/info keeps relay_mode, now always "grpc-tunnel". Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 82 +- .github/workflows/docker-image.yml | 45 +- .github/workflows/docker.yml | 61 +- .github/workflows/trivy.yml | 12 - .github/workflows/tunnel-load-test.yml | 4 +- .github/workflows/validate-filters.yml | 2 +- .vscode/launch.json | 5 +- AGENTS.md | 4 - Makefile | 10 +- README.md | 1 - README.relay.md | 86 +- agent/.gitignore | 1 - agent/Makefile | 29 +- agent/cmd/http_client.go | 4 +- agent/cmd/http_client_test.go | 3 +- agent/cmd/relay.go | 11 +- agent/cmd/relay_mode.go | 94 -- agent/cmd/relay_mode_test.go | 44 - agent/cmd/serve.go | 11 +- agent/cmd/serve_test.go | 16 +- agent/cmd/stack.go | 6 - agent/common/integration.go | 4 +- agent/common/integration_test.go | 4 +- agent/config/config.go | 152 +-- agent/config/config_test.go | 55 -- agent/go.mod | 1 - agent/go.sum | 2 - .../acceptfile/accept_file.go | 34 +- .../acceptfile/accept_file_gitlab_test.go | 2 +- .../acceptfile/accept_file_test.go | 28 - .../accept_files/accept.bitbucket.basic.json | 0 .../accept_files/accept.bitbucket.json | 0 .../accept_files/accept.github.app.json | 0 .../accept_files/accept.github.json | 0 .../accept_files/accept.gitlab.json | 0 .../accept_files/accept.google.json | 0 .../accept_files/accept.harness.json | 0 .../accept_files/accept.jira.bearer.json | 0 .../accept_files/accept.jira.json | 0 .../accept_files/accept.prometheus.json | 0 .../accept_files/accept.sonarqube.json | 0 .../accept_files/config.bitbucket.json | 0 .../accept_files/config.github.json | 0 .../accept_files/config.gitlab.json | 0 .../accept_files/config.harness.json | 0 .../accept_files/config.jira.json | 0 .../acceptfile/accept_google_test.go | 7 +- .../{snykbroker => }/acceptfile/auth.go | 0 .../{snykbroker => }/acceptfile/headers.go | 0 .../acceptfile/helpers_test.go | 0 .../{snykbroker => }/acceptfile/matcher.go | 15 +- .../acceptfile/matcher_parity_test.go | 6 +- .../acceptfile/matcher_test.go | 0 .../{snykbroker => }/acceptfile/origin.go | 0 .../acceptfile/origin_test.go | 7 +- .../{snykbroker => }/acceptfile/plugin.go | 0 .../{snykbroker => }/acceptfile/plugin.sh | 0 .../acceptfile/plugin_fail.sh | 0 .../acceptfile/plugin_test.go | 0 .../plugins/github-app-scaffolder | 0 .../plugins/github-app-token | 0 .../{snykbroker => }/acceptfile/pool.go | 0 .../{snykbroker => }/acceptfile/pool_test.go | 0 .../acceptfile/render_golden_test.go | 8 +- .../{snykbroker => }/acceptfile/resolver.go | 0 .../{snykbroker => }/acceptfile/router.go | 18 +- .../acceptfile/router_auth_test.go | 0 .../acceptfile/router_credential_test.go | 8 +- .../acceptfile/router_pool_test.go | 0 .../acceptfile/router_test.go | 0 .../acceptfile/router_wildcard_test.go | 2 +- .../{snykbroker => }/acceptfile/supported.go | 16 +- .../accept.bitbucket.basic.golden.json | 0 .../accept.bitbucket.golden.json | 0 .../accept.github.app.golden.json | 0 .../render_golden/accept.github.golden.json | 0 .../render_golden/accept.gitlab.golden.json | 0 .../render_golden/accept.harness.golden.json | 0 .../accept.jira.bearer.golden.json | 0 .../render_golden/accept.jira.golden.json | 0 .../accept.prometheus.golden.json | 0 .../accept.sonarqube.golden.json | 0 .../acceptfile/unsupported_test.go | 14 +- agent/server/grpctunnel/call_handler.go | 7 +- agent/server/grpctunnel/call_report_test.go | 2 +- agent/server/grpctunnel/conformance_test.go | 7 +- agent/server/grpctunnel/module.go | 3 +- agent/server/grpctunnel/proxy_dialer.go | 3 +- .../registration.go | 12 +- .../registration_test.go | 24 +- .../server/grpctunnel/response_header_test.go | 8 +- agent/server/grpctunnel/router.go | 2 +- agent/server/grpctunnel/router_test.go | 2 +- agent/server/grpctunnel/tunnel_client.go | 23 +- agent/server/grpctunnel/tunnel_client_test.go | 13 +- agent/server/http/axon_handler.go | 21 +- agent/server/http/axon_info_test.go | 42 - agent/server/http/http_server.go | 8 +- agent/server/http/http_server_idle_test.go | 16 +- agent/server/relaymode/relaymode.go | 128 --- agent/server/relaymode/relaymode_test.go | 161 --- .../acceptfile/origin_contract_test.go | 122 --- agent/server/snykbroker/event_tracker.go | 46 - agent/server/snykbroker/event_tracker_test.go | 65 -- agent/server/snykbroker/logger_test.go | 52 - agent/server/snykbroker/module.go | 21 - agent/server/snykbroker/origin.go | 157 --- agent/server/snykbroker/reflector.go | 694 ------------- .../reflector_accept_file_wiring_test.go | 160 --- .../snykbroker/reflector_boundary_test.go | 412 -------- .../reflector_dynamic_target_test.go | 517 ---------- .../reflector_failure_class_test.go | 88 -- .../snykbroker/reflector_google_live_test.go | 254 ----- .../reflector_headers_harness_test.go | 96 -- .../reflector_headers_simple_test.go | 232 ----- .../snykbroker/reflector_headers_test.go | 397 -------- agent/server/snykbroker/reflector_key_test.go | 136 --- agent/server/snykbroker/reflector_test.go | 766 --------------- .../snykbroker/relay_instance_manager.go | 924 ------------------ .../snykbroker/relay_instance_manager_test.go | 703 ------------- agent/server/snykbroker/supervisor.go | 388 -------- agent/server/snykbroker/supervisor_test.go | 109 --- agent/server/snykbroker/token_logging_test.go | 72 -- agent/server/snykbroker/watchdog.sh | 36 - agent/server/snykbroker/ws_proxy.go | 333 ------- agent/server/snykbroker/ws_proxy_test.go | 910 ----------------- agent/test/conformance/README.md | 37 +- agent/test/load/docker-compose.load.yml | 1 - .../test/relay/Dockerfile.snyk-broker-server | 24 - agent/test/relay/accept-server.json | 13 - .../relay/docker-compose.grpc.noproxy.yml | 12 - agent/test/relay/docker-compose.grpc.yml | 132 --- agent/test/relay/docker-compose.noproxy.yml | 2 +- agent/test/relay/docker-compose.proxy.yml | 17 - agent/test/relay/docker-compose.yml | 73 +- agent/test/relay/generate-certs.sh | 67 -- agent/test/relay/nginx-tls-proxy.conf | 42 - agent/test/relay/proxy.env | 1 - agent/test/relay/relay_scenarios.sh | 27 +- agent/test/relay/relay_test.grpc.sh | 250 ----- agent/test/relay/relay_test.sh | 256 ++--- agent/test/validate_filters.sh | 4 +- agent/util/proxyconnect.go | 5 +- docker/Dockerfile | 87 +- docs/design/grpc-tunnel-v2.md | 7 + examples/relay/helm-chart/README.md | 2 +- 146 files changed, 424 insertions(+), 9721 deletions(-) delete mode 100644 agent/cmd/relay_mode.go delete mode 100644 agent/cmd/relay_mode_test.go rename agent/server/{snykbroker => }/acceptfile/accept_file.go (90%) rename agent/server/{snykbroker => }/acceptfile/accept_file_gitlab_test.go (96%) rename agent/server/{snykbroker => }/acceptfile/accept_file_test.go (80%) rename agent/server/{snykbroker => acceptfile}/accept_files/accept.bitbucket.basic.json (100%) rename agent/server/{snykbroker => acceptfile}/accept_files/accept.bitbucket.json (100%) rename agent/server/{snykbroker => acceptfile}/accept_files/accept.github.app.json (100%) rename agent/server/{snykbroker => acceptfile}/accept_files/accept.github.json (100%) rename agent/server/{snykbroker => acceptfile}/accept_files/accept.gitlab.json (100%) rename agent/server/{snykbroker => acceptfile}/accept_files/accept.google.json (100%) rename agent/server/{snykbroker => acceptfile}/accept_files/accept.harness.json (100%) rename agent/server/{snykbroker => acceptfile}/accept_files/accept.jira.bearer.json (100%) rename agent/server/{snykbroker => acceptfile}/accept_files/accept.jira.json (100%) rename agent/server/{snykbroker => acceptfile}/accept_files/accept.prometheus.json (100%) rename agent/server/{snykbroker => acceptfile}/accept_files/accept.sonarqube.json (100%) rename agent/server/{snykbroker => acceptfile}/accept_files/config.bitbucket.json (100%) rename agent/server/{snykbroker => acceptfile}/accept_files/config.github.json (100%) rename agent/server/{snykbroker => acceptfile}/accept_files/config.gitlab.json (100%) rename agent/server/{snykbroker => acceptfile}/accept_files/config.harness.json (100%) rename agent/server/{snykbroker => acceptfile}/accept_files/config.jira.json (100%) rename agent/server/{snykbroker => }/acceptfile/accept_google_test.go (87%) rename agent/server/{snykbroker => }/acceptfile/auth.go (100%) rename agent/server/{snykbroker => }/acceptfile/headers.go (100%) rename agent/server/{snykbroker => }/acceptfile/helpers_test.go (100%) rename agent/server/{snykbroker => }/acceptfile/matcher.go (92%) rename agent/server/{snykbroker => }/acceptfile/matcher_parity_test.go (97%) rename agent/server/{snykbroker => }/acceptfile/matcher_test.go (100%) rename agent/server/{snykbroker => }/acceptfile/origin.go (100%) rename agent/server/{snykbroker => }/acceptfile/origin_test.go (94%) rename agent/server/{snykbroker => }/acceptfile/plugin.go (100%) rename agent/server/{snykbroker => }/acceptfile/plugin.sh (100%) rename agent/server/{snykbroker => }/acceptfile/plugin_fail.sh (100%) rename agent/server/{snykbroker => }/acceptfile/plugin_test.go (100%) rename agent/server/{snykbroker => acceptfile}/plugins/github-app-scaffolder (100%) rename agent/server/{snykbroker => acceptfile}/plugins/github-app-token (100%) rename agent/server/{snykbroker => }/acceptfile/pool.go (100%) rename agent/server/{snykbroker => }/acceptfile/pool_test.go (100%) rename agent/server/{snykbroker => }/acceptfile/render_golden_test.go (93%) rename agent/server/{snykbroker => }/acceptfile/resolver.go (100%) rename agent/server/{snykbroker => }/acceptfile/router.go (93%) rename agent/server/{snykbroker => }/acceptfile/router_auth_test.go (100%) rename agent/server/{snykbroker => }/acceptfile/router_credential_test.go (85%) rename agent/server/{snykbroker => }/acceptfile/router_pool_test.go (100%) rename agent/server/{snykbroker => }/acceptfile/router_test.go (100%) rename agent/server/{snykbroker => }/acceptfile/router_wildcard_test.go (99%) rename agent/server/{snykbroker => }/acceptfile/supported.go (84%) rename agent/server/{snykbroker => }/acceptfile/testdata/render_golden/accept.bitbucket.basic.golden.json (100%) rename agent/server/{snykbroker => }/acceptfile/testdata/render_golden/accept.bitbucket.golden.json (100%) rename agent/server/{snykbroker => }/acceptfile/testdata/render_golden/accept.github.app.golden.json (100%) rename agent/server/{snykbroker => }/acceptfile/testdata/render_golden/accept.github.golden.json (100%) rename agent/server/{snykbroker => }/acceptfile/testdata/render_golden/accept.gitlab.golden.json (100%) rename agent/server/{snykbroker => }/acceptfile/testdata/render_golden/accept.harness.golden.json (100%) rename agent/server/{snykbroker => }/acceptfile/testdata/render_golden/accept.jira.bearer.golden.json (100%) rename agent/server/{snykbroker => }/acceptfile/testdata/render_golden/accept.jira.golden.json (100%) rename agent/server/{snykbroker => }/acceptfile/testdata/render_golden/accept.prometheus.golden.json (100%) rename agent/server/{snykbroker => }/acceptfile/testdata/render_golden/accept.sonarqube.golden.json (100%) rename agent/server/{snykbroker => }/acceptfile/unsupported_test.go (96%) rename agent/server/{snykbroker => grpctunnel}/registration.go (92%) rename agent/server/{snykbroker => grpctunnel}/registration_test.go (89%) delete mode 100644 agent/server/relaymode/relaymode.go delete mode 100644 agent/server/relaymode/relaymode_test.go delete mode 100644 agent/server/snykbroker/acceptfile/origin_contract_test.go delete mode 100644 agent/server/snykbroker/event_tracker.go delete mode 100644 agent/server/snykbroker/event_tracker_test.go delete mode 100644 agent/server/snykbroker/logger_test.go delete mode 100644 agent/server/snykbroker/module.go delete mode 100644 agent/server/snykbroker/origin.go delete mode 100644 agent/server/snykbroker/reflector.go delete mode 100644 agent/server/snykbroker/reflector_accept_file_wiring_test.go delete mode 100644 agent/server/snykbroker/reflector_boundary_test.go delete mode 100644 agent/server/snykbroker/reflector_dynamic_target_test.go delete mode 100644 agent/server/snykbroker/reflector_failure_class_test.go delete mode 100644 agent/server/snykbroker/reflector_google_live_test.go delete mode 100644 agent/server/snykbroker/reflector_headers_harness_test.go delete mode 100644 agent/server/snykbroker/reflector_headers_simple_test.go delete mode 100644 agent/server/snykbroker/reflector_headers_test.go delete mode 100644 agent/server/snykbroker/reflector_key_test.go delete mode 100644 agent/server/snykbroker/reflector_test.go delete mode 100644 agent/server/snykbroker/relay_instance_manager.go delete mode 100644 agent/server/snykbroker/relay_instance_manager_test.go delete mode 100644 agent/server/snykbroker/supervisor.go delete mode 100644 agent/server/snykbroker/supervisor_test.go delete mode 100644 agent/server/snykbroker/token_logging_test.go delete mode 100644 agent/server/snykbroker/watchdog.sh delete mode 100644 agent/server/snykbroker/ws_proxy.go delete mode 100644 agent/server/snykbroker/ws_proxy_test.go delete mode 100644 agent/test/relay/Dockerfile.snyk-broker-server delete mode 100644 agent/test/relay/accept-server.json delete mode 100644 agent/test/relay/docker-compose.grpc.noproxy.yml delete mode 100644 agent/test/relay/docker-compose.grpc.yml delete mode 100644 agent/test/relay/docker-compose.proxy.yml delete mode 100755 agent/test/relay/generate-certs.sh delete mode 100644 agent/test/relay/nginx-tls-proxy.conf delete mode 100755 agent/test/relay/relay_test.grpc.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 554e376b..61e27437 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -71,6 +71,15 @@ jobs: run: | make docker-build + - name: Verify image ships no Node or snyk-broker + run: | + docker run --rm --entrypoint sh cortex-axon-agent:local -c ' + for b in node npm npx snyk-broker; do + if command -v "$b"; then echo "unexpected binary: $b" >&2; exit 1; fi + done + if [ -e /usr/local/snyk-broker ]; then echo "unexpected /usr/local/snyk-broker" >&2; exit 1; fi + ' + - name: Run scaffold test - Go run: | cd scaffold && ./scaffold_test.sh go @@ -79,81 +88,16 @@ jobs: run: | cd scaffold && ./scaffold_test.sh python + # The proxied case is the one that matters most: it is the only test + # that proves the agent's outbound gRPC dial works through an HTTP + # proxy via CONNECT, which is the deployment shape most customers + # actually have. - name: "Run Relay Test: With Proxy (TLS)" run: make -C agent relay-test-with-proxy - name: "Run Relay Test: No Proxy" run: make -C agent relay-test-no-proxy - # The same end-to-end scenarios as docker-tests, run over the gRPC tunnel - # instead of snyk-broker. Both transports share relay_scenarios.sh, so this - # is the same suite rather than a parallel copy that can drift — it already - # had once, silently losing the agent-endpoint and credential-injection - # checks, and with them a real gap where the tunnel never stamped - # x-axon-relay-instance on responses. - # - # A separate job rather than more steps on docker-tests: the two transports - # then fail independently, and a gRPC regression is legible from the job - # name without opening the log. - # - # This job is the CI pipeline for the go-only (-grpc) image: it builds that - # variant and runs only the gRPC E2E suite against it. The snyk-broker and - # scaffold tests stay on the full image in docker-tests. - docker-tests-grpc: - runs-on: ubuntu-latest - permissions: - contents: read - steps: - - name: Checkout code - uses: actions/checkout@v2 - - - name: Set up Go - uses: actions/setup-go@v3 - with: - go-version: '1.26.11' - - - name: Install dependencies - run: | - sudo apt-get update - sudo apt-get install -y protobuf-compiler - make -C agent setup proto - - - name: Build Agent Local Image (go-only) - run: | - make docker-build-grpc - - - name: Verify go-only image - env: - IMAGE: cortex-axon-agent:local-grpc - run: | - # No Node runtime or snyk-broker may ship in this variant. - docker run --rm --entrypoint sh "$IMAGE" -c ' - for b in node npm npx snyk-broker; do - if command -v "$b"; then echo "unexpected binary: $b" >&2; exit 1; fi - done - if [ -e /usr/local/snyk-broker ]; then echo "unexpected /usr/local/snyk-broker" >&2; exit 1; fi - ' - # The transport is pinned in the binary, so an override must be refused. - if out=$(docker run --rm -e AXON_RELAY_TRANSPORT=snyk-broker "$IMAGE" relay -a pin-check 2>&1); then - echo "agent accepted AXON_RELAY_TRANSPORT=snyk-broker" >&2; exit 1 - fi - echo "$out" | grep -q 'only supports AXON_RELAY_TRANSPORT=grpc-tunnel' \ - || { echo "$out" >&2; echo "expected the forced-relay-mode error" >&2; exit 1; } - - # The proxied case is the one that matters most for this transport: it - # is the only test that proves the agent's outbound gRPC dial works - # through an HTTP proxy via CONNECT, which is the deployment shape most - # customers actually have. - - name: "Run gRPC Relay Test: With Proxy (TLS)" - env: - AXON_AGENT_IMAGE: cortex-axon-agent:local-grpc - run: make -C agent grpc-relay-test-with-proxy - - - name: "Run gRPC Relay Test: No Proxy" - env: - AXON_AGENT_IMAGE: cortex-axon-agent:local-grpc - run: make -C agent grpc-relay-test-no-proxy - helm-test: runs-on: ubuntu-latest needs: test diff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.yml index 9d595b01..1b68d0f1 100644 --- a/.github/workflows/docker-image.yml +++ b/.github/workflows/docker-image.yml @@ -1,41 +1,20 @@ -# Builds, publishes and scans one variant of the agent image. docker.yml calls -# this once per variant so both flavors share one build definition: a second -# inlined copy is how two images drift into one being scanned and the other -# not (see trivy-scan.yml). +# Builds, publishes and scans the agent image. docker.yml calls this. name: Agent Image on: workflow_call: inputs: - variant: - description: VARIANT build arg for docker/Dockerfile (full or grpc). - required: true - type: string tags: - description: docker/metadata-action `tags` spec for this variant. + description: docker/metadata-action `tags` spec. required: true type: string - flavor: - description: docker/metadata-action `flavor` spec for this variant. - required: false - type: string - default: '' build-args: description: >- Extra docker/Dockerfile build args, one KEY=value per line, e.g. - NODE_VERSION=22. + APT_CACHE_BUST=2026-12-01. required: false type: string default: '' - suffix: - description: >- - Keeps this variant's PR artifact and SARIF category apart from the - full image's. Empty for the full image, so its scan history is - unchanged. - required: false - type: string - default: '' - # Each job states what it needs below. permissions: {} @@ -63,9 +42,9 @@ jobs: uses: actions/cache@v5 with: path: /tmp/.buildx-cache - key: ${{ runner.os }}-buildx-${{ inputs.variant }}-${{ github.sha }} + key: ${{ runner.os }}-buildx-agent-${{ github.sha }} restore-keys: | - ${{ runner.os }}-buildx-${{ inputs.variant }}- + ${{ runner.os }}-buildx-agent- - name: Log in to GitHub Container Registry uses: docker/login-action@v3 @@ -81,7 +60,6 @@ jobs: images: | ghcr.io/${{ github.repository_owner }}/cortex-axon-agent tags: ${{ inputs.tags }} - flavor: ${{ inputs.flavor }} - name: Build and push Docker image uses: docker/build-push-action@v6 @@ -92,7 +70,6 @@ jobs: labels: ${{ steps.meta.outputs.labels }} build-args: | BUILD_VERSION=${{ github.ref_name }}-${{ github.sha }} - VARIANT=${{ inputs.variant }} ${{ inputs.build-args }} # arm64 via QEMU is slow, so only build it on main branch or tags (not workflow_dispatch) platforms: ${{ env.IS_ARM64_BUILD == 'true' && 'linux/amd64,linux/arm64' || 'linux/amd64' }} @@ -113,16 +90,14 @@ jobs: if: env.IS_PUBLISH != 'true' uses: actions/upload-artifact@v4 with: - name: docker-image${{ inputs.suffix }} + name: docker-image path: /tmp/docker-image.tar retention-days: 1 outputs: image-tag: ${{ steps.local-tag.outputs.tag }} # The primary tag metadata-action resolved -- the semver version on a - # tag build, the branch name on main. The go-only image publishes a - # single tag per release, -grpc (0.3.11-grpc from v0.3.11 or - # v0.3.11-grpc), and main-grpc on main, so this is that tag. The release scan + # tag build, the branch name on main. The release scan # targets this rather than a hardcoded :main, so a tag build reports on # the image that tag actually published. published-ref: ghcr.io/${{ github.repository_owner }}/cortex-axon-agent:${{ steps.meta.outputs.version }} @@ -139,7 +114,7 @@ jobs: - name: Download Docker image artifact uses: actions/download-artifact@v4 with: - name: docker-image${{ inputs.suffix }} + name: docker-image path: /tmp - name: Load Docker image @@ -163,7 +138,7 @@ jobs: # Matches the release scan's category so PR and post-merge findings # for this image track one series instead of churning against # each other in the Security tab. - category: trivy-cortex-axon-agent${{ inputs.suffix }} + category: trivy-cortex-axon-agent # The bypass-trivy-fail label lets a PR merge past CVEs it did not # introduce. The findings are still uploaded above and listed here. @@ -195,5 +170,5 @@ jobs: uses: ./.github/workflows/trivy-scan.yml with: image-ref: ${{ needs.build.outputs.published-ref }} - category: trivy-cortex-axon-agent${{ inputs.suffix }} + category: trivy-cortex-axon-agent secrets: inherit diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index dfec720b..dff496be 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -16,12 +16,9 @@ on: permissions: {} jobs: - # cortex-axon-agent: -- both relay transports (snyk-broker and grpc-tunnel). - # Skipped for a -grpc release tag: semver would read v0.3.10-grpc as a - # prerelease and publish the full image as 0.3.10-grpc. - full: - name: Agent image (full) - if: ${{ !(startsWith(github.ref, 'refs/tags/') && endsWith(github.ref, '-grpc')) }} + # cortex-axon-agent: + image: + name: Agent image # A called workflow cannot hold a permission its caller did not grant: # push to ghcr, and upload Trivy SARIF from both scan jobs. permissions: @@ -30,7 +27,6 @@ jobs: security-events: write uses: ./.github/workflows/docker-image.yml with: - variant: full tags: | type=ref,event=branch type=semver,pattern={{version}} @@ -38,57 +34,16 @@ jobs: type=sha secrets: inherit - # cortex-axon-agent:-grpc -- go-only: no Node or snyk-broker, and the - # binary is pinned to AXON_RELAY_TRANSPORT=grpc-tunnel. Every release tag - # publishes it next to the full image: v0.3.11 publishes 0.3.11 (full) and - # 0.3.11-grpc. A v0.3.10-grpc tag publishes only this one, as 0.3.10-grpc, - # which lets a go-only build go out without re-releasing the others. A push - # to main publishes main-grpc. PRs build and scan it without publishing. - # - # Intermediate stage: once snyk-broker is fully deprecated, the full image - # becomes go-only and this variant (and every -grpc tag) collapses back into - # it. - grpc: - name: Agent image (go-only) - if: ${{ github.event_name == 'pull_request' || github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v') }} - permissions: - contents: read - packages: write - security-events: write - uses: ./.github/workflows/docker-image.yml - with: - variant: grpc - # The optional (-grpc) group strips a -grpc tag's own suffix so the - # flavor suffix is not applied twice (0.3.10-grpc-grpc). - # - # latest-grpc moves with the full image's latest: only on a plain v* - # release tag. A one-off v*-grpc tag (often an older version) leaves it - # alone so it cannot roll latest-grpc backwards. latest=false turns off - # the auto latest, which would fire on both; onlatest makes the explicit - # one latest-grpc rather than overwriting the full image's latest. - tags: | - type=match,pattern=^v(.*?)(-grpc)?$,group=1 - type=ref,event=branch - type=ref,event=pr - type=raw,value=latest,enable=${{ startsWith(github.ref, 'refs/tags/v') && !endsWith(github.ref, '-grpc') }} - flavor: | - latest=false - suffix=-grpc,onlatest=true - suffix: -grpc - secrets: inherit - # `build` is a required status check on main, named after the single job - # this workflow used to have. The image jobs above now report as - # "Agent image (full) / build" etc., so without this the required check - # never reports and every PR sits blocked. It passes only when every image - # job that ran passed; a job skipped by its `if` (e.g. full on a -grpc tag) - # does not count against it. + # this workflow used to have. The image job above reports as + # "Agent image / build" etc., so without this the required check never + # reports and every PR sits blocked. build: - needs: [full, grpc] + needs: [image] if: ${{ always() }} runs-on: ubuntu-latest steps: - - name: All agent images built + - name: Agent image built env: RESULTS: ${{ join(needs.*.result, ' ') }} run: | diff --git a/.github/workflows/trivy.yml b/.github/workflows/trivy.yml index 37dd9ad3..8e078507 100644 --- a/.github/workflows/trivy.yml +++ b/.github/workflows/trivy.yml @@ -28,18 +28,6 @@ jobs: category: trivy-cortex-axon-agent secrets: inherit - agent-grpc: - name: Agent image (go-only) - permissions: - contents: read - packages: read - security-events: write - uses: ./.github/workflows/trivy-scan.yml - with: - image-ref: ghcr.io/${{ github.repository_owner }}/cortex-axon-agent:main-grpc - category: trivy-cortex-axon-agent-grpc - secrets: inherit - tunnel-server: name: Tunnel server image permissions: diff --git a/.github/workflows/tunnel-load-test.yml b/.github/workflows/tunnel-load-test.yml index 6aaf057e..be5d5702 100644 --- a/.github/workflows/tunnel-load-test.yml +++ b/.github/workflows/tunnel-load-test.yml @@ -67,8 +67,8 @@ jobs: # pulling the images the image workflows already publish to ghcr.io, or # driving the build through docker/bake-action with cache type=gha. - # Measured peak footprint is ~5GB: a 1.26GB agent image (it bundles Node - # for snyk-broker), a 126MB server image, ~1.2GB of base images and + # Measured peak footprint is ~5GB: a 1.26GB agent image (measured when + # it still bundled Node), a 126MB server image, ~1.2GB of base images and # ~2.5GB of build cache, against the runner's 14GB. Printed so a disk # failure is diagnosable from the log rather than a mystery. - name: Report free disk diff --git a/.github/workflows/validate-filters.yml b/.github/workflows/validate-filters.yml index 392630e4..ee1ccc53 100644 --- a/.github/workflows/validate-filters.yml +++ b/.github/workflows/validate-filters.yml @@ -6,7 +6,7 @@ on: - '**' paths: - 'agent/test/*.json' - - 'agent/server/snykbroker/accept_files/**' + - 'agent/server/acceptfile/accept_files/**' jobs: diff --git a/.vscode/launch.json b/.vscode/launch.json index 300f8769..ea7e09db 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -84,7 +84,7 @@ "SCAFFOLD_DIR": "${workspaceFolder}/scaffold", "SCAFFOLD_DOCKER_IMAGE": "cortex-axon-agent:local", "PORT" : "7399", - "BUILTIN_PLUGIN_DIR": "${workspaceFolder}/agent/server/snykbroker/plugins", + "BUILTIN_PLUGIN_DIR": "${workspaceFolder}/agent/server/acceptfile/plugins", "ENABLE_PPROF": "true" } }, @@ -118,8 +118,7 @@ "SCAFFOLD_DIR": "${workspaceFolder}/scaffold", "SCAFFOLD_DOCKER_IMAGE": "cortex-axon-agent:local", "PORT": "7399", - "BUILTIN_PLUGIN_DIR": "${workspaceFolder}/agent/server/snykbroker/plugins", - "RELAY_MODE": "grpc-tunnel", + "BUILTIN_PLUGIN_DIR": "${workspaceFolder}/agent/server/acceptfile/plugins", "BROKER_SERVER_URL": "localhost:50052", "BROKER_TOKEN": "4f49654b-000-0000-000-9deef1d9f2f6", "CORTEX_TENANT_ID": "1", diff --git a/AGENTS.md b/AGENTS.md index d3cc4eac..55e68952 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,10 +6,6 @@ Guidance for AI coding agents working in this repository. - Never include customer names or identifiers, always anonymize references -# Architecture notes - -- The snyk-broker component is always used in websocket mode. Data transport never uses long polling. - # Protocol compatibility - Changes under `proto/` MUST be wire compatible in both directions. Tunnel servers and agents are deployed independently and run mixed versions, so existing functionality must never depend on which side is upgraded first. diff --git a/Makefile b/Makefile index 596fb5dd..16d06607 100644 --- a/Makefile +++ b/Makefile @@ -14,19 +14,13 @@ run-agent: .PHONY: run-agent DOCKER_TAG ?= cortex-axon-agent:local -# full or grpc (go-only, no Node); see the top of docker/Dockerfile. -DOCKER_VARIANT ?= full -# Extra `--build-arg`s, e.g. NODE_VERSION (see deps-full in docker/Dockerfile). +# Extra `--build-arg`s, e.g. APT_CACHE_BUST (see docker/Dockerfile). DOCKER_BUILD_ARGS ?= docker-build: docker/Dockerfile - docker build -t $(DOCKER_TAG) --build-arg VARIANT=$(DOCKER_VARIANT) $(DOCKER_BUILD_ARGS) --progress=plain -f $< . + docker build -t $(DOCKER_TAG) $(DOCKER_BUILD_ARGS) --progress=plain -f $< . .PHONY: docker-build -docker-build-grpc: - $(MAKE) docker-build DOCKER_VARIANT=grpc DOCKER_TAG=cortex-axon-agent:local-grpc -.PHONY: docker-build-grpc - setup: $(MAKE) -C agent setup diff --git a/README.md b/README.md index 989d1e2c..d152b736 100644 --- a/README.md +++ b/README.md @@ -230,5 +230,4 @@ The agent exposes a Prometheus endpoint at `/metrics` on the default port (80), * `axon_handler_latency` (histogram) the latency of the handler invocation, with labels for the handler name and the status of the invocation (success or failure) * `axon_http_requests` (counter) the number of HTTP requests made to the agent, with labels for the method, path, and status of the request * `axon_http_request_latency_seconds` (histogram) the latency of the HTTP request, with labels for the method, path, and status of the request -* `broker_operations` (counter) the number of operations made to the broker, with labels for the operation type (`broker_start`, `broker_restart`, `broker_register`, `broker-exit`) and status of the request * `axon_webhook_received` (counter) the number of webhooks received, with labels for the webhook id and status of the request diff --git a/README.relay.md b/README.relay.md index 7575416a..be17f7a2 100644 --- a/README.relay.md +++ b/README.relay.md @@ -61,7 +61,7 @@ Now run `docker compose up` and you should see the agent start up and connect to To test it, go to the settings page for your integration and push "Test Configurations". If you watch the logging output you should see the agent receive the request and forward it to your internal service, and the Cortex Integrations Settings page will show success. -You can see the list of built in file types [here](agent/server/snykbroker/accept_files), which will show the variables needed to execute. If an environment variable +You can see the list of built in file types [here](agent/server/acceptfile/accept_files), which will show the variables needed to execute. If an environment variable is not found, the start will fail with an error message indicating the missing variable name. Generally the naming works like: @@ -145,37 +145,19 @@ docker run --rm --entrypoint /agent/plugins/google-adc cortex-axon-agent:latest `cortex-axon-agent` subcommand. No output means ADC found a credential; it's cached in a file so it isn't re-minted on every request. -## Relay transports +## Relay transport -The relay agent supports two wire transports between your network and the -Cortex cloud, selected with the `AXON_RELAY_TRANSPORT` environment variable: +The relay agent connects to the Cortex cloud over a gRPC tunnel. The agent +opens all connections outbound, gets the tunnel server address and token from +the `/register` call, and relays the calls that its accept file allows. -| Transport | `AXON_RELAY_TRANSPORT` | Status | -|-----------|------------------------|--------| -| Snyk Broker (WebSocket) | `snyk-broker` | Default | -| gRPC tunnel | `grpc-tunnel` | Incubating (opt-in) | +Earlier versions also supported a Snyk Broker (WebSocket) transport, selected +with `AXON_RELAY_TRANSPORT`. That transport is removed. The agent ignores +`AXON_RELAY_TRANSPORT`, `RELAY_MODE`, `ENABLE_RELAY_REFLECTOR`, +`REFLECTOR_WEBSOCKET_UPGRADE`, `RELAY_IDLE_TIMEOUT` and `SNYK_BROKER_PORT`. +Accept files do not change. -Both transports use the same accept files, the same `/register` handshake, -and the same Cortex-side configuration — the accept-file conformance suite -(`agent/test/conformance/`) pins their semantics to a single definition, so -switching transports never changes which requests are allowed or how they -are rewritten. To switch, set the environment variable and restart the -agent; to roll back, unset it and restart. No state carries between modes. - -When `AXON_RELAY_TRANSPORT` is not set, Cortex can select the transport for -your tenant. The agent reads it from the `/register` response at start, -and checks it again at the auto-register interval (`AUTO_REGISTER_FREQUENCY`, -default 5 minutes). When a successful check returns a different transport, -the agent stops cleanly and starts again in the same process with the new -transport. A failed check changes nothing. The agent selects the transport -in this order: - -1. `AXON_RELAY_TRANSPORT` (or `RELAY_MODE`), if set. Cortex never changes it. -2. The transport Cortex selects for your tenant. -3. The default, `snyk-broker`. The agent also uses the default if the - `/register` call fails at start. - -gRPC-tunnel-specific settings (all optional): +Tunnel settings (all optional): | Variable | Default | Meaning | |----------|---------|---------| @@ -238,7 +220,7 @@ the agent has, it holds the stream for up to `AGENT_REPORT_GRACE` (default first, so its header can only say `awaiting_agent`; the log line carries the final cause. -The design, wire protocol, and rollout plan are documented in +The design and wire protocol are documented in [docs/design/grpc-tunnel-v2.md](docs/design/grpc-tunnel-v2.md). ### Network timeouts @@ -255,54 +237,48 @@ exists, takes precedence. | Waiting for response headers | 5m (matches `AXON_GRPC_TUNNEL_MAX_REQUEST_TIMEOUT`) | | Idle connection kept in the pool | 90s | | Relay registration (`/register`) | 30s | -| Broker `/systemcheck` proxy | 10s | -| WebSocket proxy dial, CONNECT and TLS handshake | 30s | The agent's own HTTP servers bound how long they take to read an incoming -request, headers and body, counted from when the connection is accepted. The -relay reflector allows 30s, because the broker writes a request only when its -event loop gets to it, and that loop stalls for two to three seconds while it -sends a large response. +request, headers and body, counted from when the connection is accepted. | Server | Read bound | |--------|------------| -| Relay reflector | 30s | | Webhook server | 30s | | Main server | 1s (30s for a `/cortex-api/` request body) | ## How it works -Internally, Cortex Axon uses an open-source project published by Snyk called [Snyk Broker](https://docs.snyk.io/enterprise-setup/snyk-broker). +The agent opens a gRPC tunnel from the internal network to the cloud-hosted +Cortex. As the tunnel is initiated from the internal network, no firewall +ports need to be opened. -Snyk Broker is a connector that uses websockets to create a secure tunnel between the internal network and the cloud-hosted Cortex. As the tunnel is initiated from the internal network, so no firewall ports need to be opened. - -The flow is based on your Cortex API key, is used to authenticate the agent and secure the connection process. +The flow is based on your Cortex API key, which is used to authenticate the agent and secure the connection process. 1. On the Cortex side, the integration is registered in the integration configuration settings page, with an "alias" name that you choose, such as `github-relay`. -2. The Cortex Axon Docker container is started with the your Cortex API key, the integration type (e.g. `github`), and the alias name that you chose. +2. The Cortex Axon Docker container is started with your Cortex API key, the integration type (e.g. `github`), and the alias name that you chose. 3. The Cortex Axon agent connects to the Cortex service, authenticates, and registers itself with the integration type and alias name. -4. The agent starts an instance of the `snyk-broker` (client) process and uses configuration infromatio from the `/register` call to connect to the Cortex backend instance of the `snyk-broker` server. +4. The agent uses the tunnel server address and token from the `/register` call to open gRPC streams to the Cortex tunnel server. Once this is established, it is a robust connection that allows API calls made on the Cortex side to be relayed to the internal network, and the responses to be relayed back to the Cortex service. ```mermaid graph TD - + CortexAxonAgent -->|Registration| CortexService - SnykBrokerServer -->|Github API Calls|SnykBrokerClient - SnykBrokerClient -->|Github API Calls|InternalGithub - CortexService -->|Github API Calls|SnykBrokerServer + TunnelServer -->|Github API Calls|TunnelClient + TunnelClient -->|Github API Calls|InternalGithub + CortexService -->|Github API Calls|TunnelServer subgraph Cortex-Cloud - CortexService["CortexService
api.getcortexapp.com"] - SnykBrokerServer["SnykBrokerServer
relay.cortex.io"] + CortexService["CortexService
api.getcortexapp.com"] + TunnelServer["TunnelServer
relay.cortex.io"] end subgraph Customer-Network subgraph CortexAxonAgent["CortexAxonAgent - ghcr.io"] - SnykBrokerClient + TunnelClient end InternalGithub end @@ -310,8 +286,8 @@ graph TD style Cortex-Cloud fill:#93f, color:white style CortexAxonAgent fill:#93f style Customer-Network fill:#070 - style SnykBrokerServer fill:#ffbf00,color:black - style SnykBrokerClient fill:#ffbf00,color:black + style TunnelServer fill:#ffbf00,color:black + style TunnelClient fill:#ffbf00,color:black style InternalGithub fill:#39f ``` @@ -349,7 +325,7 @@ proxy: | Endpoint | Purpose | |----------|---------| | `api.getcortexapp.com` | CortexService - Agent registration and API calls | - | `relay.cortex.io` | SnykBrokerServer - WebSocket tunnel for relayed requests | + | `relay.cortex.io` | TunnelServer - gRPC tunnel for relayed requests (the address comes from `/register`) | No inbound firewall ports need to be opened - the agent initiates all outbound connections. @@ -357,7 +333,7 @@ proxy: ## Understanding the Agent configuration -Agent configuration is driven with an `accept.json` file which defines which outbound routes the agent can call in your environment. There are built-in files for all of the supported integrations [here](agent/server/snykbroker/accept_files), but these files are not special, you can always create your own file and pass it with the `-f` flag, for example: +Agent configuration is driven with an `accept.json` file which defines which outbound routes the agent can call in your environment. There are built-in files for all of the supported integrations [here](agent/server/acceptfile/accept_files), but these files are not special, you can always create your own file and pass it with the `-f` flag, for example: ```bash docker run ... -v "/path/to/accept.json:/config/accept.json" ... cortex-axon-agent:latest relay -i github -a github-relay -f /config/accept.json @@ -378,7 +354,7 @@ The file supports the following as a Hello World example: } ``` -This says that any traffic sent to the agent via the Snyk Broker connection will be forwarded to `https://some-server.com/*`, and the method can be any HTTP method (GET, POST, etc). +This says that any traffic sent to the agent through the tunnel will be forwarded to `https://some-server.com/*`, and the method can be any HTTP method (GET, POST, etc). This can be differentiated by paths to select multiple outbounds: diff --git a/agent/.gitignore b/agent/.gitignore index 2650dbaa..039c0fb9 100644 --- a/agent/.gitignore +++ b/agent/.gitignore @@ -6,6 +6,5 @@ axon-agent plugins/google-adc *.pyc # mitmproxy: ignore generated/derived files, track CA files -test/relay/.mitmproxy/broker-server-* test/relay/.mitmproxy/combined-ca-bundle.crt test/relay/.mitmproxy/*.srl diff --git a/agent/Makefile b/agent/Makefile index d31aff5c..0b2f1aa5 100644 --- a/agent/Makefile +++ b/agent/Makefile @@ -84,12 +84,7 @@ server/http/http_server_mock.go: server/http/http_server.go $(GOBIN)/mockgen -package http -destination $@ github.com/cortexapps/axon/server/http Server @echo "Mock $@ generated" -server/snykbroker/registration_mock.go: server/snykbroker/registration.go - @$(MAKE) mockgen - $(GOBIN)/mockgen -package snykbroker -destination $@ github.com/cortexapps/axon/server/snykbroker Registration - @echo "Mock $@ generated" - -mocks: server/http/http_server_mock.go server/snykbroker/registration_mock.go +mocks: server/http/http_server_mock.go test: mocks go mod tidy @@ -99,7 +94,7 @@ test: mocks # not yet: server, server/handler, server/http and cmd have known races # (handler manager, the fx server stack). Move packages up here as those are # fixed. -RACE_CLEAN_PKGS := ./common/... ./config/... ./scaffold/... ./server/api/... ./server/cron/... ./server/snykbroker/... ./test/httpfake/... ./util/... +RACE_CLEAN_PKGS := ./common/... ./config/... ./scaffold/... ./server/api/... ./server/cron/... ./server/acceptfile/... ./test/httpfake/... ./util/... test-race: mocks go test -race $(RACE_CLEAN_PKGS) @@ -108,36 +103,20 @@ test-race: mocks # Live check of the Google credential source against whatever Application Default # Credentials this machine has. Opt-in: it makes real requests to Google. -test-google-live: plugins - AXON_GOOGLE_LIVE_TEST=1 go test -count=1 -run TestLiveGoogle -v ./server/snykbroker/ -.PHONY: test-google-live - validate-filters: test/validate_filters.sh relay-test-no-proxy: - # No proxy case @echo "Running relay tests: no proxy" cd test/relay && export PROXY=0 && ./relay_test.sh -relay-test-with-proxy: - # Proxy case +relay-test-with-proxy: @echo "Running relay tests: with proxy" cd test/relay && export PROXY=1 && ./relay_test.sh relay-test: relay-test-no-proxy relay-test-with-proxy -grpc-relay-test-no-proxy: - @echo "Running gRPC relay tests: no proxy" - cd test/relay && export PROXY=0 && ./relay_test.grpc.sh - -grpc-relay-test-with-proxy: - @echo "Running gRPC relay tests: with proxy" - cd test/relay && export PROXY=1 && ./relay_test.grpc.sh - -grpc-relay-test: grpc-relay-test-no-proxy grpc-relay-test-with-proxy - -.PHONY: relay-test relay-test-no-proxy relay-test-with-proxy grpc-relay-test grpc-relay-test-no-proxy grpc-relay-test-with-proxy +.PHONY: relay-test relay-test-no-proxy relay-test-with-proxy run: proto go run main.go serve diff --git a/agent/cmd/http_client.go b/agent/cmd/http_client.go index 66b7352b..6ad90a68 100644 --- a/agent/cmd/http_client.go +++ b/agent/cmd/http_client.go @@ -61,8 +61,8 @@ func createHttpTransport(config config.AgentConfig, logger *zap.Logger) *gohttp. } } - // This transport is shared by the Cortex API proxy, the reflector and - // relay registration. It is deliberately uncapped: MaxConnsPerHost queues + // This transport is shared by the Cortex API proxy and relay + // registration. It is deliberately uncapped: MaxConnsPerHost queues // instead of failing, so one caller that leaks connections (registration // bodies left unclosed, in one incident) would starve every other user of // the same host with no error anywhere. The gRPC tunnel, whose upstream is diff --git a/agent/cmd/http_client_test.go b/agent/cmd/http_client_test.go index ab1f39e6..47ec29b4 100644 --- a/agent/cmd/http_client_test.go +++ b/agent/cmd/http_client_test.go @@ -9,8 +9,7 @@ import ( "go.uber.org/zap" ) -// The shared transport serves the Cortex API proxy, registration and the -// reflector. It must never cap connections per host (a cap queues instead of +// The shared transport serves the Cortex API proxy and registration. It must never cap connections per host (a cap queues instead of // failing, so one leaking caller starves every other user of the host) and it // must bound every phase of a request so a hung upstream cannot hold a // connection forever. diff --git a/agent/cmd/relay.go b/agent/cmd/relay.go index 327db04c..9d6d0c21 100644 --- a/agent/cmd/relay.go +++ b/agent/cmd/relay.go @@ -8,7 +8,6 @@ import ( "github.com/cortexapps/axon/config" "github.com/cortexapps/axon/server/grpctunnel" "github.com/cortexapps/axon/server/handler" - "github.com/cortexapps/axon/server/snykbroker" "github.com/spf13/cobra" "go.uber.org/fx" ) @@ -82,19 +81,11 @@ func init() { } func buildRelayStack(cmd *cobra.Command, cfg config.AgentConfig, integrationInfo common.IntegrationInfo) fx.Option { - cfg, relayModeRestart := withRelayMode(cfg, integrationInfo) - - relayModule := snykbroker.Module - if cfg.IsGRPCTunnel() { - relayModule = grpctunnel.Module - } - stack := fx.Options( initStack(cmd, cfg, integrationInfo), AgentModule, fx.Provide(handler.NewHandlerManager), - relayModule, - relayModeRestart, + grpctunnel.Module, ) return stack } diff --git a/agent/cmd/relay_mode.go b/agent/cmd/relay_mode.go deleted file mode 100644 index 63b45007..00000000 --- a/agent/cmd/relay_mode.go +++ /dev/null @@ -1,94 +0,0 @@ -package cmd - -import ( - "context" - "fmt" - "os" - "sync/atomic" - "syscall" - "time" - - "github.com/cortexapps/axon/common" - "github.com/cortexapps/axon/config" - "github.com/cortexapps/axon/server/relaymode" - "github.com/cortexapps/axon/server/snykbroker" - "go.uber.org/fx" - "go.uber.org/zap" -) - -// defaultRelayModeCheckInterval applies when AUTO_REGISTER_FREQUENCY is 0. -const defaultRelayModeCheckInterval = 5 * time.Minute - -// restartRequested is set when the relay mode watcher stops the app because -// Cortex selected a different mode. startAgent then starts the agent again. -var restartRequested atomic.Bool - -// withRelayMode returns cfg with RelayMode set to the mode the stack runs. -// It runs before the stack is built, because the mode decides which relay -// module the stack contains. The registration uses the same transport -// settings (proxy, CA) as the stack. When Cortex drives the mode, it also -// returns restartOnRelayModeChange for the stack. -func withRelayMode(cfg config.AgentConfig, info common.IntegrationInfo) (config.AgentConfig, fx.Option) { - reg := snykbroker.NewRegistration(cfg, createHttpClient(cfg, createHttpTransport(cfg, zap.NewNop()))) - res := relaymode.Resolve(context.Background(), cfg, info, reg) - fmt.Printf("Relay mode: %s, %s\n", res.Mode, res.Reason) - cfg.RelayMode = string(res.Mode) - - if !res.Remote { - return cfg, fx.Options() - } - return cfg, restartOnRelayModeChange(cfg, info, res.Mode) -} - -// restartOnRelayModeChange is the fx wiring for relaymode.Watch, which has -// the watch logic. It runs Watch for the life of the app. When Watch -// reports a different mode, it stops the app and requests a restart, which -// startAgent does after the stop. -func restartOnRelayModeChange(cfg config.AgentConfig, info common.IntegrationInfo, running config.RelayMode) fx.Option { - interval := cfg.AutoRegisterFrequency - if interval <= 0 { - interval = defaultRelayModeCheckInterval - } - - return fx.Invoke(func(lc fx.Lifecycle, shutdowner fx.Shutdowner, logger *zap.Logger, reg snykbroker.Registration) { - ctx, cancel := context.WithCancel(context.Background()) - done := make(chan struct{}) - lc.Append(fx.Hook{ - OnStart: func(context.Context) error { - go func() { - defer close(done) - relaymode.Watch(ctx, interval, info, reg, running, func(mode config.RelayMode) { - logger.Info("Cortex selected a different relay mode, restarting the agent", - zap.String("from", string(running)), zap.String("to", string(mode))) - restartRequested.Store(true) - if err := shutdowner.Shutdown(); err != nil { - logger.Error("Unable to stop the agent for a relay mode change", zap.Error(err)) - } - }) - }() - return nil - }, - OnStop: func(context.Context) error { - cancel() - <-done - return nil - }, - }) - }) -} - -// reexec replaces this process with a new run of the same binary, with the -// same arguments and environment. The PID stays the same, so it works with -// no restart policy, and a container does not restart. The app must be -// stopped first, so that child processes (snyk-broker) are gone and ports -// are free. If the exec fails, the agent exits so that a restart policy can -// start it again. -func reexec() { - exe, err := os.Executable() - if err == nil { - fmt.Println("Starting the agent again with the new relay mode") - err = syscall.Exec(exe, os.Args, os.Environ()) - } - fmt.Printf("Unable to start the agent again: %v\n", err) - os.Exit(1) -} diff --git a/agent/cmd/relay_mode_test.go b/agent/cmd/relay_mode_test.go deleted file mode 100644 index af26b343..00000000 --- a/agent/cmd/relay_mode_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package cmd - -import ( - "context" - "testing" - "time" - - "github.com/cortexapps/axon/common" - "github.com/cortexapps/axon/config" - "github.com/cortexapps/axon/server/snykbroker" - "github.com/stretchr/testify/require" - "go.uber.org/fx" - "go.uber.org/zap" -) - -type grpcTunnelRegistration struct{} - -func (grpcTunnelRegistration) Register(context.Context, common.Integration, string) (*snykbroker.RegistrationInfoResponse, error) { - return &snykbroker.RegistrationInfoResponse{TunnelMode: "grpc-tunnel"}, nil -} - -// When Cortex selects a different mode, the watcher stops the app and -// requests a restart. startAgent then starts the agent again. -func TestRestartOnRelayModeChange_StopsTheApp(t *testing.T) { - restartRequested.Store(false) - t.Cleanup(func() { restartRequested.Store(false) }) - - app := fx.New( - fx.NopLogger, - fx.Supply(zap.NewNop()), - fx.Provide(func() snykbroker.Registration { return grpcTunnelRegistration{} }), - restartOnRelayModeChange(config.AgentConfig{AutoRegisterFrequency: time.Millisecond}, - common.IntegrationInfo{}, config.RelayModeSnykBroker), - ) - require.NoError(t, app.Start(context.Background())) - - select { - case <-app.Wait(): - case <-time.After(2 * time.Second): - t.Fatal("the watcher did not stop the app") - } - require.True(t, restartRequested.Load()) - require.NoError(t, app.Stop(context.Background())) -} diff --git a/agent/cmd/serve.go b/agent/cmd/serve.go index cf8b56fc..3b3991d9 100644 --- a/agent/cmd/serve.go +++ b/agent/cmd/serve.go @@ -9,7 +9,6 @@ import ( "github.com/cortexapps/axon/config" "github.com/cortexapps/axon/server/grpctunnel" "github.com/cortexapps/axon/server/http" - "github.com/cortexapps/axon/server/snykbroker" "github.com/spf13/cobra" "go.uber.org/fx" ) @@ -42,19 +41,11 @@ var serveCmd = &cobra.Command{ Alias: config.IntegrationAlias, } - config, relayModeRestart := withRelayMode(config, info) - - relayModule := snykbroker.Module - if config.IsGRPCTunnel() { - relayModule = grpctunnel.Module - } - stack := fx.Options( initStack(cmd, config, info), AgentModule, http.Module, - relayModule, - relayModeRestart, + grpctunnel.Module, ) startAgent(stack) diff --git a/agent/cmd/serve_test.go b/agent/cmd/serve_test.go index 116a021d..a120d74a 100644 --- a/agent/cmd/serve_test.go +++ b/agent/cmd/serve_test.go @@ -13,8 +13,8 @@ import ( "github.com/cortexapps/axon/common" "github.com/cortexapps/axon/config" + "github.com/cortexapps/axon/server/grpctunnel" cortexHttp "github.com/cortexapps/axon/server/http" - "github.com/cortexapps/axon/server/snykbroker" "github.com/cortexapps/axon/util" "github.com/spf13/cobra" "github.com/stretchr/testify/require" @@ -27,7 +27,7 @@ func buildServeStack(cmd *cobra.Command, config config.AgentConfig) fx.Option { initStack(cmd, config, common.IntegrationInfo{}), AgentModule, cortexHttp.Module, - snykbroker.Module, + grpctunnel.Module, ) } @@ -56,7 +56,7 @@ func TestBuildServeStackLive(t *testing.T) { // create a fake server that serves http://localhost:xxx/relay/register server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - rr := snykbroker.RegistrationInfoResponse{ + rr := grpctunnel.RegistrationInfoResponse{ ServerUri: "http://localhost:12345", Token: "test-broker-token", } @@ -129,8 +129,7 @@ func TestBuildRelayStack(t *testing.T) { "PORT": "0", "BROKER_SERVER_URL": "http://broker.cortex.io", "BROKER_TOKEN": "abcd1234", - "SNYK_BROKER_PATH": "bash", - "ACCEPTFILE_DIR": "../server/snykbroker/accept_files", + "ACCEPTFILE_DIR": "../server/acceptfile/accept_files", "GITHUB_TOKEN": "the-token", "GITHUB_API": "api.github.com", "GITHUB_GRAPHQL": "api.github.com/graphql", @@ -142,7 +141,6 @@ func TestBuildRelayStack(t *testing.T) { config.FailWaitTime = time.Millisecond config.HttpServerPort = common.GetRandomPort() config.WebhookServerPort = common.GetRandomPort() - config.RelayIdleTimeout = 0 // Disable idle timeout to prevent restart during test stack := buildRelayStack(&cobra.Command{}, config, common.IntegrationInfo{ Integration: common.IntegrationGithub, }) @@ -163,22 +161,20 @@ func TestBuildRelayStack(t *testing.T) { // The gRPC tunnel takes the shared *http.Transport through an optional fx // parameter; validating the graph proves the dependency resolves without // dialing anything. -func TestBuildRelayStackGrpcTunnel_Validates(t *testing.T) { +func TestBuildRelayStack_Validates(t *testing.T) { oldEnv := util.SaveEnv(false) defer util.RestoreEnv(oldEnv) common.ApplyEnv(map[string]string{ "DRYRUN": "true", "PORT": "0", - "ACCEPTFILE_DIR": "../server/snykbroker/accept_files", + "ACCEPTFILE_DIR": "../server/acceptfile/accept_files", "GITHUB_TOKEN": "the-token", "GITHUB_API": "api.github.com", "GITHUB_GRAPHQL": "api.github.com/graphql", }) cfg := config.NewAgentEnvConfig() - cfg.RelayMode = string(config.RelayModeGrpcTunnel) - require.True(t, cfg.IsGRPCTunnel()) stack := buildRelayStack(&cobra.Command{}, cfg, common.IntegrationInfo{Integration: common.IntegrationGithub}) require.NoError(t, fx.ValidateApp(stack)) diff --git a/agent/cmd/stack.go b/agent/cmd/stack.go index d662f03a..cf6c14db 100644 --- a/agent/cmd/stack.go +++ b/agent/cmd/stack.go @@ -30,12 +30,6 @@ func startAgent(opts fx.Option) { fmt.Println(banner) } app.Run() - - // Run returns after a clean stop. When the relay mode watcher stopped - // the app, start the agent again with the new mode. - if restartRequested.Load() { - reexec() - } } var AgentModule = fx.Module("agent", diff --git a/agent/common/integration.go b/agent/common/integration.go index 57a6f1f0..8a009254 100644 --- a/agent/common/integration.go +++ b/agent/common/integration.go @@ -9,7 +9,7 @@ import ( "strings" "github.com/cortexapps/axon/config" - "github.com/cortexapps/axon/server/snykbroker/acceptfile" + "github.com/cortexapps/axon/server/acceptfile" "go.uber.org/zap" ) @@ -190,7 +190,7 @@ func (ii IntegrationInfo) getIntegrationFileContents(fileName string) (string, e acceptFileDir := os.Getenv("ACCEPTFILE_DIR") if acceptFileDir == "" { - acceptFileDir = "server/snykbroker/accept_files" + acceptFileDir = "server/acceptfile/accept_files" } fullPath := path.Join(acceptFileDir, fileName) diff --git a/agent/common/integration_test.go b/agent/common/integration_test.go index e09723c2..f36139ba 100644 --- a/agent/common/integration_test.go +++ b/agent/common/integration_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/cortexapps/axon/config" - "github.com/cortexapps/axon/server/snykbroker/acceptfile" + "github.com/cortexapps/axon/server/acceptfile" "github.com/stretchr/testify/require" "go.uber.org/zap" @@ -92,7 +92,7 @@ func TestExistingAcceptFile(t *testing.T) { func setAcceptFileDir(t *testing.T) { pwd, err := os.Getwd() require.NoError(t, err) - acceptFileDir := path.Join(pwd, "..", "server", "snykbroker", "accept_files") + acceptFileDir := path.Join(pwd, "..", "server", "acceptfile", "accept_files") os.Setenv("ACCEPTFILE_DIR", acceptFileDir) } diff --git a/agent/config/config.go b/agent/config/config.go index 1106916e..e861c0e9 100644 --- a/agent/config/config.go +++ b/agent/config/config.go @@ -15,57 +15,6 @@ const DefaultGrpcPort = 50051 const DefaultHttpPort = 80 const WebhookServerPort = 8081 -type RelayReflectorMode int - -// RelayReflectorMode controls how the reflector proxy routes traffic. -// The reflector intercepts HTTP requests to handle CA certs and add custom headers. -const ( - RelayReflectorDisabled RelayReflectorMode = iota // No reflector - all traffic goes direct - RelayReflectorRegistrationOnly // Only broker server URL goes through reflector - RelayReflectorAllTraffic // Both broker URL and accept file origins go through reflector - RelayReflectorTrafficOnly // Only accept file origins go through reflector (DEFAULT) -) - -func (m RelayReflectorMode) String() string { - switch m { - case RelayReflectorDisabled: - return "Disabled" - case RelayReflectorRegistrationOnly: - return "RegistrationOnly" - case RelayReflectorAllTraffic: - return "AllTraffic" - case RelayReflectorTrafficOnly: - return "TrafficOnly" - default: - return "Unknown" - } -} - -// ReflectsRegistration returns true if this mode routes the broker server URL through the reflector. -// Modes: registration, all -func (m RelayReflectorMode) ReflectsRegistration() bool { - return m == RelayReflectorRegistrationOnly || m == RelayReflectorAllTraffic -} - -// ReflectsTraffic returns true if this mode routes accept file origins through the reflector. -// Modes: traffic, all -func (m RelayReflectorMode) ReflectsTraffic() bool { - return m == RelayReflectorTrafficOnly || m == RelayReflectorAllTraffic -} - -// IsEnabled returns true if this mode enables the reflector at all. -// Modes: registration, traffic, all -func (m RelayReflectorMode) IsEnabled() bool { - return m != RelayReflectorDisabled -} - -type RelayMode string - -const ( - RelayModeSnykBroker RelayMode = "snyk-broker" - RelayModeGrpcTunnel RelayMode = "grpc-tunnel" -) - type AgentConfig struct { GrpcPort int CortexApiBaseUrl string @@ -77,7 +26,6 @@ type AgentConfig struct { IntegrationAlias string HttpServerPort int WebhookServerPort int - SnykBrokerPort int EnableApiProxy bool EnablePprof bool FailWaitTime time.Duration @@ -89,19 +37,9 @@ type AgentConfig struct { HandlerHistoryMaxAge time.Duration HandlerHistoryMaxSizeBytes int64 - HttpDisableTLS bool - HttpCaCertFilePath string - HttpRelayReflectorMode RelayReflectorMode - ReflectorWebSocketUpgrade bool - RelayIdleTimeout time.Duration - - // RelayMode selects the tunnel implementation: "snyk-broker" or - // "grpc-tunnel". NewAgentEnvConfig sets it only from AXON_RELAY_TRANSPORT - // (or RELAY_MODE) or ForcedRelayMode, and leaves it empty otherwise, so - // that a customer choice is distinguishable from the default. The relay - // commands then fill it in from the Cortex registration or the default - // before they build the stack; see cmd/relay_mode.go. - RelayMode string + HttpDisableTLS bool + HttpCaCertFilePath string + // TunnelConns is how many gRPC connections the agent opens outbound, and // the only tunnel dial there is. Each is load-balanced round-robin // across every server instance, so this is a blast-radius decision: @@ -117,8 +55,8 @@ type AgentConfig struct { // opens to any single upstream host, and sets its idle-connection pool to // match so concurrent calls reuse connections instead of handshaking. // - // Tunnel only. The shared transport used for Cortex API calls, - // registration and the reflector is deliberately uncapped, because a cap + // Tunnel only. The shared transport used for Cortex API calls and + // registration is deliberately uncapped, because a cap // queues rather than fails and would hide a connection leak; see // cmd/http_client.go. The tunnel clones that transport and applies this // cap to its own copy (grpctunnel.NewTunnelClient), since its upstream is @@ -146,42 +84,6 @@ func (ac AgentConfig) HttpBaseUrl() string { return fmt.Sprintf("http://localhost:%d", ac.HttpServerPort) } -// ForcedRelayMode, when non-empty, is the only relay mode this binary will -// run. It is stamped at build time by the go-only (-grpc) image: -// -// go build -ldflags "-X github.com/cortexapps/axon/config.ForcedRelayMode=grpc-tunnel" -// -// That image ships no Node or snyk-broker, so snyk-broker mode would fail at -// the first spawn. Pinning it in the binary rather than only as an image ENV -// means an AXON_RELAY_TRANSPORT override in a customer's deployment cannot -// select it. -var ForcedRelayMode string - -// applyForcedRelayMode returns the mode the configuration pins, or "" when -// nothing pins one. An explicit request for a different mode than the forced -// one panics rather than being silently ignored, so a deployment still -// configured for snyk-broker fails loudly at startup. -func applyForcedRelayMode(requested string) string { - if ForcedRelayMode == "" { - return requested - } - if requested != "" && requested != ForcedRelayMode { - panic(fmt.Sprintf("this build only supports AXON_RELAY_TRANSPORT=%s, got %q", ForcedRelayMode, requested)) - } - return ForcedRelayMode -} - -// IsGRPCTunnel returns true if the relay mode is grpc-tunnel. -func (ac AgentConfig) IsGRPCTunnel() bool { - return ac.RelayMode == "grpc-tunnel" -} - -// RelayModePinned returns true if the customer or the build selected a relay -// mode. Cortex cannot change a pinned mode. -func (ac AgentConfig) RelayModePinned() bool { - return ac.RelayMode != "" -} - func (ac AgentConfig) Print() { fmt.Println("Agent Configuration:") if ac.GrpcPort != DefaultGrpcPort { @@ -270,15 +172,6 @@ func NewAgentEnvConfig() AgentConfig { httpPort = p } - snykBrokerPort := 0 - if snykBrokerPortStr := os.Getenv("SNYK_BROKER_PORT"); snykBrokerPortStr != "" { - p, err := strconv.Atoi(snykBrokerPortStr) - if err != nil { - panic(err) - } - snykBrokerPort = p - } - dryRun := false if dryRunEnv := os.Getenv("DRYRUN"); dryRunEnv != "" { dryRun = dryRunEnv == "true" || dryRunEnv == "1" @@ -350,7 +243,6 @@ func NewAgentEnvConfig() AgentConfig { IntegrationAlias: identifier, HttpServerPort: httpPort, WebhookServerPort: WebhookServerPort, - SnykBrokerPort: snykBrokerPort, EnableApiProxy: true, EnablePprof: enablePprof, FailWaitTime: time.Second * 2, @@ -383,40 +275,6 @@ func NewAgentEnvConfig() AgentConfig { cfg.HttpCaCertFilePath = filepath.Clean(cfg.HttpCaCertFilePath) } - cfg.HttpRelayReflectorMode = RelayReflectorAllTraffic // Default to "all" - if relayReflector := os.Getenv("ENABLE_RELAY_REFLECTOR"); relayReflector != "" { - switch relayReflector { - case "false", "disabled": - cfg.HttpRelayReflectorMode = RelayReflectorDisabled - case "registration": - cfg.HttpRelayReflectorMode = RelayReflectorRegistrationOnly - case "true", "all": - cfg.HttpRelayReflectorMode = RelayReflectorAllTraffic - case "traffic": - cfg.HttpRelayReflectorMode = RelayReflectorTrafficOnly - } - } - - // Default to true - WebSocket upgrade support in reflector - cfg.ReflectorWebSocketUpgrade = true - if wsUpgrade := os.Getenv("REFLECTOR_WEBSOCKET_UPGRADE"); wsUpgrade == "false" { - cfg.ReflectorWebSocketUpgrade = false - } - - cfg.RelayIdleTimeout = 10 * time.Minute - if relayIdleTimeout := os.Getenv("RELAY_IDLE_TIMEOUT"); relayIdleTimeout != "" { - rit, err := time.ParseDuration(relayIdleTimeout) - if err != nil { - panic(err) - } - cfg.RelayIdleTimeout = rit - } - - // AXON_RELAY_TRANSPORT is the documented name (design doc §10); - // RELAY_MODE is accepted as an alias. No default here: an unset mode - // must stay distinguishable from a customer choice. See RelayMode. - cfg.RelayMode = applyForcedRelayMode(envFirst("AXON_RELAY_TRANSPORT", "RELAY_MODE")) - cfg.TunnelConns = 4 if v := os.Getenv("AXON_GRPC_TUNNEL_CONNS"); v != "" { n, err := strconv.Atoi(v) diff --git a/agent/config/config_test.go b/agent/config/config_test.go index 5903affc..876f3f28 100644 --- a/agent/config/config_test.go +++ b/agent/config/config_test.go @@ -4,7 +4,6 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) // These pin the environment variables the tunnel actually reads. They exist @@ -72,60 +71,6 @@ func TestEnvConfig_GrpcTunnelServer(t *testing.T) { assert.Equal(t, "tunnel.example.com:443", NewAgentEnvConfig().GrpcTunnelServer) } -func TestEnvConfig_RelayModeSelectsTheTunnel(t *testing.T) { - t.Setenv("AXON_RELAY_TRANSPORT", "grpc-tunnel") - require.True(t, NewAgentEnvConfig().IsGRPCTunnel()) - - t.Setenv("AXON_RELAY_TRANSPORT", "snyk-broker") - require.False(t, NewAgentEnvConfig().IsGRPCTunnel()) -} - -// An unset mode stays empty, so that the agent can tell it from a customer -// choice and let Cortex select the mode. -func TestEnvConfig_RelayModeUnsetIsNotPinned(t *testing.T) { - t.Setenv("AXON_RELAY_TRANSPORT", "") - t.Setenv("RELAY_MODE", "") - cfg := NewAgentEnvConfig() - assert.Equal(t, "", cfg.RelayMode) - assert.False(t, cfg.RelayModePinned()) - - t.Setenv("AXON_RELAY_TRANSPORT", "snyk-broker") - assert.True(t, NewAgentEnvConfig().RelayModePinned()) -} - -func TestEnvConfig_RelayModeLegacyAlias(t *testing.T) { - t.Setenv("RELAY_MODE", "grpc-tunnel") - assert.True(t, NewAgentEnvConfig().IsGRPCTunnel()) -} - -// The go-only image stamps ForcedRelayMode at build time; see its doc comment. -func forceRelayMode(t *testing.T, mode string) { - prev := ForcedRelayMode - ForcedRelayMode = mode - t.Cleanup(func() { ForcedRelayMode = prev }) -} - -func TestEnvConfig_ForcedRelayModeIsTheDefault(t *testing.T) { - forceRelayMode(t, "grpc-tunnel") - assert.True(t, NewAgentEnvConfig().IsGRPCTunnel(), "no env set must still run the forced mode") - - t.Setenv("AXON_RELAY_TRANSPORT", "grpc-tunnel") - assert.True(t, NewAgentEnvConfig().IsGRPCTunnel()) -} - -func TestEnvConfig_ForcedRelayModeRejectsOtherModes(t *testing.T) { - forceRelayMode(t, "grpc-tunnel") - - t.Setenv("AXON_RELAY_TRANSPORT", "snyk-broker") - assert.PanicsWithValue(t, - `this build only supports AXON_RELAY_TRANSPORT=grpc-tunnel, got "snyk-broker"`, - func() { NewAgentEnvConfig() }) - - t.Setenv("AXON_RELAY_TRANSPORT", "") - t.Setenv("RELAY_MODE", "snyk-broker") - assert.Panics(t, func() { NewAgentEnvConfig() }, "the legacy alias must not bypass the pin") -} - func TestEnvConfig_MaxRequestTimeout(t *testing.T) { t.Setenv("AXON_GRPC_TUNNEL_MAX_REQUEST_TIMEOUT", "90s") assert.Equal(t, "1m30s", NewAgentEnvConfig().MaxRequestTimeout.String()) diff --git a/agent/go.mod b/agent/go.mod index 5d0059ae..443dfe24 100644 --- a/agent/go.mod +++ b/agent/go.mod @@ -7,7 +7,6 @@ toolchain go1.26.11 require ( github.com/google/uuid v1.6.0 github.com/gorilla/mux v1.8.1 - github.com/gorilla/websocket v1.5.3 github.com/prometheus/client_golang v1.22.0 github.com/prometheus/client_model v0.6.1 github.com/robfig/cron/v3 v3.0.0 diff --git a/agent/go.sum b/agent/go.sum index cc3dfecb..e2b9b3e2 100644 --- a/agent/go.sum +++ b/agent/go.sum @@ -17,8 +17,6 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= -github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= -github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= diff --git a/agent/server/snykbroker/acceptfile/accept_file.go b/agent/server/acceptfile/accept_file.go similarity index 90% rename from agent/server/snykbroker/acceptfile/accept_file.go rename to agent/server/acceptfile/accept_file.go index eabed576..8ecc3a99 100644 --- a/agent/server/snykbroker/acceptfile/accept_file.go +++ b/agent/server/acceptfile/accept_file.go @@ -11,10 +11,9 @@ import ( "go.uber.org/zap" ) -// AcceptFile is an abstraction over the Snyk Broker "accept.json" format. -// It owns manipulating a raw file into one that is customized for Axon including -// adding the Axon rules, and doing replacements for the reflector (eg all traffic is sent through the agent -// instead of directly to the target), as well as adding support for adding outbound headers. +// AcceptFile is an abstraction over the "accept.json" format, which comes from +// Snyk Broker. It owns manipulating a raw file into one that is customized for +// Axon, including adding the Axon rules and support for outbound headers. type AcceptFile struct { wrapper acceptFileWrapper content []byte @@ -51,11 +50,11 @@ func NewAcceptFile(content []byte, cfg config.AgentConfig, logger *zap.Logger) ( } af.wrapper = newAcceptFileWrapper(processedContent, af) - // Deliberately no strict validation here. Parsing an accept file is shared - // with the snyk-broker path, where the Node broker honours constructs this - // package does not — refusing them here would break a deployment that - // works today. The Router warns about them when it is built instead, where - // they would otherwise be silently dropped. + // Deliberately no strict validation here. Accept files can carry + // constructs that snyk-broker honoured and this package does not, and + // refusing them here would stop a deployment that works today. The Router + // warns about them when it is built instead, where they would otherwise + // be silently dropped. warnIgnoredPublicRules(af.wrapper.dict, af.logger) return af, nil } @@ -72,27 +71,22 @@ type RenderContext struct { type RenderStep func(renderContext RenderContext) error -var IgnoreHosts = []string{ - "localhost", - "127.0.0.1", -} - const RULES_PRIVATE = "private" const RULES_PUBLIC = "public" -// Render renders the accept file by applying Axon updates plus any additional render steps provided. +// Render renders the accept file by applying the Axon updates. // It returns the rendered JSON content of the accept file. -func (a *AcceptFile) Render(logger *zap.Logger, extraRenderSteps ...RenderStep) ([]byte, error) { +func (a *AcceptFile) Render(logger *zap.Logger) ([]byte, error) { renderContext := RenderContext{ Logger: logger, AcceptFile: newAcceptFileWrapper(a.content, a), } - renderSteps := append([]RenderStep{ + renderSteps := []RenderStep{ a.ensurePublicAndPrivate, a.addAxonRoute, - }, extraRenderSteps...) + } for _, step := range renderSteps { if err := step(renderContext); err != nil { @@ -266,10 +260,6 @@ func (r AcceptFileRuleWrapper) RawOrigin() string { return origin } -func (r AcceptFileRuleWrapper) SetOrigin(origin string) { - r.dict["origin"] = origin -} - func (r AcceptFileRuleWrapper) Method() string { method, ok := r.dict["method"].(string) if !ok { diff --git a/agent/server/snykbroker/acceptfile/accept_file_gitlab_test.go b/agent/server/acceptfile/accept_file_gitlab_test.go similarity index 96% rename from agent/server/snykbroker/acceptfile/accept_file_gitlab_test.go rename to agent/server/acceptfile/accept_file_gitlab_test.go index dbde1546..f60f3ffc 100644 --- a/agent/server/snykbroker/acceptfile/accept_file_gitlab_test.go +++ b/agent/server/acceptfile/accept_file_gitlab_test.go @@ -36,7 +36,7 @@ type builtinAcceptFile struct { // /info/refs?service=git-upload-pack. This mirrors the allowlist proven to fix // Fiserv's NA agent (CD-219). func TestGitlabAcceptFileHasScaffolderRules(t *testing.T) { - contents, err := os.ReadFile(filepath.Join("..", "accept_files", "accept.gitlab.json")) + contents, err := os.ReadFile(filepath.Join("accept_files", "accept.gitlab.json")) require.NoError(t, err) var af builtinAcceptFile diff --git a/agent/server/snykbroker/acceptfile/accept_file_test.go b/agent/server/acceptfile/accept_file_test.go similarity index 80% rename from agent/server/snykbroker/acceptfile/accept_file_test.go rename to agent/server/acceptfile/accept_file_test.go index 5f630716..1af494c2 100644 --- a/agent/server/snykbroker/acceptfile/accept_file_test.go +++ b/agent/server/acceptfile/accept_file_test.go @@ -152,34 +152,6 @@ func TestRenderEnvVars(t *testing.T) { require.Equal(t, expected, string(rendered), "Rendered accept file does not match expected output") } -func TestExtraRenderSteps(t *testing.T) { - acceptFileContents := `{ - - "private": [ - {"method": "GET", "origin": "http://localhost:9999", "path": "/private/*"} - ] - }` - cfg := axonConfig.NewAgentEnvConfig() - cfg.HttpServerPort = 9999 - logger := zap.NewNop() - acceptFile, err := NewAcceptFile([]byte(acceptFileContents), cfg, nil) - require.NoError(t, err) - - rendered, err := acceptFile.Render(logger, func(renderContext RenderContext) error { - - for _, entry := range renderContext.AcceptFile.PrivateRules() { - if !strings.Contains(entry.Path(), "axon") { - entry.SetOrigin("http://localhost:8888") - } - } - return nil - }) - require.NoError(t, err) - require.NotEmpty(t, rendered) - expected := `{"private":[{"method":"any","origin":"http://localhost:9999","path":"/__axon/*"},{"method":"GET","origin":"http://localhost:8888","path":"/private/*"}],"public":[]}` - require.Equal(t, expected, string(rendered), "Rendered accept file does not match expected output") -} - func TestPreProcessContent(t *testing.T) { content := `{ "$vars":[ diff --git a/agent/server/snykbroker/accept_files/accept.bitbucket.basic.json b/agent/server/acceptfile/accept_files/accept.bitbucket.basic.json similarity index 100% rename from agent/server/snykbroker/accept_files/accept.bitbucket.basic.json rename to agent/server/acceptfile/accept_files/accept.bitbucket.basic.json diff --git a/agent/server/snykbroker/accept_files/accept.bitbucket.json b/agent/server/acceptfile/accept_files/accept.bitbucket.json similarity index 100% rename from agent/server/snykbroker/accept_files/accept.bitbucket.json rename to agent/server/acceptfile/accept_files/accept.bitbucket.json diff --git a/agent/server/snykbroker/accept_files/accept.github.app.json b/agent/server/acceptfile/accept_files/accept.github.app.json similarity index 100% rename from agent/server/snykbroker/accept_files/accept.github.app.json rename to agent/server/acceptfile/accept_files/accept.github.app.json diff --git a/agent/server/snykbroker/accept_files/accept.github.json b/agent/server/acceptfile/accept_files/accept.github.json similarity index 100% rename from agent/server/snykbroker/accept_files/accept.github.json rename to agent/server/acceptfile/accept_files/accept.github.json diff --git a/agent/server/snykbroker/accept_files/accept.gitlab.json b/agent/server/acceptfile/accept_files/accept.gitlab.json similarity index 100% rename from agent/server/snykbroker/accept_files/accept.gitlab.json rename to agent/server/acceptfile/accept_files/accept.gitlab.json diff --git a/agent/server/snykbroker/accept_files/accept.google.json b/agent/server/acceptfile/accept_files/accept.google.json similarity index 100% rename from agent/server/snykbroker/accept_files/accept.google.json rename to agent/server/acceptfile/accept_files/accept.google.json diff --git a/agent/server/snykbroker/accept_files/accept.harness.json b/agent/server/acceptfile/accept_files/accept.harness.json similarity index 100% rename from agent/server/snykbroker/accept_files/accept.harness.json rename to agent/server/acceptfile/accept_files/accept.harness.json diff --git a/agent/server/snykbroker/accept_files/accept.jira.bearer.json b/agent/server/acceptfile/accept_files/accept.jira.bearer.json similarity index 100% rename from agent/server/snykbroker/accept_files/accept.jira.bearer.json rename to agent/server/acceptfile/accept_files/accept.jira.bearer.json diff --git a/agent/server/snykbroker/accept_files/accept.jira.json b/agent/server/acceptfile/accept_files/accept.jira.json similarity index 100% rename from agent/server/snykbroker/accept_files/accept.jira.json rename to agent/server/acceptfile/accept_files/accept.jira.json diff --git a/agent/server/snykbroker/accept_files/accept.prometheus.json b/agent/server/acceptfile/accept_files/accept.prometheus.json similarity index 100% rename from agent/server/snykbroker/accept_files/accept.prometheus.json rename to agent/server/acceptfile/accept_files/accept.prometheus.json diff --git a/agent/server/snykbroker/accept_files/accept.sonarqube.json b/agent/server/acceptfile/accept_files/accept.sonarqube.json similarity index 100% rename from agent/server/snykbroker/accept_files/accept.sonarqube.json rename to agent/server/acceptfile/accept_files/accept.sonarqube.json diff --git a/agent/server/snykbroker/accept_files/config.bitbucket.json b/agent/server/acceptfile/accept_files/config.bitbucket.json similarity index 100% rename from agent/server/snykbroker/accept_files/config.bitbucket.json rename to agent/server/acceptfile/accept_files/config.bitbucket.json diff --git a/agent/server/snykbroker/accept_files/config.github.json b/agent/server/acceptfile/accept_files/config.github.json similarity index 100% rename from agent/server/snykbroker/accept_files/config.github.json rename to agent/server/acceptfile/accept_files/config.github.json diff --git a/agent/server/snykbroker/accept_files/config.gitlab.json b/agent/server/acceptfile/accept_files/config.gitlab.json similarity index 100% rename from agent/server/snykbroker/accept_files/config.gitlab.json rename to agent/server/acceptfile/accept_files/config.gitlab.json diff --git a/agent/server/snykbroker/accept_files/config.harness.json b/agent/server/acceptfile/accept_files/config.harness.json similarity index 100% rename from agent/server/snykbroker/accept_files/config.harness.json rename to agent/server/acceptfile/accept_files/config.harness.json diff --git a/agent/server/snykbroker/accept_files/config.jira.json b/agent/server/acceptfile/accept_files/config.jira.json similarity index 100% rename from agent/server/snykbroker/accept_files/config.jira.json rename to agent/server/acceptfile/accept_files/config.jira.json diff --git a/agent/server/snykbroker/acceptfile/accept_google_test.go b/agent/server/acceptfile/accept_google_test.go similarity index 87% rename from agent/server/snykbroker/acceptfile/accept_google_test.go rename to agent/server/acceptfile/accept_google_test.go index abf2c78d..fc01e6b6 100644 --- a/agent/server/snykbroker/acceptfile/accept_google_test.go +++ b/agent/server/acceptfile/accept_google_test.go @@ -13,8 +13,7 @@ import ( // googleTemplateOrigin returns the origin the shipped google template resolves to. // // Origin() rather than the rendered JSON, because the rendered file keeps -// ${GOOGLE_API} for the broker to expand. Origin() is what the reflector builds -// its proxy target from. +// ${GOOGLE_API} unexpanded. // // The google-adc stub is required: Headers() locates the plugin and panics if it // cannot, and a real binary would tie the result to the machine's identity. @@ -25,7 +24,7 @@ func googleTemplateOrigin(t *testing.T) string { require.NoError(t, os.WriteFile(filepath.Join(pluginDir, "google-adc"), []byte("#!/bin/sh\nprintf 'Bearer stub'\n"), 0700)) - content, err := os.ReadFile(filepath.Join("..", "accept_files", "accept.google.json")) + content, err := os.ReadFile(filepath.Join("accept_files", "accept.google.json")) require.NoError(t, err) cfg := axonConfig.AgentConfig{HttpServerPort: 80, PluginDirs: []string{pluginDir}} @@ -56,7 +55,7 @@ func TestGoogleTemplateOriginCanBeOverridden(t *testing.T) { } func TestGoogleTemplateUsesThePluginForAuthorization(t *testing.T) { - content, err := os.ReadFile(filepath.Join("..", "accept_files", "accept.google.json")) + content, err := os.ReadFile(filepath.Join("accept_files", "accept.google.json")) require.NoError(t, err) require.Contains(t, string(content), "${plugin:google-adc}") } diff --git a/agent/server/snykbroker/acceptfile/auth.go b/agent/server/acceptfile/auth.go similarity index 100% rename from agent/server/snykbroker/acceptfile/auth.go rename to agent/server/acceptfile/auth.go diff --git a/agent/server/snykbroker/acceptfile/headers.go b/agent/server/acceptfile/headers.go similarity index 100% rename from agent/server/snykbroker/acceptfile/headers.go rename to agent/server/acceptfile/headers.go diff --git a/agent/server/snykbroker/acceptfile/helpers_test.go b/agent/server/acceptfile/helpers_test.go similarity index 100% rename from agent/server/snykbroker/acceptfile/helpers_test.go rename to agent/server/acceptfile/helpers_test.go diff --git a/agent/server/snykbroker/acceptfile/matcher.go b/agent/server/acceptfile/matcher.go similarity index 92% rename from agent/server/snykbroker/acceptfile/matcher.go rename to agent/server/acceptfile/matcher.go index 735a03f8..ce55b388 100644 --- a/agent/server/snykbroker/acceptfile/matcher.go +++ b/agent/server/acceptfile/matcher.go @@ -8,18 +8,13 @@ import ( "sync" ) -// Rule matching runs on the gRPC tunnel path only. +// Rule matching. The one non-test caller is acceptfile.Router, which the +// tunnel client builds. // -// Despite living under snykbroker/, nothing in this file is consulted when the -// relay runs through snyk-broker: there the Node broker matches the rendered -// accept file itself, and the agent only hands it the file. The one non-test -// caller is acceptfile.Router, which the tunnel client builds. -// -// It is written to agree with the broker's matcher anyway — path-to-regexp +// It is written to agree with snyk-broker's matcher — path-to-regexp // wildcards, the GET default, traversal and fragment handling — because -// enabling the tunnel switches deployments that are running on snyk-broker -// today, and a rule that selected one origin there has to select the same one -// here. +// deployments that moved from snyk-broker keep their accept files, and a rule +// that selected one origin there has to select the same one here. // MatchRule finds the first accept file rule that matches the given HTTP method, path, and headers. // Returns nil if no rule matches. diff --git a/agent/server/snykbroker/acceptfile/matcher_parity_test.go b/agent/server/acceptfile/matcher_parity_test.go similarity index 97% rename from agent/server/snykbroker/acceptfile/matcher_parity_test.go rename to agent/server/acceptfile/matcher_parity_test.go index b7091245..87d59e0b 100644 --- a/agent/server/snykbroker/acceptfile/matcher_parity_test.go +++ b/agent/server/acceptfile/matcher_parity_test.go @@ -68,7 +68,7 @@ func TestGitlabTemplateMatchesNestedGroups(t *testing.T) { for _, v := range []string{"GITLAB_API", "GITLAB_TOKEN"} { t.Setenv(v, "https://gitlab.example") } - content, err := os.ReadFile(filepath.Join("..", "accept_files", "accept.gitlab.json")) + content, err := os.ReadFile(filepath.Join("accept_files", "accept.gitlab.json")) require.NoError(t, err) rt := newTestRouter(t, string(content)) @@ -114,8 +114,8 @@ func hasBasicAuth(v string) bool { // An earlier revision of this branch pinned the segment to the configured value // instead, which reads better as an allowlist but is not what the broker does — // a request the broker rewrote and forwarded would have 404'd on the tunnel. -// Enabling the tunnel switches deployments that are running on snyk-broker -// today, so the quirk has to come with them. +// Deployments that moved from snyk-broker keep their accept files, so the +// quirk has to come with them. func TestPathEnvVarMatchesAnySegmentAndRewrites(t *testing.T) { t.Setenv("GITHUB_ORG", "acme") t.Setenv("UPSTREAM", "https://up.example") diff --git a/agent/server/snykbroker/acceptfile/matcher_test.go b/agent/server/acceptfile/matcher_test.go similarity index 100% rename from agent/server/snykbroker/acceptfile/matcher_test.go rename to agent/server/acceptfile/matcher_test.go diff --git a/agent/server/snykbroker/acceptfile/origin.go b/agent/server/acceptfile/origin.go similarity index 100% rename from agent/server/snykbroker/acceptfile/origin.go rename to agent/server/acceptfile/origin.go diff --git a/agent/server/snykbroker/acceptfile/origin_test.go b/agent/server/acceptfile/origin_test.go similarity index 94% rename from agent/server/snykbroker/acceptfile/origin_test.go rename to agent/server/acceptfile/origin_test.go index f67e46be..29173fa8 100644 --- a/agent/server/snykbroker/acceptfile/origin_test.go +++ b/agent/server/acceptfile/origin_test.go @@ -7,11 +7,8 @@ import ( "github.com/stretchr/testify/require" ) -// These mirror the reflector's wildcard-origin suite -// (server/snykbroker/reflector_dynamic_target_test.go) case for case, against -// the Router's own implementation. The Router is the authoritative accept-file -// engine; the reflector keeps its copy until it is rerouted through this one, -// and until then the two suites are how we know they agree. +// Wildcard-origin parsing and policy for the Router, the authoritative +// accept-file engine. func TestParseOriginAcceptsWildcardFamilies(t *testing.T) { for _, origin := range []string{ diff --git a/agent/server/snykbroker/acceptfile/plugin.go b/agent/server/acceptfile/plugin.go similarity index 100% rename from agent/server/snykbroker/acceptfile/plugin.go rename to agent/server/acceptfile/plugin.go diff --git a/agent/server/snykbroker/acceptfile/plugin.sh b/agent/server/acceptfile/plugin.sh similarity index 100% rename from agent/server/snykbroker/acceptfile/plugin.sh rename to agent/server/acceptfile/plugin.sh diff --git a/agent/server/snykbroker/acceptfile/plugin_fail.sh b/agent/server/acceptfile/plugin_fail.sh similarity index 100% rename from agent/server/snykbroker/acceptfile/plugin_fail.sh rename to agent/server/acceptfile/plugin_fail.sh diff --git a/agent/server/snykbroker/acceptfile/plugin_test.go b/agent/server/acceptfile/plugin_test.go similarity index 100% rename from agent/server/snykbroker/acceptfile/plugin_test.go rename to agent/server/acceptfile/plugin_test.go diff --git a/agent/server/snykbroker/plugins/github-app-scaffolder b/agent/server/acceptfile/plugins/github-app-scaffolder similarity index 100% rename from agent/server/snykbroker/plugins/github-app-scaffolder rename to agent/server/acceptfile/plugins/github-app-scaffolder diff --git a/agent/server/snykbroker/plugins/github-app-token b/agent/server/acceptfile/plugins/github-app-token similarity index 100% rename from agent/server/snykbroker/plugins/github-app-token rename to agent/server/acceptfile/plugins/github-app-token diff --git a/agent/server/snykbroker/acceptfile/pool.go b/agent/server/acceptfile/pool.go similarity index 100% rename from agent/server/snykbroker/acceptfile/pool.go rename to agent/server/acceptfile/pool.go diff --git a/agent/server/snykbroker/acceptfile/pool_test.go b/agent/server/acceptfile/pool_test.go similarity index 100% rename from agent/server/snykbroker/acceptfile/pool_test.go rename to agent/server/acceptfile/pool_test.go diff --git a/agent/server/snykbroker/acceptfile/render_golden_test.go b/agent/server/acceptfile/render_golden_test.go similarity index 93% rename from agent/server/snykbroker/acceptfile/render_golden_test.go rename to agent/server/acceptfile/render_golden_test.go index acb30a4c..b65d10a6 100644 --- a/agent/server/snykbroker/acceptfile/render_golden_test.go +++ b/agent/server/acceptfile/render_golden_test.go @@ -36,12 +36,12 @@ var reFileVar = regexp.MustCompile(`\$\{([A-Z][A-Z0-9_]*)(?::[^}]*)?\}`) // TestRenderGolden pins the rendered output of every built-in accept file. // Any change to the acceptfile package that alters rendered output for -// existing accept files fails this test — additions for the gRPC tunnel -// must be invisible to the snyk-broker path (design doc §9). +// existing accept files fails this test, so a change in rendered output is +// always deliberate (design doc §9). // // Update intentionally with: // -// go test ./server/snykbroker/acceptfile/ -run TestRenderGolden -update-golden +// go test ./server/acceptfile/ -run TestRenderGolden -update-golden func TestRenderGolden(t *testing.T) { files := builtinAcceptFiles(t) require.NotEmpty(t, files, "no built-in accept files found") @@ -102,7 +102,7 @@ func TestRenderGolden(t *testing.T) { // glob — every file present there is tracked by definition. func builtinAcceptFiles(t *testing.T) []string { t.Helper() - dir := filepath.Join("..", "accept_files") + dir := filepath.Join("accept_files") out, err := exec.Command("git", "-C", dir, "ls-files", "--", "accept.*.json").Output() if err != nil { diff --git a/agent/server/snykbroker/acceptfile/resolver.go b/agent/server/acceptfile/resolver.go similarity index 100% rename from agent/server/snykbroker/acceptfile/resolver.go rename to agent/server/acceptfile/resolver.go diff --git a/agent/server/snykbroker/acceptfile/router.go b/agent/server/acceptfile/router.go similarity index 93% rename from agent/server/snykbroker/acceptfile/router.go rename to agent/server/acceptfile/router.go index c7636826..35386951 100644 --- a/agent/server/snykbroker/acceptfile/router.go +++ b/agent/server/acceptfile/router.go @@ -36,8 +36,7 @@ type RoutedRequest struct { // rendered accept file rules: rule matching, origin/pool resolution, // wildcard-origin retargeting, target URL construction, and header/auth // injection. It is the authoritative implementation of accept-file -// semantics; the snyk-broker reflector keeps its own copy of the wildcard -// policy until it is rerouted through this one. +// semantics. type Router struct { rules []AcceptFileRuleWrapper pools *PoolManager @@ -70,15 +69,15 @@ func NewRouter(rules []AcceptFileRuleWrapper, logger *zap.Logger) (*Router, erro continue } // A malformed wildcard origin is the one thing that stops the agent. - // The snyk-broker path refuses it too — at render, or by panicking when - // the reflector is off — so no working deployment has one, and treating - // a bad family as permissive would authorize hosts nobody chose. + // snyk-broker refused it too, so no working deployment has one, and + // treating a bad family as permissive would authorize hosts nobody + // chose. parsed, err := parseOrigin(origin) if err != nil { return nil, fmt.Errorf("accept file rule %q: %w", rule.Path(), err) } // Anything else about the origin is left to fail per request, the way - // it does on the snyk-broker path, rather than at startup. + // it did under snyk-broker, rather than at startup. if parsed.url.Scheme == "" || parsed.url.Host == "" { rt.logger.Warn("Accept file rule has an origin with no scheme or host; "+ "requests matching it will fail to route", @@ -185,10 +184,9 @@ func (rt *Router) Route(method, rawPath string, headers map[string]string) (*Rou // A credential provider that fails has to stop the request rather than // let its placeholder travel upstream as the credential — the refusal // then comes back as an authorization failure and names the wrong - // culprit, which is the thing #127 set out to stop. The reflector's - // serve() answers 502 here; returning an error lands in the default - // arm of grpctunnel's RouteError mapping, which is also a 502, so both - // transports refuse the same way. + // culprit, which is the thing #127 set out to stop. Returning an error + // lands in the default arm of grpctunnel's RouteError mapping, which + // is a 502. resolved, err := ruleHeaders.ToStringMap() if err != nil { rt.logger.Error("Credential provider failed", diff --git a/agent/server/snykbroker/acceptfile/router_auth_test.go b/agent/server/acceptfile/router_auth_test.go similarity index 100% rename from agent/server/snykbroker/acceptfile/router_auth_test.go rename to agent/server/acceptfile/router_auth_test.go diff --git a/agent/server/snykbroker/acceptfile/router_credential_test.go b/agent/server/acceptfile/router_credential_test.go similarity index 85% rename from agent/server/snykbroker/acceptfile/router_credential_test.go rename to agent/server/acceptfile/router_credential_test.go index 0c9d86bc..605ee13c 100644 --- a/agent/server/snykbroker/acceptfile/router_credential_test.go +++ b/agent/server/acceptfile/router_credential_test.go @@ -9,13 +9,11 @@ import ( // A credential provider that fails has to refuse the request, not let its // placeholder travel upstream as the credential — the upstream then refuses on // authorization and the log names the wrong culprit. #127 made ResolverMap -// report that failure instead of swallowing it, and taught the reflector's -// serve() to answer 502. This pins the same behaviour on the tunnel path, -// which reads the same ResolverMap through Router.Route. +// report that failure instead of swallowing it. This pins that behaviour on +// the tunnel path, which reads the ResolverMap through Router.Route. // // Route returns a plain error here rather than a classified one, which is what -// puts it in the default arm of grpctunnel's RouteError mapping — a 502, the -// same status the reflector sends. +// puts it in the default arm of grpctunnel's RouteError mapping — a 502. func TestRouteRefusesWhenACredentialProviderFails(t *testing.T) { router := newTestRouter(t, `{"private":[{ "method": "any", diff --git a/agent/server/snykbroker/acceptfile/router_pool_test.go b/agent/server/acceptfile/router_pool_test.go similarity index 100% rename from agent/server/snykbroker/acceptfile/router_pool_test.go rename to agent/server/acceptfile/router_pool_test.go diff --git a/agent/server/snykbroker/acceptfile/router_test.go b/agent/server/acceptfile/router_test.go similarity index 100% rename from agent/server/snykbroker/acceptfile/router_test.go rename to agent/server/acceptfile/router_test.go diff --git a/agent/server/snykbroker/acceptfile/router_wildcard_test.go b/agent/server/acceptfile/router_wildcard_test.go similarity index 99% rename from agent/server/snykbroker/acceptfile/router_wildcard_test.go rename to agent/server/acceptfile/router_wildcard_test.go index 05233f19..c0948e74 100644 --- a/agent/server/snykbroker/acceptfile/router_wildcard_test.go +++ b/agent/server/acceptfile/router_wildcard_test.go @@ -229,7 +229,7 @@ func TestGoogleTemplateRoutesThroughTheWildcardFamily(t *testing.T) { require.NoError(t, os.WriteFile(filepath.Join(pluginDir, "google-adc"), []byte("#!/bin/sh\nprintf 'Bearer stub-token'\n"), 0700)) - content, err := os.ReadFile(filepath.Join("..", "accept_files", "accept.google.json")) + content, err := os.ReadFile(filepath.Join("accept_files", "accept.google.json")) require.NoError(t, err) rt := newTestRouter(t, string(content), pluginDir) diff --git a/agent/server/snykbroker/acceptfile/supported.go b/agent/server/acceptfile/supported.go similarity index 84% rename from agent/server/snykbroker/acceptfile/supported.go rename to agent/server/acceptfile/supported.go index e0c27b36..3db64651 100644 --- a/agent/server/snykbroker/acceptfile/supported.go +++ b/agent/server/acceptfile/supported.go @@ -8,11 +8,10 @@ import ( // Nothing in an accept file stops the agent. // -// Enabling the tunnel switches deployments that are running on snyk-broker -// today, and that switch has to be transparent: a file the broker accepts must -// still start. Anything the Router cannot carry is warned about and ignored, so -// an operator relying on it finds out from the log rather than from an agent -// that will not boot, and can stay on snyk-broker until we implement it. +// Deployments that moved from snyk-broker keep their accept files, so a file +// the broker accepted must still start. Anything the Router cannot carry is +// warned about and ignored, so an operator relying on it finds out from the +// log rather than from an agent that will not boot. // // Two classes end up here: // @@ -25,10 +24,9 @@ import ( // assumes a credential went out. // // The one thing still refused is a malformed wildcard origin, and that is not a -// migration risk: the snyk-broker path already refuses it too, at render -// (ErrWildcardOriginRequiresTLSVerification, the invalid-origin error) or by -// panicking when the reflector is disabled. No working deployment has one, and -// treating a bad family as permissive would authorize hosts nobody chose. +// migration risk: snyk-broker refused it too, so no working deployment has +// one, and treating a bad family as permissive would authorize hosts nobody +// chose. // warnIgnoredPublicRules logs once for an accept file that declares inbound // rules, and reports how many it found. diff --git a/agent/server/snykbroker/acceptfile/testdata/render_golden/accept.bitbucket.basic.golden.json b/agent/server/acceptfile/testdata/render_golden/accept.bitbucket.basic.golden.json similarity index 100% rename from agent/server/snykbroker/acceptfile/testdata/render_golden/accept.bitbucket.basic.golden.json rename to agent/server/acceptfile/testdata/render_golden/accept.bitbucket.basic.golden.json diff --git a/agent/server/snykbroker/acceptfile/testdata/render_golden/accept.bitbucket.golden.json b/agent/server/acceptfile/testdata/render_golden/accept.bitbucket.golden.json similarity index 100% rename from agent/server/snykbroker/acceptfile/testdata/render_golden/accept.bitbucket.golden.json rename to agent/server/acceptfile/testdata/render_golden/accept.bitbucket.golden.json diff --git a/agent/server/snykbroker/acceptfile/testdata/render_golden/accept.github.app.golden.json b/agent/server/acceptfile/testdata/render_golden/accept.github.app.golden.json similarity index 100% rename from agent/server/snykbroker/acceptfile/testdata/render_golden/accept.github.app.golden.json rename to agent/server/acceptfile/testdata/render_golden/accept.github.app.golden.json diff --git a/agent/server/snykbroker/acceptfile/testdata/render_golden/accept.github.golden.json b/agent/server/acceptfile/testdata/render_golden/accept.github.golden.json similarity index 100% rename from agent/server/snykbroker/acceptfile/testdata/render_golden/accept.github.golden.json rename to agent/server/acceptfile/testdata/render_golden/accept.github.golden.json diff --git a/agent/server/snykbroker/acceptfile/testdata/render_golden/accept.gitlab.golden.json b/agent/server/acceptfile/testdata/render_golden/accept.gitlab.golden.json similarity index 100% rename from agent/server/snykbroker/acceptfile/testdata/render_golden/accept.gitlab.golden.json rename to agent/server/acceptfile/testdata/render_golden/accept.gitlab.golden.json diff --git a/agent/server/snykbroker/acceptfile/testdata/render_golden/accept.harness.golden.json b/agent/server/acceptfile/testdata/render_golden/accept.harness.golden.json similarity index 100% rename from agent/server/snykbroker/acceptfile/testdata/render_golden/accept.harness.golden.json rename to agent/server/acceptfile/testdata/render_golden/accept.harness.golden.json diff --git a/agent/server/snykbroker/acceptfile/testdata/render_golden/accept.jira.bearer.golden.json b/agent/server/acceptfile/testdata/render_golden/accept.jira.bearer.golden.json similarity index 100% rename from agent/server/snykbroker/acceptfile/testdata/render_golden/accept.jira.bearer.golden.json rename to agent/server/acceptfile/testdata/render_golden/accept.jira.bearer.golden.json diff --git a/agent/server/snykbroker/acceptfile/testdata/render_golden/accept.jira.golden.json b/agent/server/acceptfile/testdata/render_golden/accept.jira.golden.json similarity index 100% rename from agent/server/snykbroker/acceptfile/testdata/render_golden/accept.jira.golden.json rename to agent/server/acceptfile/testdata/render_golden/accept.jira.golden.json diff --git a/agent/server/snykbroker/acceptfile/testdata/render_golden/accept.prometheus.golden.json b/agent/server/acceptfile/testdata/render_golden/accept.prometheus.golden.json similarity index 100% rename from agent/server/snykbroker/acceptfile/testdata/render_golden/accept.prometheus.golden.json rename to agent/server/acceptfile/testdata/render_golden/accept.prometheus.golden.json diff --git a/agent/server/snykbroker/acceptfile/testdata/render_golden/accept.sonarqube.golden.json b/agent/server/acceptfile/testdata/render_golden/accept.sonarqube.golden.json similarity index 100% rename from agent/server/snykbroker/acceptfile/testdata/render_golden/accept.sonarqube.golden.json rename to agent/server/acceptfile/testdata/render_golden/accept.sonarqube.golden.json diff --git a/agent/server/snykbroker/acceptfile/unsupported_test.go b/agent/server/acceptfile/unsupported_test.go similarity index 96% rename from agent/server/snykbroker/acceptfile/unsupported_test.go rename to agent/server/acceptfile/unsupported_test.go index c1b2050f..e205327d 100644 --- a/agent/server/snykbroker/acceptfile/unsupported_test.go +++ b/agent/server/acceptfile/unsupported_test.go @@ -16,13 +16,13 @@ import ( // Nothing in an accept file stops the agent. // -// Enabling the tunnel switches deployments running on snyk-broker today, and -// that switch has to be transparent: a file the broker accepts must still -// start. Anything the Router cannot carry is warned about and ignored. +// Deployments that moved from snyk-broker keep their accept files, so a file +// the broker accepted must still start. Anything the Router cannot carry is +// warned about and ignored. // // The one exception is a malformed wildcard origin, covered in -// router_wildcard_test.go — the snyk-broker path refuses that too, so no -// working deployment has one. +// router_wildcard_test.go — snyk-broker refused that too, so no working +// deployment has one. // loadWithLogs parses an accept file with a logger the test can inspect. func loadWithLogs(t *testing.T, content string) (*AcceptFile, []observer.LoggedEntry, error) { @@ -314,8 +314,8 @@ func acceptFilesUnderTest(t *testing.T) []string { t.Helper() files := builtinAcceptFiles(t) for _, fixture := range []string{ - filepath.Join("..", "..", "..", "test", "relay", "accept-client.json"), - filepath.Join("..", "..", "..", "test", "load", "accept-load.json"), + filepath.Join("..", "..", "test", "relay", "accept-client.json"), + filepath.Join("..", "..", "test", "load", "accept-load.json"), } { require.FileExists(t, fixture) files = append(files, fixture) diff --git a/agent/server/grpctunnel/call_handler.go b/agent/server/grpctunnel/call_handler.go index 5763fa6f..18d5f156 100644 --- a/agent/server/grpctunnel/call_handler.go +++ b/agent/server/grpctunnel/call_handler.go @@ -300,11 +300,8 @@ func (tc *tunnelClient) runCall(ctx context.Context, sc *streamCtx, c *agentCall headers[strings.ToLower(k)] = strings.Join(v, ", ") } - // Identify which agent instance served this call. Under snyk-broker the - // reflector stamps this on the way out; the tunnel routes upstream - // traffic directly and never touches the reflector, so it has to add the - // header itself. Without it the two transports differ in exactly the - // place you would notice last: debugging which agent in a pool answered. + // Identify which agent instance served this call, so that it is possible + // to find which agent in a pool answered. if tc.config.InstanceId != "" { headers["x-axon-relay-instance"] = tc.config.InstanceId } diff --git a/agent/server/grpctunnel/call_report_test.go b/agent/server/grpctunnel/call_report_test.go index 27dc6635..1e2f8c55 100644 --- a/agent/server/grpctunnel/call_report_test.go +++ b/agent/server/grpctunnel/call_report_test.go @@ -7,7 +7,7 @@ import ( pb "github.com/cortexapps/axon/.generated/proto/github.com/cortexapps/axon/tunnelpb" "github.com/cortexapps/axon/config" - "github.com/cortexapps/axon/server/snykbroker/acceptfile" + "github.com/cortexapps/axon/server/acceptfile" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "go.uber.org/zap" diff --git a/agent/server/grpctunnel/conformance_test.go b/agent/server/grpctunnel/conformance_test.go index 410053aa..b9dfe0a1 100644 --- a/agent/server/grpctunnel/conformance_test.go +++ b/agent/server/grpctunnel/conformance_test.go @@ -9,7 +9,7 @@ import ( pb "github.com/cortexapps/axon/.generated/proto/github.com/cortexapps/axon/tunnelpb" "github.com/cortexapps/axon/config" - "github.com/cortexapps/axon/server/snykbroker/acceptfile" + "github.com/cortexapps/axon/server/acceptfile" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "go.uber.org/zap" @@ -17,9 +17,8 @@ import ( // TestAcceptFileConformance runs the shared accept-file conformance // fixtures (agent/test/conformance/) through the gRPC-tunnel path: -// accept-file render → Router.Route. The same fixtures are played through -// the snyk-broker E2E harness; together they pin both transports to one -// definition of accept-file semantics (design doc §9). +// accept-file render → Router.Route. They pin the tunnel to one definition +// of accept-file semantics (design doc §9). func TestAcceptFileConformance(t *testing.T) { fixtureDir := filepath.Join("..", "..", "test", "conformance") entries, err := os.ReadDir(fixtureDir) diff --git a/agent/server/grpctunnel/module.go b/agent/server/grpctunnel/module.go index e2153391..175f48fa 100644 --- a/agent/server/grpctunnel/module.go +++ b/agent/server/grpctunnel/module.go @@ -1,11 +1,10 @@ package grpctunnel import ( - "github.com/cortexapps/axon/server/snykbroker" "go.uber.org/fx" ) var Module = fx.Module("grpctunnel", - fx.Provide(snykbroker.NewRegistration), + fx.Provide(NewRegistration), fx.Invoke(NewTunnelClient), ) diff --git a/agent/server/grpctunnel/proxy_dialer.go b/agent/server/grpctunnel/proxy_dialer.go index 44afb7f4..dd44b3a0 100644 --- a/agent/server/grpctunnel/proxy_dialer.go +++ b/agent/server/grpctunnel/proxy_dialer.go @@ -28,8 +28,7 @@ func proxyURLFromEnv(targetAddr string, grpcInsecure bool) *url.URL { } // newProxyDialer returns a context dialer that tunnels through an HTTP -// CONNECT proxy. The CONNECT mechanics are shared with the relay -// reflector's WebSocket proxy via util.DialProxyConnect. +// CONNECT proxy. The CONNECT mechanics are in util.DialProxyConnect. func newProxyDialer(proxyURL *url.URL, logger *zap.Logger) func(ctx context.Context, addr string) (net.Conn, error) { return func(ctx context.Context, addr string) (net.Conn, error) { var proxyTLS *tls.Config diff --git a/agent/server/snykbroker/registration.go b/agent/server/grpctunnel/registration.go similarity index 92% rename from agent/server/snykbroker/registration.go rename to agent/server/grpctunnel/registration.go index 45d0518b..f14eaa5b 100644 --- a/agent/server/snykbroker/registration.go +++ b/agent/server/grpctunnel/registration.go @@ -1,4 +1,4 @@ -package snykbroker +package grpctunnel import ( "bytes" @@ -17,7 +17,7 @@ import ( // Registration is an interface for registering an integration with the Cortex API // Where the integration uses the Cortex API Key plus the integration+alias combo to -// receive a token and a server URI to be used for snyk-broker +// receive a token and a server URI to be used for the gRPC tunnel type Registration interface { Register(ctx context.Context, integration common.Integration, alias string) (*RegistrationInfoResponse, error) } @@ -48,7 +48,6 @@ func (e *RegistrationError) Unwrap() error { type registration struct { config config.AgentConfig - proxyPort int httpClient *http.Client } @@ -62,10 +61,6 @@ func NewRegistration(config config.AgentConfig, httpClient *http.Client) Registr } } -func (r *registration) SetProxyPort(port int) { - r.proxyPort = port -} - func (r *registration) Register(ctx context.Context, integration common.Integration, alias string) (*RegistrationInfoResponse, error) { if _, ok := ctx.Deadline(); !ok { var cancel context.CancelFunc @@ -144,9 +139,6 @@ func (r *registration) Register(ctx context.Context, integration common.Integrat type RegistrationInfoResponse struct { ServerUri string `json:"serverUri"` Token string `json:"token"` - // TunnelMode is the relay mode Cortex selects for this tenant: - // "snyk-broker" or "grpc-tunnel". Empty when Cortex has no preference. - TunnelMode string `json:"tunnelMode,omitempty"` } type registerRequest struct { diff --git a/agent/server/snykbroker/registration_test.go b/agent/server/grpctunnel/registration_test.go similarity index 89% rename from agent/server/snykbroker/registration_test.go rename to agent/server/grpctunnel/registration_test.go index b8d8cf94..85e1b85c 100644 --- a/agent/server/snykbroker/registration_test.go +++ b/agent/server/grpctunnel/registration_test.go @@ -1,4 +1,4 @@ -package snykbroker +package grpctunnel import ( "context" @@ -41,28 +41,6 @@ func TestRegister_Success(t *testing.T) { require.Equal(t, "http://example.com", resp.ServerUri) } -// Cortex sends tunnelMode only when a tenant has a preference. The field -// decodes when present, and stays empty when the response has no field. -func TestRegister_TunnelMode(t *testing.T) { - for _, tc := range []struct{ name, body, want string }{ - {"present", `{"serverUri":"http://example.com","token":"t","tunnelMode":"grpc-tunnel"}`, "grpc-tunnel"}, - {"absent", `{"serverUri":"http://example.com","token":"t"}`, ""}, - } { - t.Run(tc.name, func(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(tc.body)) - })) - defer server.Close() - - reg := NewRegistration(config.AgentConfig{CortexApiBaseUrl: server.URL, CortexApiToken: "test_token"}, nil) - resp, err := reg.Register(context.Background(), common.IntegrationGithub, "alias") - require.NoError(t, err) - require.Equal(t, tc.want, resp.TunnelMode) - }) - } -} - func TestRegister_Unauthorized(t *testing.T) { cfg := &config.AgentConfig{ diff --git a/agent/server/grpctunnel/response_header_test.go b/agent/server/grpctunnel/response_header_test.go index 4ab03165..a1213952 100644 --- a/agent/server/grpctunnel/response_header_test.go +++ b/agent/server/grpctunnel/response_header_test.go @@ -13,11 +13,9 @@ import ( "github.com/stretchr/testify/require" ) -// snyk-broker stamps x-axon-relay-instance through the reflector on the way -// out. The tunnel routes upstream traffic directly and never touches the -// reflector, so it has to add the header itself — and for a while it did not. -// No test caught it because the two transports were running different -// end-to-end suites, and the gRPC one had quietly lost this assertion. +// The tunnel stamps x-axon-relay-instance on every response, so that it is +// possible to find which agent in a pool answered. For a while it did not, +// and no test caught it. func TestResponse_CarriesRelayInstanceHeader(t *testing.T) { cfg := config.AgentConfig{MaxInflightRequests: 4, InstanceId: "agent-7"} tc, _ := newTestClient(t, cfg, &fakeRegistration{serverURI: "x", tokens: []string{"x"}}) diff --git a/agent/server/grpctunnel/router.go b/agent/server/grpctunnel/router.go index 8fb1b572..843149f0 100644 --- a/agent/server/grpctunnel/router.go +++ b/agent/server/grpctunnel/router.go @@ -5,7 +5,7 @@ import ( "net/http" pb "github.com/cortexapps/axon/.generated/proto/github.com/cortexapps/axon/tunnelpb" - "github.com/cortexapps/axon/server/snykbroker/acceptfile" + "github.com/cortexapps/axon/server/acceptfile" "go.uber.org/zap" ) diff --git a/agent/server/grpctunnel/router_test.go b/agent/server/grpctunnel/router_test.go index 9cf7c90b..fe11139c 100644 --- a/agent/server/grpctunnel/router_test.go +++ b/agent/server/grpctunnel/router_test.go @@ -11,7 +11,7 @@ import ( pb "github.com/cortexapps/axon/.generated/proto/github.com/cortexapps/axon/tunnelpb" "github.com/cortexapps/axon/config" - "github.com/cortexapps/axon/server/snykbroker/acceptfile" + "github.com/cortexapps/axon/server/acceptfile" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "go.uber.org/zap" diff --git a/agent/server/grpctunnel/tunnel_client.go b/agent/server/grpctunnel/tunnel_client.go index d2c00a45..08bcf93b 100644 --- a/agent/server/grpctunnel/tunnel_client.go +++ b/agent/server/grpctunnel/tunnel_client.go @@ -20,9 +20,8 @@ import ( pb "github.com/cortexapps/axon/.generated/proto/github.com/cortexapps/axon/tunnelpb" "github.com/cortexapps/axon/common" "github.com/cortexapps/axon/config" + "github.com/cortexapps/axon/server/acceptfile" cortexHttp "github.com/cortexapps/axon/server/http" - "github.com/cortexapps/axon/server/snykbroker" - "github.com/cortexapps/axon/server/snykbroker/acceptfile" "github.com/cortexapps/axon/util" "github.com/gorilla/mux" "github.com/prometheus/client_golang/prometheus" @@ -146,13 +145,19 @@ func newConnectErr(phase string, cause error) *connectError { return &connectError{phase: phase, cause: cause} } -// tunnelClient implements the snykbroker.RelayInstanceManager interface -// using gRPC bidirectional streaming instead of snyk-broker. +// TunnelClient relays calls from Cortex to the local environment. +type TunnelClient interface { + Start() error + Restart() error + Close() error +} + +// tunnelClient implements TunnelClient using gRPC bidirectional streaming. type tunnelClient struct { config config.AgentConfig logger *zap.Logger integrationInfo common.IntegrationInfo - registration snykbroker.Registration + registration Registration router *Router backend Backend httpClient *http.Client @@ -300,12 +305,12 @@ type TunnelClientParams struct { Logger *zap.Logger IntegrationInfo common.IntegrationInfo HttpServer cortexHttp.Server - Registration snykbroker.Registration + Registration Registration Transport *http.Transport `optional:"true"` Registry *prometheus.Registry `optional:"true"` } -func NewTunnelClient(p TunnelClientParams) snykbroker.RelayInstanceManager { +func NewTunnelClient(p TunnelClientParams) TunnelClient { // Connection pooling matters more here than in a typical client: every // tunnelled call becomes an upstream request, and they concentrate on a // handful of hosts. net/http's default MaxIdleConnsPerHost of 2 would @@ -364,8 +369,8 @@ func NewTunnelClient(p TunnelClientParams) snykbroker.RelayInstanceManager { } // RegisterRoutes implements cortexHttp.Handler. Exposes /restart and -// /systemcheck under the broker path prefix to preserve the snyk-broker URL -// shape. +// /systemcheck under the broker path prefix to keep the URL shape that +// clients already use. // initMetrics creates the client's metrics and returns them for registering. func (tc *tunnelClient) initMetrics() []prometheus.Collector { tc.connectionsActive = prometheus.NewGaugeVec( diff --git a/agent/server/grpctunnel/tunnel_client_test.go b/agent/server/grpctunnel/tunnel_client_test.go index 53c81aec..badf45c3 100644 --- a/agent/server/grpctunnel/tunnel_client_test.go +++ b/agent/server/grpctunnel/tunnel_client_test.go @@ -18,9 +18,8 @@ import ( pb "github.com/cortexapps/axon/.generated/proto/github.com/cortexapps/axon/tunnelpb" "github.com/cortexapps/axon/common" "github.com/cortexapps/axon/config" + "github.com/cortexapps/axon/server/acceptfile" cortexHttp "github.com/cortexapps/axon/server/http" - "github.com/cortexapps/axon/server/snykbroker" - "github.com/cortexapps/axon/server/snykbroker/acceptfile" "github.com/cortexapps/axon/test/httpfake" "github.com/prometheus/client_golang/prometheus" dto "github.com/prometheus/client_model/go" @@ -50,7 +49,7 @@ type fakeRegistration struct { calls int32 } -func (r *fakeRegistration) Register(_ context.Context, integration common.Integration, alias string) (*snykbroker.RegistrationInfoResponse, error) { +func (r *fakeRegistration) Register(_ context.Context, integration common.Integration, alias string) (*RegistrationInfoResponse, error) { r.mu.Lock() defer r.mu.Unlock() atomic.AddInt32(&r.calls, 1) @@ -58,7 +57,7 @@ func (r *fakeRegistration) Register(_ context.Context, integration common.Integr if r.idx < len(r.tokens)-1 { r.idx++ } - return &snykbroker.RegistrationInfoResponse{ + return &RegistrationInfoResponse{ ServerUri: r.serverURI, Token: tok, }, nil @@ -211,7 +210,7 @@ func startFakeServer(t *testing.T, svc pb.TunnelServiceServer) (string, func()) // newTestClient builds a tunnelClient ready for testing, with metrics // registered, a stub router/backend wired in, and the given registration // backend. -func newTestClient(t *testing.T, cfg config.AgentConfig, reg snykbroker.Registration) (*tunnelClient, *prometheus.Registry) { +func newTestClient(t *testing.T, cfg config.AgentConfig, reg Registration) (*tunnelClient, *prometheus.Registry) { t.Helper() logger := zaptest.NewLogger(t) registry := prometheus.NewRegistry() @@ -1014,12 +1013,12 @@ type countingRegistration struct { gate chan struct{} } -func (r *countingRegistration) Register(_ context.Context, _ common.Integration, _ string) (*snykbroker.RegistrationInfoResponse, error) { +func (r *countingRegistration) Register(_ context.Context, _ common.Integration, _ string) (*RegistrationInfoResponse, error) { r.calls.Add(1) if r.gate != nil { <-r.gate } - return &snykbroker.RegistrationInfoResponse{ServerUri: "127.0.0.1:1", Token: "rotated"}, nil + return &RegistrationInfoResponse{ServerUri: "127.0.0.1:1", Token: "rotated"}, nil } // startWorkers runs n manageStream workers, one per pool connection, without diff --git a/agent/server/http/axon_handler.go b/agent/server/http/axon_handler.go index b76594f9..3da51f03 100644 --- a/agent/server/http/axon_handler.go +++ b/agent/server/http/axon_handler.go @@ -90,19 +90,6 @@ func (h *axonHandler) returnJson(obj interface{}, w http.ResponseWriter) { w.Write(json) } -// relayMode reports the transport this agent relays over. It answers with the -// effective transport rather than echoing the configured string: an unset mode -// means the snyk-broker default rather than "unknown", and only an exact -// "grpc-tunnel" selects the tunnel, so anything else — a typo included — is -// running snyk-broker and is reported as such. Deciding this through the same -// predicate the relay itself switches on keeps the two from drifting. -func (h *axonHandler) relayMode() string { - if h.config.IsGRPCTunnel() { - return string(config.RelayModeGrpcTunnel) - } - return string(config.RelayModeSnykBroker) -} - func (h *axonHandler) healthcheck(w http.ResponseWriter, r *http.Request) { result := map[string]interface{}{ "OK": true, @@ -124,10 +111,8 @@ func (h *axonHandler) info(w http.ResponseWriter, r *http.Request) { Handlers []string `json:"handlers"` InstanceID string `json:"instance_id"` BuildVersion string `json:"build_version"` - // Which relay transport this agent is running: "snyk-broker" or - // "grpc-tunnel". Reported so the fleet's transport mix is visible - // from the backend rather than inferred from which server an agent - // happens to be connected to. + // The relay transport this agent runs. It is always "grpc-tunnel" + // now. The field stays because the backend reads it. RelayMode string `json:"relay_mode"` }{ InstanceID: h.config.InstanceId, @@ -135,7 +120,7 @@ func (h *axonHandler) info(w http.ResponseWriter, r *http.Request) { Alias: h.config.IntegrationAlias, Handlers: []string{}, BuildVersion: config.BuildVersion(), - RelayMode: h.relayMode(), + RelayMode: "grpc-tunnel", } handlers, err := h.fetchHandlers(r) diff --git a/agent/server/http/axon_info_test.go b/agent/server/http/axon_info_test.go index 9292adca..0f3afb37 100644 --- a/agent/server/http/axon_info_test.go +++ b/agent/server/http/axon_info_test.go @@ -12,48 +12,6 @@ import ( "go.uber.org/zap" ) -// __axon/info reports which relay transport an agent is running so the fleet's -// transport mix is visible from the backend. The endpoint itself needs a live -// gRPC server to list handlers, so it is exercised end to end by -// relay_scenarios.sh against both transports; what is unit-tested here is the -// value it reports. - -func modeFor(t *testing.T, cfg config.AgentConfig) string { - t.Helper() - logger, _ := zap.NewDevelopment() - h := NewAxonHandler(AxonHandlerParams{Logger: logger, Config: cfg}).(*axonHandler) - return h.relayMode() -} - -func TestRelayMode_GrpcTunnel(t *testing.T) { - assert.Equal(t, "grpc-tunnel", modeFor(t, config.AgentConfig{ - RelayMode: string(config.RelayModeGrpcTunnel), - })) -} - -func TestRelayMode_SnykBroker(t *testing.T) { - assert.Equal(t, "snyk-broker", modeFor(t, config.AgentConfig{ - RelayMode: string(config.RelayModeSnykBroker), - })) -} - -// An unset transport is the snyk-broker default, not an unknown. Reporting the -// effective value keeps the backend from having to encode that default, and -// stops an empty string reading as "this agent did not answer". -func TestRelayMode_UnsetReportsTheDefault(t *testing.T) { - assert.Equal(t, "snyk-broker", modeFor(t, config.AgentConfig{})) -} - -// The value reported is the effective transport, not the configured string. -// Only an exact "grpc-tunnel" selects the tunnel — config.IsGRPCTunnel compares -// exactly — so a near miss like "grpc_tunnel" runs snyk-broker, and reporting -// it verbatim would put a transport nobody is running into the fleet's mix. -func TestRelayMode_UnrecognizedReportsTheEffectiveMode(t *testing.T) { - assert.Equal(t, "snyk-broker", modeFor(t, config.AgentConfig{ - RelayMode: "grpc_tunnel", - })) -} - // Always populated, so a fleet view never has a blank column. Outside a // container image this is the "dev" fallback rather than a build tag. func TestBuildVersion_AlwaysPopulated(t *testing.T) { diff --git a/agent/server/http/http_server.go b/agent/server/http/http_server.go index eeb066a0..b0186062 100644 --- a/agent/server/http/http_server.go +++ b/agent/server/http/http_server.go @@ -294,10 +294,10 @@ var defaultReadTimeout = time.Second // defaultIdleTimeout is how long a keep-alive connection may sit between // requests. It is set explicitly because net/http otherwise reuses -// ReadTimeout for this. It must outlast the gaps between the broker's -// requests: the broker keeps its connections open and would write the next -// request into a socket this server had just closed, failing with ECONNRESET -// and retrying. +// ReadTimeout for this. It must outlast the gaps between a client's +// requests: a client that keeps its connections open would otherwise write +// the next request into a socket this server had just closed, failing with +// ECONNRESET and retrying. var defaultIdleTimeout = 5 * time.Minute func (h *httpServer) Start() (int, error) { diff --git a/agent/server/http/http_server_idle_test.go b/agent/server/http/http_server_idle_test.go index 791b0307..aad3cd06 100644 --- a/agent/server/http/http_server_idle_test.go +++ b/agent/server/http/http_server_idle_test.go @@ -31,9 +31,9 @@ func sendAndRead(t *testing.T, conn net.Conn, r *bufio.Reader) (*http.Response, // The server set ReadTimeout without IdleTimeout, and net/http falls back to // ReadTimeout as the keep-alive idle limit. One second is shorter than the gap -// between consecutive requests from the broker, which keeps its connections -// open (Node's agent does so by default), so the broker regularly wrote the -// next request into a socket the server had just closed and got ECONNRESET. +// between consecutive requests from a client that keeps its connections open, +// so such a client regularly wrote the next request into a socket the server +// had just closed and got ECONNRESET. // A connection that sat idle for longer than ReadTimeout must still accept // the next request. func TestServer_KeepsKeepAliveConnectionIdlePastReadTimeout(t *testing.T) { @@ -78,10 +78,10 @@ func newReadTimeoutTestServer(t *testing.T, opts ...ServerOption) (*httpServer, return srv, port } -// The broker opens a connection and writes its request only when its event -// loop gets to it. Under load that loop stalls for more than a second, and -// the default one-second ReadTimeout, which starts when the connection is -// accepted, closes the connection before the request arrives. +// A client can open a connection and write its request only later, for +// example when its event loop stalls under load. The default one-second +// ReadTimeout, which starts when the connection is accepted, closes the +// connection before the request arrives. // WithReadTimeout lets a server with such a client wait longer. func TestServer_ServesLateRequestWithConfiguredReadTimeout(t *testing.T) { srv, port := newReadTimeoutTestServer(t, WithReadTimeout(30*time.Second)) @@ -99,7 +99,7 @@ func TestServer_ServesLateRequestWithConfiguredReadTimeout(t *testing.T) { } // The same bound covers a request body that arrives late, such as a PUT the -// broker starts writing before a stall and finishes after it. +// client starts writing before a stall and finishes after it. func TestServer_ReadsLateBodyWithConfiguredReadTimeout(t *testing.T) { srv, port := newReadTimeoutTestServer(t, WithReadTimeout(30*time.Second)) defer srv.Close() diff --git a/agent/server/relaymode/relaymode.go b/agent/server/relaymode/relaymode.go deleted file mode 100644 index 169268cc..00000000 --- a/agent/server/relaymode/relaymode.go +++ /dev/null @@ -1,128 +0,0 @@ -// Package relaymode selects the relay tunnel mode before the agent builds -// its stack, and watches Cortex for a change after that. It has no fx -// wiring, so it can be called on its own. -// -// Precedence, highest first: -// -// 1. The agent configuration: AXON_RELAY_TRANSPORT (or RELAY_MODE), or the -// mode a build forces (config.ForcedRelayMode). -// 2. The tunnelMode field of the Cortex registration response. -// 3. Default. -// -// When the configuration does not select a mode, the mode is remote-driven: -// Resolve makes a best-effort registration at start, and Watch registers -// again at an interval. When a successful registration selects a different -// mode than the one that runs, the agent starts again with the new mode. -package relaymode - -import ( - "context" - "fmt" - "os" - "time" - - "github.com/cortexapps/axon/common" - "github.com/cortexapps/axon/config" - "github.com/cortexapps/axon/server/snykbroker" -) - -// Default is the mode the agent runs when neither the configuration nor -// Cortex selects one. It is here and not in config so that the -// configuration can tell a customer choice from the default. -const Default = config.RelayModeSnykBroker - -// registerTimeout bounds each registration call, so that a slow Cortex API -// delays the agent start by a known amount at most. A package variable so -// tests can shorten it. -var registerTimeout = 10 * time.Second - -// Result is the mode Resolve selected. -type Result struct { - Mode config.RelayMode - // Reason tells where Mode came from, for the log. - Reason string - // Remote is true when Cortex drives the mode, so Watch must run. It is - // true also when the registration at start failed and Mode is Default. - Remote bool -} - -// Resolve returns the mode to run. It calls Register only when the -// configuration does not select a mode. If the call fails, or Cortex sends -// no value or an unknown value, the mode is Default. -func Resolve(ctx context.Context, cfg config.AgentConfig, info common.IntegrationInfo, reg snykbroker.Registration) Result { - if cfg.RelayModePinned() { - // Only an exact "grpc-tunnel" selects the tunnel. All other values - // run snyk-broker, as they always did. - if cfg.IsGRPCTunnel() { - return Result{Mode: config.RelayModeGrpcTunnel, Reason: "set by configuration"} - } - return Result{Mode: config.RelayModeSnykBroker, Reason: "set by configuration"} - } - - // The tunnels do not register in these cases, so neither do we. - if cfg.DryRun { - return Result{Mode: Default, Reason: "default (dry run)"} - } - if os.Getenv("BROKER_SERVER_URL") != "" && os.Getenv("BROKER_TOKEN") != "" { - return Result{Mode: Default, Reason: "default (BROKER_SERVER_URL and BROKER_TOKEN set)"} - } - - resp, err := register(ctx, info, reg) - if err != nil { - return Result{Mode: Default, Reason: fmt.Sprintf("default (registration failed: %v)", err), Remote: true} - } - mode, known := FromRegistration(resp) - switch { - case !known: - return Result{Mode: Default, Reason: fmt.Sprintf("default (unknown tunnelMode %q from Cortex)", resp.TunnelMode), Remote: true} - case resp.TunnelMode == "": - return Result{Mode: Default, Reason: "default (Cortex has no preference)", Remote: true} - default: - return Result{Mode: mode, Reason: "selected by Cortex", Remote: true} - } -} - -// FromRegistration returns the mode that a registration response selects. -// No tunnelMode selects Default. The second result is false when the -// tunnelMode is not a known mode. -func FromRegistration(resp *snykbroker.RegistrationInfoResponse) (config.RelayMode, bool) { - switch m := config.RelayMode(resp.TunnelMode); m { - case "": - return Default, true - case config.RelayModeSnykBroker, config.RelayModeGrpcTunnel: - return m, true - } - return Default, false -} - -// Watch registers at each interval until ctx ends. When a successful -// registration selects a different mode than running, it calls onChange -// with that mode and returns. A failed registration, or a tunnelMode that -// is not a known mode, changes nothing. -func Watch(ctx context.Context, interval time.Duration, info common.IntegrationInfo, reg snykbroker.Registration, running config.RelayMode, onChange func(config.RelayMode)) { - ticker := time.NewTicker(interval) - defer ticker.Stop() - - for { - select { - case <-ctx.Done(): - return - case <-ticker.C: - } - - resp, err := register(ctx, info, reg) - if err != nil { - continue - } - if mode, known := FromRegistration(resp); known && mode != running { - onChange(mode) - return - } - } -} - -func register(ctx context.Context, info common.IntegrationInfo, reg snykbroker.Registration) (*snykbroker.RegistrationInfoResponse, error) { - ctx, cancel := context.WithTimeout(ctx, registerTimeout) - defer cancel() - return reg.Register(ctx, info.Integration, info.Alias) -} diff --git a/agent/server/relaymode/relaymode_test.go b/agent/server/relaymode/relaymode_test.go deleted file mode 100644 index cb9e4f2c..00000000 --- a/agent/server/relaymode/relaymode_test.go +++ /dev/null @@ -1,161 +0,0 @@ -package relaymode - -import ( - "context" - "errors" - "sync" - "testing" - "time" - - "github.com/cortexapps/axon/common" - "github.com/cortexapps/axon/config" - "github.com/cortexapps/axon/server/snykbroker" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -// fakeRegistration answers each call with the next response in answers, and -// repeats the last one after that. -type fakeRegistration struct { - mu sync.Mutex - answers []answer - calls int -} - -type answer struct { - tunnelMode string - err error -} - -func answers(a ...answer) *fakeRegistration { return &fakeRegistration{answers: a} } - -func mode(m string) answer { return answer{tunnelMode: m} } - -func failure() answer { return answer{err: errors.New("cortex is down")} } - -func (f *fakeRegistration) Register(ctx context.Context, _ common.Integration, _ string) (*snykbroker.RegistrationInfoResponse, error) { - f.mu.Lock() - defer f.mu.Unlock() - a := f.answers[min(f.calls, len(f.answers)-1)] - f.calls++ - if a.err != nil { - return nil, a.err - } - return &snykbroker.RegistrationInfoResponse{ServerUri: "https://relay", Token: "t", TunnelMode: a.tunnelMode}, nil -} - -func (f *fakeRegistration) callCount() int { - f.mu.Lock() - defer f.mu.Unlock() - return f.calls -} - -func resolve(t *testing.T, cfg config.AgentConfig, reg *fakeRegistration) Result { - t.Helper() - t.Setenv("BROKER_SERVER_URL", "") - t.Setenv("BROKER_TOKEN", "") - res := Resolve(context.Background(), cfg, common.IntegrationInfo{Integration: common.IntegrationGithub}, reg) - assert.NotEmpty(t, res.Reason) - return res -} - -func TestResolve_ConfigurationWins(t *testing.T) { - reg := answers(mode("grpc-tunnel")) - res := resolve(t, config.AgentConfig{RelayMode: "snyk-broker"}, reg) - assert.Equal(t, config.RelayModeSnykBroker, res.Mode) - assert.False(t, res.Remote, "Cortex cannot change a configured mode") - assert.Equal(t, 0, reg.callCount(), "a configured mode needs no registration") - - assert.Equal(t, config.RelayModeGrpcTunnel, resolve(t, config.AgentConfig{RelayMode: "grpc-tunnel"}, answers(mode(""))).Mode) - - // A near miss runs snyk-broker, as it always did. - assert.Equal(t, config.RelayModeSnykBroker, resolve(t, config.AgentConfig{RelayMode: "grpc_tunnel"}, answers(mode("grpc-tunnel"))).Mode) -} - -func TestResolve_FromCortex(t *testing.T) { - cases := []struct { - name string - reg *fakeRegistration - want config.RelayMode - }{ - {"grpc-tunnel", answers(mode("grpc-tunnel")), config.RelayModeGrpcTunnel}, - {"snyk-broker", answers(mode("snyk-broker")), config.RelayModeSnykBroker}, - {"no preference", answers(mode("")), Default}, - {"unknown value", answers(mode("carrier-pigeon")), Default}, - {"registration fails", answers(failure()), Default}, - } - for _, c := range cases { - t.Run(c.name, func(t *testing.T) { - res := resolve(t, config.AgentConfig{}, c.reg) - assert.Equal(t, c.want, res.Mode) - assert.True(t, res.Remote, "Cortex drives the mode, also after a failed registration") - assert.Equal(t, 1, c.reg.callCount()) - }) - } -} - -func TestResolve_NoRegistrationWhenTheTunnelsSkipIt(t *testing.T) { - reg := answers(mode("grpc-tunnel")) - res := resolve(t, config.AgentConfig{DryRun: true}, reg) - assert.Equal(t, Default, res.Mode) - assert.False(t, res.Remote) - assert.Equal(t, 0, reg.callCount()) - - t.Setenv("BROKER_SERVER_URL", "https://relay") - t.Setenv("BROKER_TOKEN", "t") - res = Resolve(context.Background(), config.AgentConfig{}, common.IntegrationInfo{}, reg) - assert.Equal(t, Default, res.Mode) - assert.False(t, res.Remote) - assert.Equal(t, 0, reg.callCount()) -} - -// watch runs Watch until it reports a change or the time is up, and returns -// the new mode, or "" for no change. -func watch(t *testing.T, reg *fakeRegistration, running config.RelayMode, wantCalls int) config.RelayMode { - t.Helper() - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) - defer cancel() - - var changed config.RelayMode - done := make(chan struct{}) - go func() { - defer close(done) - Watch(ctx, time.Millisecond, common.IntegrationInfo{}, reg, running, func(m config.RelayMode) { changed = m }) - }() - require.Eventually(t, func() bool { - select { - case <-done: - return true - default: - return reg.callCount() >= wantCalls - } - }, 2*time.Second, time.Millisecond) - cancel() - <-done - return changed -} - -func TestWatch_ConfirmedChangeRestarts(t *testing.T) { - assert.Equal(t, config.RelayModeGrpcTunnel, - watch(t, answers(mode("snyk-broker"), mode("grpc-tunnel")), config.RelayModeSnykBroker, 2)) - - // Cortex clears its preference, and the default differs from the running mode. - assert.Equal(t, Default, - watch(t, answers(mode("")), config.RelayModeGrpcTunnel, 1)) -} - -func TestWatch_FailuresChangeNothing(t *testing.T) { - // The registration at start failed, so the default runs. Failures after - // that are not a change; the first success that differs is. - reg := answers(failure(), failure(), failure(), mode("grpc-tunnel")) - assert.Equal(t, config.RelayModeGrpcTunnel, watch(t, reg, Default, 4)) - - reg = answers(failure()) - assert.Equal(t, config.RelayMode(""), watch(t, reg, config.RelayModeGrpcTunnel, 20)) -} - -func TestWatch_SameOrUnknownModeChangesNothing(t *testing.T) { - assert.Equal(t, config.RelayMode(""), watch(t, answers(mode("grpc-tunnel")), config.RelayModeGrpcTunnel, 20)) - assert.Equal(t, config.RelayMode(""), watch(t, answers(mode("")), Default, 20)) - assert.Equal(t, config.RelayMode(""), watch(t, answers(mode("carrier-pigeon")), config.RelayModeGrpcTunnel, 20)) -} diff --git a/agent/server/snykbroker/acceptfile/origin_contract_test.go b/agent/server/snykbroker/acceptfile/origin_contract_test.go deleted file mode 100644 index c30a2418..00000000 --- a/agent/server/snykbroker/acceptfile/origin_contract_test.go +++ /dev/null @@ -1,122 +0,0 @@ -package acceptfile - -import ( - "testing" - - "github.com/cortexapps/axon/config" - "github.com/stretchr/testify/require" - "go.uber.org/zap" -) - -// AcceptFileRuleWrapper.Origin() is the one accessor this package shares with -// the snyk-broker reflector: relay_instance_manager.go reads it to decide -// whether a rule needs a wildcard policy, to build the reflector proxy URI, and -// to report a bad origin. Nothing else the tunnel work touched is reachable -// from that path — Path() and MatchRule have no callers outside this package -// and grpctunnel. -// -// So this pins Origin()'s contract directly, in the shapes the reflector -// depends on, rather than leaving it implied by tests of the things built on -// top of it. -func TestOriginContract(t *testing.T) { - cases := []struct { - name string - origin string - env map[string]string - want string - }{ - { - name: "absolute origin is returned verbatim", - origin: "https://api.github.com", - want: "https://api.github.com", - }, - { - name: "origin keeps its base path", - origin: "https://git.example/api/v3", - want: "https://git.example/api/v3", - }, - { - name: "origin keeps its port", - origin: "http://localhost:9999", - want: "http://localhost:9999", - }, - { - name: "plaintext scheme is not upgraded", - origin: "http://internal.example", - want: "http://internal.example", - }, - { - name: "a scheme-less origin defaults to https", - origin: "github.com", - want: "https://github.com", - }, - { - name: "a scheme-less default from ${VAR:default} defaults to https", - origin: "${GITHUB:github.com}", - want: "https://github.com", - }, - { - name: "${VAR} expands from the environment", - origin: "${GITHUB_API}", - env: map[string]string{"GITHUB_API": "https://ghe.example/api/v3"}, - want: "https://ghe.example/api/v3", - }, - { - name: "${VAR:default} prefers the environment when set", - origin: "${GITHUB:github.com}", - env: map[string]string{"GITHUB": "https://ghe.example"}, - want: "https://ghe.example", - }, - { - // The reflector greps Origin() for "*" to decide a rule needs a - // wildcard policy, so the star has to survive verbatim. - name: "a wildcard family survives untouched", - origin: "https://*.googleapis.com", - want: "https://*.googleapis.com", - }, - { - name: "a wildcard family keeps its port", - origin: "https://*.api.example.net:8443", - want: "https://*.api.example.net:8443", - }, - { - name: "a wildcard family from a ${VAR:default}", - origin: "${GOOGLE_API:https://*.googleapis.com}", - want: "https://*.googleapis.com", - }, - { - name: "credentials in the origin are preserved", - origin: "http://user:pass@localhost:9000", - want: "http://user:pass@localhost:9000", - }, - } - - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - for k, v := range tc.env { - t.Setenv(k, v) - } - cfg := config.AgentConfig{HttpServerPort: 8080, PluginDirs: []string{}} - content := `{"private":[{"method":"any","path":"/*","origin":"` + tc.origin + `"}]}` - af, err := NewAcceptFile([]byte(content), cfg, zap.NewNop()) - require.NoError(t, err) - - rules := af.Wrapper().PrivateRules() - require.Len(t, rules, 1) - require.Equal(t, tc.want, rules[0].Origin()) - }) - } -} - -// A rule with no origin reads as empty rather than panicking: the reflector -// calls Origin() on every private rule before anything has vetted them. -func TestOriginOfRuleWithoutOneIsEmpty(t *testing.T) { - cfg := config.AgentConfig{HttpServerPort: 8080, PluginDirs: []string{}} - af, err := NewAcceptFile([]byte(`{"private":[{"method":"any","path":"/*"}]}`), cfg, zap.NewNop()) - require.NoError(t, err) - - rules := af.Wrapper().PrivateRules() - require.Len(t, rules, 1) - require.Equal(t, "", rules[0].Origin()) - require.Equal(t, "", rules[0].RawOrigin()) -} diff --git a/agent/server/snykbroker/event_tracker.go b/agent/server/snykbroker/event_tracker.go deleted file mode 100644 index c453fd17..00000000 --- a/agent/server/snykbroker/event_tracker.go +++ /dev/null @@ -1,46 +0,0 @@ -package snykbroker - -import ( - "sync" - "time" -) - -// eventTracker tracks the timestamps of events -type eventTracker struct { - events []time.Time - lock sync.Mutex -} - -// NeweventTracker creates a new eventTracker -func newEventTracker() *eventTracker { - return &eventTracker{ - events: make([]time.Time, 0), - } -} - -// AddEvent adds a new event with the current timestamp -func (et *eventTracker) AddEvent() { - et.lock.Lock() - defer et.lock.Unlock() - et.events = append(et.events, time.Now()) -} - -// CountEventsWithinWindow counts the number of events within the specified time window -func (et *eventTracker) CountEventsWithinWindow(window time.Duration) int { - et.lock.Lock() - defer et.lock.Unlock() - now := time.Now() - count := 0 - invalidBeforeIndex := -1 - for i, eventTime := range et.events { - if now.Sub(eventTime) <= window { - count++ - } else if invalidBeforeIndex == -1 { - invalidBeforeIndex = i - } - } - if invalidBeforeIndex >= 0 { - et.events = et.events[invalidBeforeIndex:] - } - return count -} diff --git a/agent/server/snykbroker/event_tracker_test.go b/agent/server/snykbroker/event_tracker_test.go deleted file mode 100644 index 942d3b54..00000000 --- a/agent/server/snykbroker/event_tracker_test.go +++ /dev/null @@ -1,65 +0,0 @@ -package snykbroker - -import ( - "testing" - "time" - - "github.com/stretchr/testify/require" -) - -func TestCountEventsWithinWindow_NoEvents(t *testing.T) { - tracker := newEventTracker() - count := tracker.CountEventsWithinWindow(1 * time.Minute) - require.Equal(t, 0, count) -} - -func TestCountEventsWithinWindow_AllEventsWithinWindow(t *testing.T) { - tracker := newEventTracker() - tracker.AddEvent() - tracker.AddEvent() - tracker.AddEvent() - - count := tracker.CountEventsWithinWindow(1 * time.Minute) - require.Equal(t, 3, count) -} - -func TestCountEventsWithinWindow_SomeEventsWithinWindow(t *testing.T) { - tracker := newEventTracker() - tracker.AddEvent() - time.Sleep(5 * time.Millisecond) - tracker.AddEvent() - time.Sleep(5 * time.Millisecond) - tracker.AddEvent() - - count := tracker.CountEventsWithinWindow(5 * time.Millisecond) - require.Equal(t, 1, count) -} - -func TestCountEventsWithinWindow_NoEventsWithinWindow(t *testing.T) { - tracker := newEventTracker() - tracker.AddEvent() - tracker.AddEvent() - tracker.AddEvent() - - time.Sleep(10 * time.Millisecond) - - count := tracker.CountEventsWithinWindow(5 * time.Millisecond) - require.Equal(t, 0, count) -} - -func TestCountEventsWithinWindow_EventsCleanup(t *testing.T) { - tracker := newEventTracker() - tracker.AddEvent() - time.Sleep(5 * time.Millisecond) - tracker.AddEvent() - time.Sleep(5 * time.Millisecond) - tracker.AddEvent() - - count := tracker.CountEventsWithinWindow(5 * time.Millisecond) - require.Equal(t, 1, count) - time.Sleep(5 * time.Millisecond) - - count = tracker.CountEventsWithinWindow(5 * time.Millisecond) - require.Equal(t, 0, count) - -} diff --git a/agent/server/snykbroker/logger_test.go b/agent/server/snykbroker/logger_test.go deleted file mode 100644 index bc20452f..00000000 --- a/agent/server/snykbroker/logger_test.go +++ /dev/null @@ -1,52 +0,0 @@ -package snykbroker - -import ( - "bytes" - "sync" - "testing" - - "go.uber.org/zap" - "go.uber.org/zap/zapcore" -) - -// testLogWriter forwards zap output to the test log, then goes quiet once the -// test finishes. Request goroutines outlive the test that started them, and -// writing to a finished test races tRunner marking it done. Waiting for them -// instead does not work: every layer logs after the one below it has already -// signalled completion. -// -// The mutex spans the check and the write, so a call cannot pass the check and -// then land after the test is done. -type testLogWriter struct { - mu sync.Mutex - t testing.TB - finished bool -} - -func (w *testLogWriter) Write(p []byte) (int, error) { - w.mu.Lock() - defer w.mu.Unlock() - if !w.finished { - w.t.Logf("%s", bytes.TrimRight(p, "\n")) - } - return len(p), nil -} - -func (w *testLogWriter) stop() { - w.mu.Lock() - defer w.mu.Unlock() - w.finished = true -} - -// newTestLogger returns a logger safe to call from goroutines that outlive the -// test. Use it instead of zaptest.NewLogger wherever one can. -func newTestLogger(t testing.TB) *zap.Logger { - t.Helper() - w := &testLogWriter{t: t} - t.Cleanup(w.stop) - return zap.New(zapcore.NewCore( - zapcore.NewConsoleEncoder(zap.NewDevelopmentEncoderConfig()), - zapcore.AddSync(w), - zapcore.DebugLevel, - )) -} diff --git a/agent/server/snykbroker/module.go b/agent/server/snykbroker/module.go deleted file mode 100644 index 8d8856de..00000000 --- a/agent/server/snykbroker/module.go +++ /dev/null @@ -1,21 +0,0 @@ -package snykbroker - -import ( - "github.com/cortexapps/axon/config" - "go.uber.org/fx" -) - -var Module = fx.Module("snykbroker", - fx.Provide(NewRegistration), - fx.Provide(MaybeNewRegistrationReflector), - fx.Invoke(NewRelayInstanceManager), -) - -func MaybeNewRegistrationReflector(cfg config.AgentConfig, p RegistrationReflectorParams) *RegistrationReflector { - - if !cfg.HttpRelayReflectorMode.IsEnabled() { - return nil - } - - return NewRegistrationReflector(p) -} diff --git a/agent/server/snykbroker/origin.go b/agent/server/snykbroker/origin.go deleted file mode 100644 index 9e18f04a..00000000 --- a/agent/server/snykbroker/origin.go +++ /dev/null @@ -1,157 +0,0 @@ -package snykbroker - -import ( - "errors" - "fmt" - "net" - "net/url" - "strconv" - "strings" - - "golang.org/x/net/publicsuffix" -) - -// HeaderTargetHost is routing input, never authorization: the deployed origin -// stays the policy, and this value is only ever checked against it. -const HeaderTargetHost = "x-cortex-target-host" - -// HeaderFailureClass names the component that failed, so a caller can branch on -// it without reading a body an upstream could also have written. Only components -// on this side of the boundary set it; an upstream copy is stripped. -const HeaderFailureClass = "x-cortex-failure-class" - -const ErrClassDestinationRejected = "AXON_DESTINATION_REJECTED" - -// The rule's credential provider produced no value. Distinct from an upstream -// 401 or 403, which says the credential was produced and then refused. -const ErrClassCredentialFailure = "AXON_CREDENTIAL_FAILURE" - -// This agent's own DNS, connection, or TLS failed, so the upstream never -// answered and its status must not be invented on its behalf. -const ErrClassNetworkFailure = "AXON_NETWORK_FAILURE" - -// With verification off, anything answering the connection can claim the -// authorized name, so a host family authorizes nothing. A concrete origin at -// least names one host the operator chose. -var ErrWildcardOriginRequiresTLSVerification = errors.New( - "a wildcard origin requires TLS verification, but it is disabled") - -type wildcardOrigin struct { - // Keeps the leading dot, so matching is label-aligned: ".example.com". - suffix string -} - -// matches reports whether host sits exactly one label under the wildcard. -// -// One label, not one-or-more: a wildcard certificate covers a single label, so -// a multi-label match would authorize names that verification then refuses. Do -// not relax this to a plain suffix test. -func (w wildcardOrigin) matches(host string) bool { - if !strings.HasSuffix(host, w.suffix) { - return false - } - label := host[:len(host)-len(w.suffix)] - return label != "" && !strings.Contains(label, ".") -} - -// parseOrigin returns the URL to dial and, for a wildcard origin, the family it -// authorizes. Callers run it at startup so a malformed policy fails there -// rather than per request. -func parseOrigin(origin string) (*url.URL, *wildcardOrigin, error) { - asURL, err := url.Parse(origin) - if err != nil { - return nil, nil, fmt.Errorf("invalid target URI: %w", err) - } - - if !strings.Contains(asURL.Host, "*") { - // Deliberately not port-checked. A concrete origin names one host the - // operator picked, and the agent's own origin carries port 0 until its - // listener binds. - return asURL, nil, nil - } - - // Certificate verification is the destination control, so a family cannot - // be served over plaintext. - if asURL.Scheme != "https" { - return nil, nil, fmt.Errorf("wildcard origin %q must use https", origin) - } - // A wildcard origin's port is dialed against a host the operator never - // wrote down, so an unusable one has to stop the agent rather than surface - // as a per-request failure. - if err := validatePort(asURL.Port()); err != nil { - return nil, nil, fmt.Errorf("wildcard origin %q: %w", origin, err) - } - - host := asURL.Hostname() - suffix, found := strings.CutPrefix(host, "*.") - if !found || strings.Contains(suffix, "*") { - return nil, nil, fmt.Errorf("wildcard origin %q must have the form https://*.example.com", origin) - } - // "https://*." alone would authorize every host, and an empty label would - // misalign the match against the dot this stores. - if suffix == "" || strings.HasPrefix(suffix, ".") || - strings.HasSuffix(suffix, ".") || strings.Contains(suffix, "..") { - return nil, nil, fmt.Errorf("wildcard origin %q has an empty label", origin) - } - // ICANN division only. The private section holds ordinary registrable - // domains added for cookie scoping, and rejecting those would rule out - // legitimate families. - if publicSuffix, icann := publicsuffix.PublicSuffix(suffix); icann && publicSuffix == suffix { - return nil, nil, fmt.Errorf("wildcard origin %q must contain a registrable domain", origin) - } - - return asURL, &wildcardOrigin{suffix: "." + suffix}, nil -} - -// parseTargetHost normalizes a header value into a host to match against the -// origin, or reports why it is unusable. -// -// Deliberately not a hostname validator. The destination controls are -// wildcardOrigin.matches, which confines the value to the family whatever it -// contains, and the certificate check behind it, which no made-up name can -// pass. What is left here is the handful of shapes that would confuse those two -// or dial something other than a host in the family. -// -// The value names a host and nothing else. The origin decides the port, so a -// value carrying one is either restating it or trying to change it, and there -// is no reason to tell those apart. -func parseTargetHost(value string) (string, error) { - if value == "" { - return "", fmt.Errorf("empty target host") - } - // A comma-joined value used to pass the suffix test whole and come back as - // the host to dial, so this one guards the match rather than tidying input. - if strings.ContainsAny(value, ",") { - return "", fmt.Errorf("target host carries multiple values") - } - // This becomes a Host header, so CR and LF do not get to travel. - if strings.TrimSpace(value) != value || strings.ContainsAny(value, " \t\r\n") { - return "", fmt.Errorf("target host contains whitespace") - } - if _, _, err := net.SplitHostPort(value); err == nil { - return "", fmt.Errorf("target host declares a port") - } - - // Lowercased because matches and the concrete-origin comparison are both - // byte comparisons against a policy the operator wrote in some other case. - host := strings.ToLower(value) - // An address cannot sit under a DNS family, so one here means the caller is - // trying to leave the policy rather than move within it. - if net.ParseIP(host) != nil { - return "", fmt.Errorf("target host is an IP address") - } - return host, nil -} - -// validatePort accepts an empty port, meaning the scheme's default. url.Parse -// already rejects a non-numeric port, but not 0 or an out-of-range number. -func validatePort(port string) error { - if port == "" { - return nil - } - n, err := strconv.Atoi(port) - if err != nil || n < 1 || n > 65535 { - return fmt.Errorf("port %q is not in 1-65535", port) - } - return nil -} diff --git a/agent/server/snykbroker/reflector.go b/agent/server/snykbroker/reflector.go deleted file mode 100644 index 5fcd3599..00000000 --- a/agent/server/snykbroker/reflector.go +++ /dev/null @@ -1,694 +0,0 @@ -package snykbroker - -import ( - "context" - "fmt" - "hash/fnv" - "net" - "net/http" - "net/http/httputil" - "net/url" - "strings" - "sync/atomic" - "time" - - "github.com/cortexapps/axon/config" - cortexHttp "github.com/cortexapps/axon/server/http" - "github.com/cortexapps/axon/server/snykbroker/acceptfile" - "github.com/gorilla/mux" - "github.com/prometheus/client_golang/prometheus" - "go.uber.org/fx" - "go.uber.org/zap" -) - -type RegistrationReflector struct { - logger *zap.Logger - transport *http.Transport - server cortexHttp.Server - // Never mutated once published; registration swaps in a new map. Readers - // hold no lock, so the map a reader is ranging over must stay frozen. - targets atomic.Pointer[map[string]proxyEntry] - serverStarted atomic.Bool - mode config.RelayReflectorMode - config config.AgentConfig - lastTrafficTime atomic.Int64 - lastStartupTime atomic.Int64 - lastTunnelTime atomic.Int64 - wsProxy *WebSocketProxy -} - -type RegistrationReflectorParams struct { - fx.In - Lifecycle fx.Lifecycle `optional:"true"` - Logger *zap.Logger - Transport *http.Transport `optional:"true"` - Registry *prometheus.Registry `optional:"true"` - Config config.AgentConfig -} - -// reflectorReadTimeout bounds reading a request from the broker. The broker -// opens a connection and writes its request only when its event loop gets to -// it, and that loop stalls for two to three seconds while it sends a large -// response. It stays under the relay dispatcher's 60-second request timeout. -const reflectorReadTimeout = 30 * time.Second - -func NewRegistrationReflector(p RegistrationReflectorParams) *RegistrationReflector { - - httpParams := cortexHttp.HttpServerParams{ - Logger: p.Logger.Named("relay-reflector"), - Config: p.Config, - } - - if p.Registry != nil { - httpParams.Registry = p.Registry - } - - // Injects rule credentials, so it must not be reachable off-host. Its only - // client is the broker running beside the agent. - server := cortexHttp.NewHttpServer(httpParams, - cortexHttp.WithName("relay-reflector"), - cortexHttp.WithLoopbackOnly(), - cortexHttp.WithReadTimeout(reflectorReadTimeout), - ) - - rr := &RegistrationReflector{ - transport: p.Transport, - server: server, - logger: httpParams.Logger, - mode: p.Config.HttpRelayReflectorMode, - config: p.Config, - } - rr.targets.Store(&map[string]proxyEntry{}) - - // Create WebSocket proxy with callbacks for tunnel lifecycle - rr.wsProxy = NewWebSocketProxy(httpParams.Logger, p.Transport) - rr.wsProxy.OnTunnelEstablished = func(target string) { - rr.logger.Info("WebSocket tunnel established", zap.String("target", target)) - } - - rr.RecordStartup() - - server.RegisterHandler(rr) - - if p.Lifecycle != nil { - p.Lifecycle.Append( - fx.Hook{ - OnStart: func(ctx context.Context) error { - _, err := rr.Start() - return err - }, - }, - ) - } - - return rr -} - -func (rr *RegistrationReflector) Start() (int, error) { - - if rr.serverStarted.CompareAndSwap(false, true) { - _, err := rr.server.Start() - if err != nil { - return 0, err - } - } - - return rr.server.Port(), nil -} - -func (rr *RegistrationReflector) Stop() error { - if rr.server != nil { - return rr.server.Close() - } - return nil -} - -// RecordTraffic updates the last traffic timestamp to now. -func (rr *RegistrationReflector) RecordTraffic() { - rr.lastTrafficTime.Store(time.Now().UnixMilli()) -} - -// LastTrafficTime returns the time of the last recorded traffic. -func (rr *RegistrationReflector) LastTrafficTime() time.Time { - return time.UnixMilli(rr.lastTrafficTime.Load()) -} - -// RecordStartup marks that the reflector (or the broker beside it) just -// (re)started. It never touches lastTrafficTime, so LastTrafficTime keeps -// meaning "last real relayed request" rather than being reset by restarts. -func (rr *RegistrationReflector) RecordStartup() { - rr.lastStartupTime.Store(time.Now().UnixMilli()) -} - -// LastStartupTime returns the time of the last recorded (re)start. -func (rr *RegistrationReflector) LastStartupTime() time.Time { - return time.UnixMilli(rr.lastStartupTime.Load()) -} - -// RecordTunnelActivity marks that the broker server just sent something down -// the websocket tunnel. It is kept apart from lastTrafficTime: a heartbeat -// proves the tunnel is alive, not that anything was relayed. -func (rr *RegistrationReflector) RecordTunnelActivity() { - rr.lastTunnelTime.Store(time.Now().UnixMilli()) -} - -// LastActivityTime is the latest of the last relayed request, the last frame -// from the broker server, and the last (re)start: the idle watchdog's clock. -// -// Relayed requests alone can't tell a dead tunnel from a quiet one: the -// broker server hands a token's requests to only its newest client, so every -// other replica sharing the token looks idle. Frames cover that when the -// tunnel runs through this reflector; in "traffic" mode it doesn't, and -// relayed requests are the only signal. -func (rr *RegistrationReflector) LastActivityTime() time.Time { - return time.UnixMilli(max( - rr.lastTrafficTime.Load(), - rr.lastTunnelTime.Load(), - rr.lastStartupTime.Load(), - )) -} - -// SetOnWSTunnelClose sets a callback invoked when a WebSocket tunnel closes. -// Used by the relay instance manager to trigger a broker restart. -func (rr *RegistrationReflector) SetOnWSTunnelClose(fn func()) { - if rr.wsProxy != nil { - rr.wsProxy.OnTunnelClosed = func(target string, duration time.Duration) { - rr.logger.Warn("WebSocket tunnel closed", - zap.String("target", target), - zap.Duration("duration", duration)) - fn() - } - } -} - -// IsWSTunnelConnected returns true if a WebSocket tunnel is currently active. -func (rr *RegistrationReflector) IsWSTunnelConnected() bool { - return rr.wsProxy != nil && rr.wsProxy.IsConnected() -} - -func (rr *RegistrationReflector) getProxy(targetURI string, isDefault bool, headers acceptfile.ResolverMap) (*proxyEntry, error) { - - if targetURI == "" { - return nil, fmt.Errorf("target URI cannot be empty") - } - - _, err := rr.Start() - if err != nil { - panic(fmt.Sprintf("failed to start registration reflector: %v", err)) - } - - newEntry, err := newProxyEntry(targetURI, isDefault, rr.server.Port(), headers, rr.transport) - if err != nil { - return nil, fmt.Errorf("failed to create new proxy entry: %w", err) - } - - key := newEntry.key() - - // Set before the entry is published so the copy in the map carries the - // header too, rather than only the reverse proxy's captured newEntry. - newEntry.addResponseHeader("x-axon-relay-instance", rr.config.InstanceId) - newEntry.logger = rr.logger - - // Copy-on-write: publish a new map rather than mutating the live one, so - // readers never synchronize. Retried on CAS failure because a concurrent - // registration may have published between the load and the swap. - for { - current := rr.targets.Load() - if entry, exists := (*current)[key]; exists { - return &entry, nil - } - - next := make(map[string]proxyEntry, len(*current)+1) - for k, v := range *current { - next[k] = v - } - next[key] = *newEntry - - if !rr.targets.CompareAndSwap(current, &next) { - continue - } - - entry := next[key] - rr.logger.Info("Registered redirector", - zap.String("targetURI", entry.TargetURI), - zap.String("proxyURI", entry.proxyURI), - zap.Bool("isDefault", entry.isDefault), - zap.String("key", key), - // Names only. A rule header value is a credential, and the - // resolver carries the accept-file value verbatim. - zap.Strings("headerNames", headers.Names()), - ) - return &entry, nil - } -} - -func (rr *RegistrationReflector) extractHash(part string) string { - // Check if the part is a valid hash (a number) - if !strings.HasPrefix(part, "!") || !strings.HasSuffix(part, "!") { - return "" - } - return part[1 : len(part)-1] -} - -func (rr *RegistrationReflector) parseTargetUri(proxyPath string) (*proxyEntry, string, error) { - path := strings.TrimLeft(proxyPath, "/") - slash := strings.Index(path, "/") - beforeSlash := path - remainder := "/" - if slash != -1 { - beforeSlash = path[:slash] - remainder = path[slash:] - } - hash := rr.extractHash(beforeSlash) - - targets := *rr.targets.Load() - - if hash == "" { - // find the default proxy entry - if entry, exists := targets["default"]; exists { - // Found the default proxy entry - return &entry, proxyPath, nil - } else { - // No default proxy entry found, return an error - return nil, "", fmt.Errorf("no default proxy entry found for path: %s", proxyPath) - } - } - - // the map is keyed by exactly the value key() returns - if entry, exists := targets[hash]; exists { - return &entry, remainder, nil - } - - return nil, "", fmt.Errorf("no proxy entry found for path: %s", proxyPath) -} - -type ProxyOption func(*proxyOption) - -type proxyOption struct { - isDefault bool - headerResolvers acceptfile.ResolverMap -} - -func WithDefault(value bool) ProxyOption { - return func(option *proxyOption) { - option.isDefault = value - } -} - -func WithHeaders(headers map[string]string) ProxyOption { - return func(option *proxyOption) { - if option.headerResolvers == nil { - option.headerResolvers = make(acceptfile.ResolverMap, len(headers)) - } - for k, v := range headers { - option.headerResolvers[k] = acceptfile.StringValueResolver(v) - } - } -} - -func WithHeadersResolver(headers acceptfile.ResolverMap) ProxyOption { - return func(option *proxyOption) { - option.headerResolvers = headers - } -} - -// getUriForTarget scans by target URI rather than by key. Only tests need this -// direction, so the linear scan is not on any request path. -func (rr *RegistrationReflector) getUriForTarget(target string) (string, error) { - - if target == "" { - return "", fmt.Errorf("target URI cannot be empty") - } - - for _, entry := range *rr.targets.Load() { - if entry.TargetURI == target { - return entry.proxyURI, nil - } - } - return "", fmt.Errorf("no proxy entry found for target URI: %s", target) -} - -func (rr *RegistrationReflector) ProxyURI(target string, options ...ProxyOption) string { - - opts := &proxyOption{} - - for _, opt := range options { - opt(opts) - } - - proxy, err := rr.getProxy(target, opts.isDefault, opts.headerResolvers) - if err != nil { - rr.logger.Error("Failed to get proxy URI", zap.Error(err)) - return target - } - return proxy.proxyURI -} - -func (rr *RegistrationReflector) RegisterRoutes(mux *mux.Router) error { - mux.PathPrefix("/").Handler(rr) - return nil -} - -func (rr *RegistrationReflector) ServeHTTP(w http.ResponseWriter, r *http.Request) { - - fields := []zap.Field{ - zap.String("method", r.Method), - zap.String("url", r.URL.String()), - } - if upgrade := r.Header.Get("Upgrade"); upgrade != "" { - fields = append(fields, zap.String("upgrade", upgrade)) - fields = append(fields, zap.String("connection", r.Header.Get("Connection"))) - } - rr.logger.Debug("Reflector request", fields...) - // Parse against the escaped (raw) path so that percent-encoded characters - // such as %2F in mid-path segments (e.g. GitLab namespace/project IDs) - // survive this hop. r.URL.Path is always percent-decoded; slicing it - // silently loses %2F, and writing r.URL.Path without also updating - // r.URL.RawPath causes EscapedPath() — which the downstream reverse proxy - // uses on the wire — to fall back to PathEscape(Path), which does not - // re-encode '/'. - escapedPath := r.URL.EscapedPath() - entry, newPath, err := rr.parseTargetUri(escapedPath) - if err != nil { - rr.logger.Error("Failed to find Entry for target URI", zap.Error(err)) - http.Error(w, "Invalid target URI", http.StatusBadGateway) - w.WriteHeader(http.StatusBadGateway) - return - } - - if !strings.HasPrefix(newPath, "/") { - newPath = "/" + newPath - } - decodedPath, err := url.PathUnescape(newPath) - if err != nil { - rr.logger.Error("Failed to decode target path", zap.Error(err)) - http.Error(w, "Invalid target path", http.StatusBadRequest) - return - } - r.URL.Path = decodedPath - r.URL.RawPath = newPath - rr.logger.Debug("Proxying request", - zap.String("targetURI", entry.TargetURI), - zap.String("proxyURI", entry.proxyURI), - zap.String("key", entry.key()), - zap.String("newPath", newPath), - ) - - // Strip before anything can forward, log, or fail: internal routing - // metadata must not survive on any path, rejections included. - requestedTargets := r.Header.Values(HeaderTargetHost) - r.Header.Del(HeaderTargetHost) - - // A tunnel carries no per-request routing, so a family has no authority to - // upgrade against. - if entry.wildcard != nil && IsWebSocketUpgrade(r) { - rr.logger.Error("WebSocket upgrade is not supported for a wildcard origin", - zap.String("targetURI", entry.TargetURI), - ) - writeFailureClass(w, ErrClassDestinationRejected, http.StatusForbidden) - return - } - - // The reason is safe to log; the requested value is not. - targetHost, err := entry.resolveTargetHost(requestedTargets) - if err != nil { - rr.logger.Error("Rejected destination", - zap.String("targetURI", entry.TargetURI), - zap.String("class", ErrClassDestinationRejected), - zap.Error(err), - ) - writeFailureClass(w, ErrClassDestinationRejected, http.StatusForbidden) - return - } - if targetHost != "" { - r = withDynamicTarget(r, targetHost) - } - - // Check if this is a WebSocket upgrade request - if rr.config.ReflectorWebSocketUpgrade && IsWebSocketUpgrade(r) { - rr.logger.Debug("Detected WebSocket upgrade request, using WebSocket proxy") - // Only the default entry is the broker's own tunnel to the server; a - // websocket to a customer origin says nothing about that tunnel. - var onActivity func() - if entry.isDefault { - onActivity = rr.RecordTunnelActivity - } - if err := rr.wsProxy.Proxy(w, r, entry.TargetURI, onActivity); err != nil { - rr.logger.Error("WebSocket proxy failed", zap.Error(err)) - } - return - } - - // Only record traffic for forwarded requests, not WebSocket tunnel - // infrastructure (primus). The traffic watermark is used to detect idle - // brokers, so it should only reflect real caller traffic. - rr.RecordTraffic() - - entry.serve(w, r) -} - -// serve resolves the rule's credentials and then proxies. -// -// Resolution belongs here rather than in the Director, which has no way to fail a -// request: a provider failure must stop the request before it is dialed, not -// degrade into a placeholder the upstream would refuse. -func (pe *proxyEntry) serve(w http.ResponseWriter, r *http.Request) { - resolvedHeaders, err := pe.headers.ToStringMap() - if err != nil { - if pe.logger != nil { - pe.logger.Error("Credential provider failed", - zap.String("targetURI", pe.TargetURI), - zap.String("class", ErrClassCredentialFailure), - zap.Error(err), - ) - } - writeFailureClass(w, ErrClassCredentialFailure, http.StatusBadGateway) - return - } - - pe.handler.ServeHTTP(w, withResolvedHeaders(r, resolvedHeaders)) -} - -// writeFailureClass names the failing component in a header as well as the body. -// The header is the machine-readable half: a body can come from an upstream, and -// a caller must be able to tell the two apart. -func writeFailureClass(w http.ResponseWriter, class string, status int) { - w.Header().Set(HeaderFailureClass, class) - http.Error(w, class, status) -} - -func hashString(s string) uint32 { - h := fnv.New32a() - h.Write([]byte(s)) - return h.Sum32() -} - -type proxyEntry struct { - isDefault bool - TargetURI string // Exported for clean access - proxyURI string - handler http.Handler - headers acceptfile.ResolverMap - responseHeaders map[string]string - hashCode string - // Set when the origin authorizes a family. Such an entry has no - // destination of its own; the authority arrives per request. - wildcard *wildcardOrigin - // Read by the reverse proxy's closures at request time, so getProxy can set - // it after construction and before the entry is published. - logger *zap.Logger -} - -// dynamicTargetContextKey carries the validated per-request target host from -// ServeHTTP to the Director, so a rewrite is impossible without the -// allowlist check having run. -type dynamicTargetContextKey struct{} - -func withDynamicTarget(r *http.Request, host string) *http.Request { - return r.WithContext(context.WithValue(r.Context(), dynamicTargetContextKey{}, host)) -} - -func dynamicTargetFromRequest(req *http.Request) (string, bool) { - host, ok := req.Context().Value(dynamicTargetContextKey{}).(string) - return host, ok && host != "" -} - -// resolvedHeadersContextKey carries the rule's resolved headers from ServeHTTP to -// the Director. The Director cannot fail a request, so resolution - and any -// credential-provider failure - has to happen before it runs. -type resolvedHeadersContextKey struct{} - -func withResolvedHeaders(r *http.Request, headers map[string]string) *http.Request { - return r.WithContext(context.WithValue(r.Context(), resolvedHeadersContextKey{}, headers)) -} - -func resolvedHeadersFromRequest(req *http.Request) map[string]string { - headers, _ := req.Context().Value(resolvedHeadersContextKey{}).(map[string]string) - return headers -} - -func newProxyEntry(targetURI string, isDefault bool, port int, headers acceptfile.ResolverMap, transport *http.Transport) (*proxyEntry, error) { - if targetURI == "" { - return nil, fmt.Errorf("target URI cannot be empty") - } - - asUri, wildcard, err := parseOrigin(targetURI) - if err != nil { - return nil, err - } - - // Create the reverse proxy - proxy := httputil.NewSingleHostReverseProxy(asUri) - - pe := &proxyEntry{ - isDefault: isDefault, - TargetURI: targetURI, - handler: proxy, - headers: headers, - wildcard: wildcard, - } - - // Set up the director to handle host and headers - defaultDirector := proxy.Director - proxy.Director = func(req *http.Request) { - defaultDirector(req) - req.Host = asUri.Host - - // A wildcard entry always has one, because ServeHTTP rejects the - // request otherwise, so the literal "*" in asUri is never dialed. - if host, ok := dynamicTargetFromRequest(req); ok { - // The header names a host; the origin keeps deciding the port. - if port := asUri.Port(); port != "" { - host = net.JoinHostPort(host, port) - } - req.URL.Host = host - req.Host = host - } - - // ServeHTTP resolved these, so the provider runs once per request and its - // failure has already stopped the request. Absent means no rule headers. - for headerName, headerValue := range resolvedHeadersFromRequest(req) { - req.Header.Set(headerName, headerValue) - } - } - proxy.ModifyResponse = func(resp *http.Response) error { - // An upstream must not be able to name a failure class, so its copy goes - // before anything downstream can read one. - resp.Header.Del(HeaderFailureClass) - for headerName, headerValue := range pe.responseHeaders { - resp.Header.Set(headerName, headerValue) - } - return nil - } - proxy.ErrorHandler = func(w http.ResponseWriter, req *http.Request, err error) { - // DNS, connection, and TLS failures all arrive here. They are this agent's - // own network rather than the upstream's answer, and saying so keeps a - // caller from retrying against an upstream that was never reached. - if pe.logger != nil { - pe.logger.Error("Upstream connection failed", - zap.String("targetURI", pe.TargetURI), - zap.String("class", ErrClassNetworkFailure), - zap.Error(err), - ) - } - writeFailureClass(w, ErrClassNetworkFailure, http.StatusBadGateway) - } - - // Set transport if provided - if transport != nil { - proxy.Transport = transport - } - - pe.proxyURI = pe.encodeProxyUri(targetURI, port, isDefault) - - return pe, nil -} - -// resolveTargetHost returns the host to retarget to, or "" to dial the entry's -// declared origin. Fail-closed both ways: a family never falls back to a -// declared host, and a concrete origin never ignores a value that disagrees. -func (pe *proxyEntry) resolveTargetHost(values []string) (string, error) { - if len(values) > 1 { - return "", fmt.Errorf("duplicate target host") - } - - if len(values) == 0 { - if pe.wildcard != nil { - return "", fmt.Errorf("wildcard origin requires a target host") - } - return "", nil - } - - host, err := parseTargetHost(values[0]) - if err != nil { - return "", err - } - - if pe.wildcard != nil { - if !pe.wildcard.matches(host) { - return "", fmt.Errorf("target host is outside the origin policy") - } - return host, nil - } - - // The value only ever restates the declared authority, so anything else is - // a defect or a probe. - declared, parseErr := url.Parse(pe.TargetURI) - if parseErr != nil || !strings.EqualFold(declared.Hostname(), host) { - return "", fmt.Errorf("target host disagrees with the declared origin") - } - return "", nil -} - -func (pe *proxyEntry) key() string { - if pe.isDefault { - return "default" - } - if pe.hashCode == "" { - - key := pe.TargetURI - - if len(pe.headers) > 0 { - // Create a unique key that includes headers to allow different header sets for the same URI. - // Names() sorts, so the hash is stable across map iteration order. - headerKey := "" - for _, k := range pe.headers.Names() { - headerKey += fmt.Sprintf("|%s=%s", k, pe.headers.ResolverKey(k)) - } - key = key + headerKey - } - hash := hashString(key) - pe.hashCode = fmt.Sprintf("%d", hash) - } - return pe.hashCode - -} - -func (pe *proxyEntry) addResponseHeader(name, value string) { - if pe.responseHeaders == nil { - pe.responseHeaders = make(map[string]string) - } - pe.responseHeaders[name] = value -} - -func (pe *proxyEntry) encodeProxyUri(targetURI string, port int, isDefault bool) string { - // Matches the loopback bind; "localhost" also resolves to ::1. - baseProxyURI := fmt.Sprintf("http://127.0.0.1:%d", port) - if isDefault { - // for default proxy, we only change the host and port - // to be our proxy - parsedProxyURI, err := url.Parse(baseProxyURI) - if err != nil { - panic(fmt.Sprintf("failed to parse proxy URI %q: %v", baseProxyURI, err)) - } - - parsedTarget, err := url.Parse(targetURI) - if err != nil { - panic(fmt.Errorf("failed to parse target URI %q: %v", targetURI, err)) - } - parsedTarget.Host = parsedProxyURI.Host - parsedTarget.Scheme = parsedProxyURI.Scheme - return parsedTarget.String() - } - return fmt.Sprintf("%s/!%s!", baseProxyURI, pe.key()) -} diff --git a/agent/server/snykbroker/reflector_accept_file_wiring_test.go b/agent/server/snykbroker/reflector_accept_file_wiring_test.go deleted file mode 100644 index ef8ffe99..00000000 --- a/agent/server/snykbroker/reflector_accept_file_wiring_test.go +++ /dev/null @@ -1,160 +0,0 @@ -package snykbroker - -import ( - "fmt" - "net/http" - "net/http/httptest" - "testing" - - "github.com/cortexapps/axon/config" - "github.com/cortexapps/axon/server/snykbroker/acceptfile" - "github.com/prometheus/client_golang/prometheus" - "github.com/stretchr/testify/require" - "go.uber.org/zap" -) - -// renderEnv is the reflector render step in isolation: a manager with only the -// fields that step reads, so the wiring is testable without the broker -// supervisor or a live registration. -type renderEnv struct { - mgr *relayInstanceManager - reflector *RegistrationReflector -} - -func newRenderEnv(t *testing.T, mode config.RelayReflectorMode) *renderEnv { - logger := newTestLogger(t) - cfg := config.AgentConfig{ - HttpRelayReflectorMode: mode, - ReflectorWebSocketUpgrade: true, - } - rr := newReflectorWithDrain(t, RegistrationReflectorParams{ - Logger: logger, - Registry: prometheus.NewRegistry(), - Config: cfg, - }) - t.Cleanup(func() { rr.Stop() }) - return &renderEnv{ - mgr: &relayInstanceManager{config: cfg, logger: logger, reflector: rr}, - reflector: rr, - } -} - -func (e *renderEnv) render(t *testing.T, content string) error { - t.Helper() - af, err := acceptfile.NewAcceptFile([]byte(content), e.mgr.config, e.mgr.logger) - require.NoError(t, err) - _, err = af.Render(zap.NewNop(), e.mgr.reflectorRenderStep) - return err -} - -func TestRenderRegistersWildcardOrigin(t *testing.T) { - env := newRenderEnv(t, config.RelayReflectorAllTraffic) - plain := newRecordingBackend(t, "plain") - - require.NoError(t, env.render(t, fmt.Sprintf(`{"private": [ - {"method": "any", "origin": "https://*.api.example.net", "path": "/*"}, - {"method": "any", "origin": "%s", "path": "/*"} - ]}`, plain.server.URL))) - - wildcardURI, err := env.reflector.getUriForTarget("https://*.api.example.net") - require.NoError(t, err) - wildcardEntry, _, err := env.reflector.parseTargetUri(proxyPath(t, wildcardURI)) - require.NoError(t, err) - require.NotNil(t, wildcardEntry.wildcard) - - plainURI, err := env.reflector.getUriForTarget(plain.server.URL) - require.NoError(t, err) - plainEntry, _, err := env.reflector.parseTargetUri(proxyPath(t, plainURI)) - require.NoError(t, err) - require.Nil(t, plainEntry.wildcard) -} - -func TestRenderedWildcardEnforcesItsOrigin(t *testing.T) { - env := newRenderEnv(t, config.RelayReflectorAllTraffic) - other := newRecordingBackend(t, "b") - - require.NoError(t, env.render(t, `{"private": [ - {"method": "any", "origin": "https://*.api.example.net", "path": "/*"} - ]}`)) - - uri, err := env.reflector.getUriForTarget("https://*.api.example.net") - require.NoError(t, err) - - req := httptest.NewRequest("GET", proxyPath(t, uri)+"/v1/things", nil) - req.Header.Set(HeaderTargetHost, other.hostPort(t)) - rec := httptest.NewRecorder() - env.reflector.ServeHTTP(rec, req) - - require.Equal(t, http.StatusForbidden, rec.Code) - require.Contains(t, rec.Body.String(), ErrClassDestinationRejected) - hits, _, _ := other.snapshot() - require.Equal(t, 0, hits) -} - -func TestRenderRejectsMalformedWildcardOrigin(t *testing.T) { - for name, origin := range map[string]string{ - "public suffix": "https://*.com", - "plaintext": "http://*.api.example.net", - "partial label": "https://a*.api.example.net", - } { - t.Run(name, func(t *testing.T) { - env := newRenderEnv(t, config.RelayReflectorAllTraffic) - err := env.render(t, fmt.Sprintf(`{"private": [ - {"method": "any", "origin": %q, "path": "/*"} - ]}`, origin)) - require.Error(t, err) - }) - } -} - -// With verification off, anything answering the connection can claim the -// authorized name, so a family authorizes nothing. -func TestRenderRejectsWildcardOriginWithTLSVerificationDisabled(t *testing.T) { - env := newRenderEnv(t, config.RelayReflectorAllTraffic) - env.mgr.config.HttpDisableTLS = true - - err := env.render(t, `{"private": [ - {"method": "any", "origin": "https://*.api.example.net", "path": "/*"} - ]}`) - - require.ErrorIs(t, err, ErrWildcardOriginRequiresTLSVerification) -} - -// A concrete origin names one host the operator chose, so that stays their -// call and must not break existing deployments. -func TestRenderAllowsConcreteOriginWithTLSVerificationDisabled(t *testing.T) { - env := newRenderEnv(t, config.RelayReflectorAllTraffic) - env.mgr.config.HttpDisableTLS = true - backend := newRecordingBackend(t, "a") - - require.NoError(t, env.render(t, fmt.Sprintf(`{"private": [ - {"method": "any", "origin": "%s", "path": "/*"} - ]}`, backend.server.URL))) -} - -func TestRenderRejectsWildcardOriginWithReflectorDisabled(t *testing.T) { - env := newRenderEnv(t, config.RelayReflectorDisabled) - af, err := acceptfile.NewAcceptFile([]byte(`{"private": [ - {"method": "any", "origin": "https://*.api.example.net", "path": "/*"} - ]}`), env.mgr.config, env.mgr.logger) - require.NoError(t, err) - - require.PanicsWithValue(t, - "ENABLE_RELAY_REFLECTOR must be set to 'all' or 'traffic' to use a wildcard origin in accept files", - func() { _, _ = af.Render(zap.NewNop(), env.mgr.reflectorRenderStep) }) -} - -func TestRenderLeavesConcreteRuleAlone(t *testing.T) { - env := newRenderEnv(t, config.RelayReflectorAllTraffic) - backend := newRecordingBackend(t, "a") - - require.NoError(t, env.render(t, fmt.Sprintf(`{"private": [ - {"method": "any", "origin": "%s", "path": "/*"} - ]}`, backend.server.URL))) - - uri, err := env.reflector.getUriForTarget(backend.server.URL) - require.NoError(t, err) - entry, _, err := env.reflector.parseTargetUri(proxyPath(t, uri)) - require.NoError(t, err) - require.Nil(t, entry.wildcard) -} diff --git a/agent/server/snykbroker/reflector_boundary_test.go b/agent/server/snykbroker/reflector_boundary_test.go deleted file mode 100644 index d7ae02f2..00000000 --- a/agent/server/snykbroker/reflector_boundary_test.go +++ /dev/null @@ -1,412 +0,0 @@ -package snykbroker - -import ( - "bufio" - "bytes" - "context" - "crypto/tls" - "crypto/x509" - "fmt" - "net" - "net/http" - "net/http/httptest" - "net/url" - "sync" - "testing" - "time" - - "github.com/cortexapps/axon/config" - "github.com/cortexapps/axon/server/snykbroker/acceptfile" - "github.com/gorilla/websocket" - "github.com/prometheus/client_golang/prometheus" - "github.com/stretchr/testify/require" - "go.uber.org/zap" - "go.uber.org/zap/zapcore" -) - -// connTap records every byte the agent writes to an upstream connection, so a -// test can assert on what actually left the process rather than on what a -// handler happened to observe. -type connTap struct { - mu sync.Mutex - written bytes.Buffer -} - -func (tap *connTap) wrap(conn net.Conn) net.Conn { - return &tappedConn{Conn: conn, tap: tap} -} - -func (tap *connTap) bytesWritten() []byte { - tap.mu.Lock() - defer tap.mu.Unlock() - return append([]byte(nil), tap.written.Bytes()...) -} - -type tappedConn struct { - net.Conn - tap *connTap -} - -func (c *tappedConn) Write(p []byte) (int, error) { - c.tap.mu.Lock() - c.tap.written.Write(p) - c.tap.mu.Unlock() - return c.Conn.Write(p) -} - -// newCapturingLogger returns a logger and a reader over everything it emitted. -// Like newTestLogger it stays safe once the test finishes, because request -// goroutines outlive the test that started them. -func newCapturingLogger(t *testing.T) (*zap.Logger, func() string) { - t.Helper() - w := &syncBuffer{} - logger := zap.New(zapcore.NewCore( - zapcore.NewConsoleEncoder(zap.NewDevelopmentEncoderConfig()), - zapcore.AddSync(w), - zapcore.DebugLevel, - )) - return logger, w.contents -} - -// syncBuffer is a bytes.Buffer safe to read while writers are still going. -// Its writers outlive the test that started them — the supervisor's line -// pumps keep draining after Wait() returns, and request goroutines keep -// logging after the reflector test finishes — so an unguarded buffer races -// with any assertion on its contents. -type syncBuffer struct { - mu sync.Mutex - buf bytes.Buffer -} - -func (b *syncBuffer) Write(p []byte) (int, error) { - b.mu.Lock() - defer b.mu.Unlock() - return b.buf.Write(p) -} - -func (b *syncBuffer) contents() string { - b.mu.Lock() - defer b.mu.Unlock() - return b.buf.String() -} - -func newReflectorWith(t *testing.T, logger *zap.Logger, transport *http.Transport) *RegistrationReflector { - t.Helper() - rr := newReflectorWithDrain(t, RegistrationReflectorParams{ - Logger: logger, - Registry: prometheus.NewRegistry(), - Transport: transport, - Config: config.AgentConfig{ReflectorWebSocketUpgrade: true}, - }) - t.Cleanup(func() { rr.Stop() }) - return rr -} - -// The WebSocket path bypasses the Director and writes the caller's header set -// verbatim, so the single removal in ServeHTTP is the only thing standing -// between an internal routing value and a third-party upstream. -// -// The origin is "localhost" rather than a synthetic name because the tunnel -// dials with a plain net.Dialer: it ignores the transport's DialContext, so -// nothing else here can stand in for DNS. It must also be a name and not -// httptest's 127.0.0.1, since an IP literal is never an accepted authority. -func TestTargetHostHeaderNeverReachesAWebSocketUpstream(t *testing.T) { - env := newTestReflectorEnv(t) - - var mu sync.Mutex - var upstream http.Header - env.Router.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) { - mu.Lock() - upstream = r.Header.Clone() - mu.Unlock() - - conn, err := testUpgrader.Upgrade(w, r, nil) - if err != nil { - t.Logf("WebSocket upgrade failed: %v", err) - return - } - defer conn.Close() - for { - messageType, message, err := conn.ReadMessage() - if err != nil { - return - } - if err := conn.WriteMessage(messageType, message); err != nil { - return - } - } - }) - - origin := "http://localhost:" + portOf(t, env.Server.URL) - proxyURI := env.Reflector.ProxyURI(origin, - WithHeaders(map[string]string{"Authorization": "Bearer minted"}), - ) - - header := http.Header{} - header.Set(HeaderTargetHost, "localhost") - conn, resp, err := websocket.DefaultDialer.Dial("ws"+proxyURI[len("http"):]+"/ws", header) - require.NoError(t, err) - defer conn.Close() - require.Equal(t, http.StatusSwitchingProtocols, resp.StatusCode) - - require.NoError(t, conn.WriteMessage(websocket.TextMessage, []byte("ping"))) - _, message, err := conn.ReadMessage() - require.NoError(t, err) - require.Equal(t, "ping", string(message)) - - mu.Lock() - defer mu.Unlock() - require.NotNil(t, upstream, "the upstream never received the upgrade") - require.Empty(t, upstream.Values(HeaderTargetHost), - "the routing header reached the upstream through the tunnel") -} - -// Validation and removal both look up the canonical header key. Go canonicalises -// during parsing, so every spelling arrives under the same key - but only over a -// real socket, which is why this test writes request bytes rather than building -// a request in process. -// -// A missed spelling would not merely skip validation: the value would also -// survive removal and be forwarded. The two outcomes are distinguishable, so -// this asserts the forwarded case never happens. -func TestTargetHostHeaderIsValidatedInEverySpelling(t *testing.T) { - for _, spelling := range []string{ - "X-Cortex-Target-Host", - "x-cortex-target-host", - "X-CORTEX-TARGET-HOST", - "x-Cortex-target-host", - } { - t.Run(spelling, func(t *testing.T) { - env := newTestReflectorEnv(t) - backend := newRecordingBackend(t, "reached") - - origin := "http://localhost:" + portOf(t, backend.server.URL) - proxyURI := env.Reflector.ProxyURI(origin, - WithHeaders(map[string]string{"Authorization": "Bearer minted"}), - ) - - status := rawRequest(t, env.Reflector.server.Port(), - proxyPath(t, proxyURI)+"/v1/things", - spelling+": attacker-chosen.example.com") - - require.Equal(t, http.StatusForbidden, status, - "a value disagreeing with the declared origin must be rejected") - hits, _, _ := backend.snapshot() - require.Equal(t, 0, hits, "the rejected request reached the upstream") - }) - } -} - -// A hostile resolver is the case certificate verification exists to catch: DNS -// answers for an authorized name with a host that cannot prove it. -// -// The transport verifies against the backend's own certificate pool, so the -// name mismatch is the only reason the handshake can fail. Asserting on the -// bytes the agent wrote is what makes this prove the credential was never sent -// rather than that the request failed: the handshake aborts before any -// application data, so a bearer token appearing in that capture would be the -// leak. -func TestHostileResolverReceivesNoAuthorizationHeader(t *testing.T) { - backend := newRecordingTLSBackend(t, "a") - pool := x509.NewCertPool() - pool.AddCert(backend.server.Certificate()) - - tap := &connTap{} - transport := &http.Transport{ - DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { - host, _, err := net.SplitHostPort(addr) - if err != nil { - return nil, err - } - if host != "alpha.axon.example.com" { - return nil, fmt.Errorf("no backend registered for %q", host) - } - conn, err := net.Dial(network, backend.hostPort(t)) - if err != nil { - return nil, err - } - return tap.wrap(conn), nil - }, - // Verification on, and the backend's own root: a mismatched name is - // then the only way the handshake can fail. - TLSClientConfig: &tls.Config{RootCAs: pool}, - } - - rr := newReflectorWith(t, newTestLogger(t), transport) - headers := acceptfile.NewResolverMapFromMap(map[string]string{"Authorization": "Bearer minted"}) - proxyURI := rr.ProxyURI("https://*.axon.example.com", WithHeadersResolver(headers)) - - req := httptest.NewRequest("GET", proxyPath(t, proxyURI)+"/v1/things", nil) - req.Header.Set(HeaderTargetHost, "alpha.axon.example.com") - rec := httptest.NewRecorder() - rr.ServeHTTP(rec, req) - - require.Equal(t, http.StatusBadGateway, rec.Code) - hits, _, _ := backend.snapshot() - require.Equal(t, 0, hits, "the request was served despite the certificate mismatch") - - written := tap.bytesWritten() - require.NotEmpty(t, written, "nothing was dialed, so this proves nothing") - require.NotContains(t, string(written), "Authorization") - require.NotContains(t, string(written), "Bearer minted") -} - -// A redirect is a new destination decision, and the caller owns it. The relay -// returns the 3xx so that the next request re-enters authority capture. -// -// This holds today only because httputil.ReverseProxy dials through an -// http.Transport, which does not follow redirects. A change to a -// redirect-following client would carry the injected credential to whatever -// Location named, out of policy or not, and nothing else would fail. -func TestUpstreamRedirectIsReturnedRatherThanFollowed(t *testing.T) { - redirectTarget := newRecordingTLSBackend(t, "redirect target") - authorized := &recordingBackend{} - authorized.server = httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - authorized.mu.Lock() - authorized.hits++ - authorized.header = r.Header.Clone() - authorized.mu.Unlock() - w.Header().Set("Location", "https://evil.example.com/v1/things") - w.WriteHeader(http.StatusFound) - })) - t.Cleanup(authorized.server.Close) - - backends := map[string]*recordingBackend{ - "a.axon.example.com": authorized, - // Registered so a followed redirect would connect. It must not. - "evil.example.com": redirectTarget, - } - transport := routedTransport(t, backends) - rr := newReflectorWith(t, newTestLogger(t), transport) - - // Reach the redirect target through the same dialer first, so the zero - // below is the transport declining to follow rather than a dead route. - probe := &http.Client{Transport: transport} - resp, err := probe.Get("https://evil.example.com/v1/things") - require.NoError(t, err) - require.NoError(t, resp.Body.Close()) - require.Equal(t, http.StatusOK, resp.StatusCode) - reachable, _, _ := redirectTarget.snapshot() - require.Equal(t, 1, reachable) - - headers := acceptfile.NewResolverMapFromMap(map[string]string{"Authorization": "Bearer minted"}) - proxyURI := rr.ProxyURI("https://*.axon.example.com", WithHeadersResolver(headers)) - - req := httptest.NewRequest("GET", proxyPath(t, proxyURI)+"/v1/things", nil) - req.Header.Set(HeaderTargetHost, "a.axon.example.com") - rec := httptest.NewRecorder() - rr.ServeHTTP(rec, req) - - require.Equal(t, http.StatusFound, rec.Code, "the redirect was consumed rather than returned") - require.Equal(t, "https://evil.example.com/v1/things", rec.Header().Get("Location")) - - authorizedHits, _, authorizedHeader := authorized.snapshot() - require.Equal(t, 1, authorizedHits) - require.Equal(t, "Bearer minted", authorizedHeader.Get("Authorization")) - - hits, _, header := redirectTarget.snapshot() - require.Equal(t, reachable, hits, "the redirect was followed to a destination nobody authorized") - require.Empty(t, header.Get("Authorization"), - "the injected credential was carried to the redirect target") -} - -// The rejection reason is safe to record; the requested authority is not. An -// operator reading logs, or anything shipping them onward, must not be handed -// the value a caller asked for. -func TestRoutingMetadataReachesNeitherTheResponseNorTheLogs(t *testing.T) { - const rejected = "attacker-chosen.example.com" - const accepted = "a.axon.example.com" - - backend := newRecordingTLSBackend(t, "a") - logger, logged := newCapturingLogger(t) - transport := &http.Transport{ - DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { - return net.Dial(network, backend.hostPort(t)) - }, - TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, - } - rr := newReflectorWith(t, logger, transport) - - headers := acceptfile.NewResolverMapFromMap(map[string]string{"Authorization": "Bearer minted"}) - proxyURI := rr.ProxyURI("https://*.axon.example.com", WithHeadersResolver(headers)) - path := proxyPath(t, proxyURI) + "/v1/things" - - req := httptest.NewRequest("GET", path, nil) - req.Header.Set(HeaderTargetHost, rejected) - rec := httptest.NewRecorder() - rr.ServeHTTP(rec, req) - require.Equal(t, http.StatusForbidden, rec.Code) - require.Contains(t, rec.Body.String(), ErrClassDestinationRejected) - require.Empty(t, rec.Header().Values(HeaderTargetHost)) - - req = httptest.NewRequest("GET", path, nil) - req.Header.Set(HeaderTargetHost, accepted) - rec = httptest.NewRecorder() - rr.ServeHTTP(rec, req) - require.Equal(t, http.StatusOK, rec.Code) - require.Empty(t, rec.Header().Values(HeaderTargetHost), - "the routing header was echoed back to the caller") - - output := logged() - require.NotContains(t, output, rejected, "a rejected authority was written to the log") - require.NotContains(t, output, accepted, "a routed authority was written to the log") - require.Contains(t, output, ErrClassDestinationRejected, - "the rejection itself must still be recorded") -} - -// A rule header value is a credential. Registration logs the rule, so it must -// log the names and not the map. -// -// The map was safe to log only by accident: zap falls back to json.Marshal, -// which fails on the resolver's func field and drops the whole field. Making -// ValueResolver serializable would have written every accept-file header value -// to the log at INFO, with nothing to catch it. -func TestRegistrationLogsHeaderNamesRatherThanValues(t *testing.T) { - const secret = "Bearer sk-literal-value" - - logger, logged := newCapturingLogger(t) - rr := newReflectorWith(t, logger, nil) - backend := newRecordingBackend(t, "a") - - rr.ProxyURI(backend.server.URL, WithHeaders(map[string]string{ - "Authorization": secret, - "X-GitHub-Api-Version": "2022-11-28", - })) - - output := logged() - require.NotContains(t, output, secret, "a rule credential was written to the log") - require.NotContains(t, output, "sk-literal-value") - require.Contains(t, output, "Authorization", "the header names are still worth recording") - require.Contains(t, output, "X-GitHub-Api-Version") -} - -func portOf(t *testing.T, rawURL string) string { - t.Helper() - u, err := url.Parse(rawURL) - require.NoError(t, err) - return u.Port() -} - -// rawRequest writes request bytes to the reflector's own listener and returns -// the status code, so header names arrive exactly as spelled here. -func rawRequest(t *testing.T, port int, path string, headerLines ...string) int { - t.Helper() - - conn, err := net.DialTimeout("tcp", net.JoinHostPort("127.0.0.1", fmt.Sprint(port)), 5*time.Second) - require.NoError(t, err) - defer conn.Close() - require.NoError(t, conn.SetDeadline(time.Now().Add(10*time.Second))) - - request := "GET " + path + " HTTP/1.1\r\nHost: 127.0.0.1\r\n" - for _, line := range headerLines { - request += line + "\r\n" - } - request += "Connection: close\r\n\r\n" - _, err = conn.Write([]byte(request)) - require.NoError(t, err) - - resp, err := http.ReadResponse(bufio.NewReader(conn), nil) - require.NoError(t, err) - defer resp.Body.Close() - return resp.StatusCode -} diff --git a/agent/server/snykbroker/reflector_dynamic_target_test.go b/agent/server/snykbroker/reflector_dynamic_target_test.go deleted file mode 100644 index 66bc93bb..00000000 --- a/agent/server/snykbroker/reflector_dynamic_target_test.go +++ /dev/null @@ -1,517 +0,0 @@ -package snykbroker - -import ( - "context" - "crypto/tls" - "fmt" - "net" - "net/http" - "net/http/httptest" - "net/url" - "strings" - "sync" - "testing" - - "github.com/cortexapps/axon/config" - "github.com/cortexapps/axon/server/snykbroker/acceptfile" - "github.com/prometheus/client_golang/prometheus" - "github.com/stretchr/testify/require" -) - -type recordingBackend struct { - server *httptest.Server - mu sync.Mutex - hits int - host string - header http.Header -} - -func newRecordingBackend(t *testing.T, body string) *recordingBackend { - return newRecordingBackendWith(t, body, httptest.NewServer) -} - -func newRecordingTLSBackend(t *testing.T, body string) *recordingBackend { - return newRecordingBackendWith(t, body, httptest.NewTLSServer) -} - -func newRecordingBackendWith(t *testing.T, body string, start func(http.Handler) *httptest.Server) *recordingBackend { - rb := &recordingBackend{} - rb.server = start(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - rb.mu.Lock() - rb.hits++ - rb.host = r.Host - rb.header = r.Header.Clone() - rb.mu.Unlock() - w.WriteHeader(http.StatusOK) - w.Write([]byte(body)) - })) - t.Cleanup(rb.server.Close) - return rb -} - -func (rb *recordingBackend) hostPort(t *testing.T) string { - u, err := url.Parse(rb.server.URL) - require.NoError(t, err) - return u.Host -} - -func (rb *recordingBackend) snapshot() (int, string, http.Header) { - rb.mu.Lock() - defer rb.mu.Unlock() - return rb.hits, rb.host, rb.header -} - -// newRoutedReflector resolves synthetic hostnames to local backends. Wildcard -// hosts never exist in DNS, and a concrete origin needs a real hostname before -// a target can agree with it, which httptest's 127.0.0.1 cannot provide. -// Verification is skipped because the backends' certificates do not carry the -// synthetic names. -func newRoutedReflector(t *testing.T, backends map[string]*recordingBackend) *RegistrationReflector { - t.Helper() - transport := routedTransport(t, backends) - rr := newReflectorWithDrain(t, RegistrationReflectorParams{ - Logger: newTestLogger(t), - Registry: prometheus.NewRegistry(), - Transport: transport, - Config: config.AgentConfig{ReflectorWebSocketUpgrade: true}, - }) - t.Cleanup(func() { rr.Stop() }) - return rr -} - -// routedTransport is the DNS stand-in on its own, for tests that also need to -// reach a backend without going through the reflector. -func routedTransport(t *testing.T, backends map[string]*recordingBackend) *http.Transport { - t.Helper() - return &http.Transport{ - DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { - host, _, err := net.SplitHostPort(addr) - if err != nil { - return nil, err - } - backend, ok := backends[host] - if !ok { - return nil, fmt.Errorf("no backend registered for %q", host) - } - return net.Dial(network, backend.hostPort(t)) - }, - TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, - } -} - -func TestParseOriginAcceptsWildcardFamilies(t *testing.T) { - for _, origin := range []string{ - "https://*.api.example.net", - "https://*.internal.api.example.net", - "https://*.axon.example.com", - "https://*.api.example.net:8443", - "https://*.something.com.internal:8443", - } { - _, wildcard, err := parseOrigin(origin) - require.NoError(t, err, "origin=%q", origin) - require.NotNil(t, wildcard, "origin=%q", origin) - } -} - -func TestParseOriginRejectsUnusableWildcards(t *testing.T) { - cases := map[string]string{ - "plaintext": "http://*.api.example.net", - "bare wildcard": "https://*", - "partial label": "https://a*.api.example.net", - "non-leftmost": "https://foo.*.api.example.net", - "two wildcards": "https://*.*.api.example.net", - "public suffix": "https://*.com", - "multipart public sfx": "https://*.co.uk", - "empty suffix": "https://*.", - "port zero": "https://*.api.example.net:0", - "port out of range": "https://*.api.example.net:70000", - } - for name, origin := range cases { - t.Run(name, func(t *testing.T) { - _, _, err := parseOrigin(origin) - require.Error(t, err) - }) - } -} - -func TestParseOriginLeavesConcreteOriginsAlone(t *testing.T) { - for _, origin := range []string{ - "https://beta.api.example.net", - "http://127.0.0.1:8080", - } { - asURL, wildcard, err := parseOrigin(origin) - require.NoError(t, err, "origin=%q", origin) - require.Nil(t, wildcard, "origin=%q", origin) - require.NotNil(t, asURL) - } -} - -// A wildcard certificate covers a single label, so a multi-label match would -// authorize names that verification then refuses. If this fails, the fix is -// not to relax it. -func TestWildcardMatchesExactlyOneLabel(t *testing.T) { - _, wildcard, err := parseOrigin("https://*.api.example.net") - require.NoError(t, err) - - for _, host := range []string{ - "alpha.api.example.net", - "eu-west1-compute.api.example.net", - } { - require.True(t, wildcard.matches(host), "host=%q", host) - } - - for _, host := range []string{ - "a.b.api.example.net", - "svc.internal.api.example.net", - "api.example.net", - "evilapi.example.net", - "notapi.example.net", - "alpha.api.example.net.evil.com", - "evil.com", - } { - require.False(t, wildcard.matches(host), "host=%q", host) - } -} - -// parseTargetHost is not a hostname validator, so this covers only what it -// still claims: the shapes that would confuse the origin match or dial -// something other than a host. Everything else is the match's job, and -// TestPolicyRefusesValuesOutsideTheFamily covers that. -func TestParseTargetHostNormalizesAndRejects(t *testing.T) { - host, err := parseTargetHost("ALPHA.API.Example.NET") - require.NoError(t, err) - require.Equal(t, "alpha.api.example.net", host) - - cases := map[string]string{ - "empty": "", - "comma joined": "alpha.api.example.net,beta.api.example.net", - "leading space": " alpha.api.example.net", - "inner space": "alpha api.example.net", - "tab": "alpha.api.example.net\t", - "carriage": "alpha.api.example.net\r\nX-Evil: y", - "default port": "alpha.api.example.net:443", - "other port": "alpha.api.example.net:8443", - "ipv4": "127.0.0.1", - "ipv6": "::1", - } - for name, value := range cases { - t.Run(name, func(t *testing.T) { - _, err := parseTargetHost(value) - require.Error(t, err) - }) - } -} - -// Ordinary hostnames must reach the dial. The double-hyphen cases are here on -// purpose: they are valid DNS but idna.Lookup rejects a hyphen in label -// positions 3-4, which IDNA reserves for "xn--". An earlier revision of this -// change validated through that profile and would have refused a real -// destination. If a strict validator ever comes back, this is what catches it. -func TestPolicyAdmitsOrdinaryHostnames(t *testing.T) { - entry, err := newProxyEntry("https://*.example.net", false, 1234, nil, nil) - require.NoError(t, err) - - for _, value := range []string{ - "alpha.example.net", - "eu-west1-compute.example.net", - "my-service-01.example.net", - "ab--cd.example.net", - "x1--y.example.net", - "a--b.example.net", - "1.example.net", - "xn--e1afmkfd.example.net", - strings.Repeat("a", 63) + ".example.net", - } { - host, err := entry.resolveTargetHost([]string{value}) - require.NoError(t, err, "value=%q", value) - require.Equal(t, value, host, "value=%q", value) - } -} - -// The origin match is the destination control, not parseTargetHost, so these -// have to be refused by the policy however well-formed they look. -func TestPolicyRefusesValuesOutsideTheFamily(t *testing.T) { - entry, err := newProxyEntry("https://*.api.example.net", false, 1234, nil, nil) - require.NoError(t, err) - - cases := map[string]string{ - "other family": "alpha.evil.example.net", - "suffix as prefix": "alpha.api.example.net.evil.com", - "parent of family": "api.example.net", - "partial label": "evilapi.example.net", - "two labels": "a.b.api.example.net", - "nested family": "svc.internal.api.example.net", - "bare suffix": ".api.example.net", - "empty inner label": "alpha..api.example.net", - "trailing dot": "alpha.api.example.net.", - "path appended": "alpha.api.example.net/v1", - "url": "https://alpha.api.example.net", - "percent encoded": "alpha%2eapi.example.net", - "unicode label": "alpha.api.exampl\u0131.net", - "over-long label": strings.Repeat("a", 64) + ".example.net", - } - for name, value := range cases { - t.Run(name, func(t *testing.T) { - _, err := entry.resolveTargetHost([]string{value}) - require.Error(t, err) - }) - } -} - -func TestResolveTargetHostFailsClosedBothDirections(t *testing.T) { - wildcardEntry, err := newProxyEntry("https://*.api.example.net", false, 1234, nil, nil) - require.NoError(t, err) - concreteEntry, err := newProxyEntry("https://beta.api.example.net", false, 1234, nil, nil) - require.NoError(t, err) - - cases := []struct { - name string - entry *proxyEntry - values []string - want string - wantErr bool - }{ - {"wildcard, inside policy", wildcardEntry, []string{"alpha.api.example.net"}, "alpha.api.example.net", false}, - {"wildcard, outside policy", wildcardEntry, []string{"evil.example.com"}, "", true}, - {"wildcard, absent", wildcardEntry, nil, "", true}, - {"wildcard, duplicated", wildcardEntry, []string{"alpha.api.example.net", "beta.api.example.net"}, "", true}, - {"concrete, absent", concreteEntry, nil, "", false}, - {"concrete, equal", concreteEntry, []string{"beta.api.example.net"}, "", false}, - {"concrete, equal but cased", concreteEntry, []string{"Beta.API.Example.NET"}, "", false}, - {"concrete, disagreeing", concreteEntry, []string{"alpha.api.example.net"}, "", true}, - {"concrete, duplicated", concreteEntry, []string{"beta.api.example.net", "beta.api.example.net"}, "", true}, - } - - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - got, err := tc.entry.resolveTargetHost(tc.values) - if tc.wantErr { - require.Error(t, err) - return - } - require.NoError(t, err) - require.Equal(t, tc.want, got) - }) - } -} - -func TestWildcardRetargetsAcrossHosts(t *testing.T) { - backendA := newRecordingTLSBackend(t, "a") - backendB := newRecordingTLSBackend(t, "b") - rr := newRoutedReflector(t, map[string]*recordingBackend{ - "a.axon.example.com": backendA, - "b.axon.example.com": backendB, - }) - - headers := acceptfile.NewResolverMapFromMap(map[string]string{"Authorization": "Bearer minted"}) - proxyURI := rr.ProxyURI("https://*.axon.example.com", WithHeadersResolver(headers)) - path := proxyPath(t, proxyURI) - - for _, tc := range []struct{ host, want string }{ - {"a.axon.example.com", "a"}, - {"b.axon.example.com", "b"}, - } { - req := httptest.NewRequest("GET", path+"/v1/things", nil) - req.Header.Set(HeaderTargetHost, tc.host) - rec := httptest.NewRecorder() - rr.ServeHTTP(rec, req) - require.Equal(t, http.StatusOK, rec.Code, "host=%s", tc.host) - require.Equal(t, tc.want, rec.Body.String()) - } - - _, hostA, _ := backendA.snapshot() - hitsB, hostB, headerB := backendB.snapshot() - require.Equal(t, "a.axon.example.com", hostA) - require.Equal(t, "b.axon.example.com", hostB) - require.Equal(t, 1, hitsB) - require.Equal(t, "Bearer minted", headerB.Get("Authorization")) - require.Empty(t, headerB.Get(HeaderTargetHost)) -} - -// The header names a host, so the port has to come from the origin. If it did -// not, a family on a non-default port would silently dial 443. -func TestWildcardOriginPortReachesTheDial(t *testing.T) { - backend := newRecordingTLSBackend(t, "a") - var dialed []string - var mu sync.Mutex - transport := &http.Transport{ - DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { - mu.Lock() - dialed = append(dialed, addr) - mu.Unlock() - return net.Dial(network, backend.hostPort(t)) - }, - TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, - } - rr := newReflectorWithDrain(t, RegistrationReflectorParams{ - Logger: newTestLogger(t), - Registry: prometheus.NewRegistry(), - Transport: transport, - Config: config.AgentConfig{ReflectorWebSocketUpgrade: true}, - }) - t.Cleanup(func() { rr.Stop() }) - - proxyURI := rr.ProxyURI("https://*.something.com.internal:8443") - req := httptest.NewRequest("GET", proxyPath(t, proxyURI)+"/v1/things", nil) - req.Header.Set(HeaderTargetHost, "alpha.something.com.internal") - rec := httptest.NewRecorder() - rr.ServeHTTP(rec, req) - - require.Equal(t, http.StatusOK, rec.Code) - mu.Lock() - defer mu.Unlock() - require.Equal(t, []string{"alpha.something.com.internal:8443"}, dialed) -} - -func TestWildcardWithoutTargetHostIsRejected(t *testing.T) { - backend := newRecordingTLSBackend(t, "a") - rr := newRoutedReflector(t, map[string]*recordingBackend{"a.axon.example.com": backend}) - - proxyURI := rr.ProxyURI("https://*.axon.example.com") - rec := httptest.NewRecorder() - rr.ServeHTTP(rec, httptest.NewRequest("GET", proxyPath(t, proxyURI)+"/v1/things", nil)) - - require.Equal(t, http.StatusForbidden, rec.Code) - require.Contains(t, rec.Body.String(), ErrClassDestinationRejected) - hits, _, _ := backend.snapshot() - require.Equal(t, 0, hits) -} - -func TestWildcardOutsidePolicyIsRejected(t *testing.T) { - backend := newRecordingTLSBackend(t, "a") - rr := newRoutedReflector(t, map[string]*recordingBackend{"a.axon.example.com": backend}) - - proxyURI := rr.ProxyURI("https://*.axon.example.com") - req := httptest.NewRequest("GET", proxyPath(t, proxyURI)+"/v1/things", nil) - req.Header.Set(HeaderTargetHost, "evil.example.com") - rec := httptest.NewRecorder() - rr.ServeHTTP(rec, req) - - require.Equal(t, http.StatusForbidden, rec.Code) - require.Contains(t, rec.Body.String(), ErrClassDestinationRejected) - hits, _, _ := backend.snapshot() - require.Equal(t, 0, hits) -} - -func TestWildcardRefusesWebSocketUpgrade(t *testing.T) { - backend := newRecordingTLSBackend(t, "a") - rr := newRoutedReflector(t, map[string]*recordingBackend{"a.axon.example.com": backend}) - - proxyURI := rr.ProxyURI("https://*.axon.example.com") - req := httptest.NewRequest("GET", proxyPath(t, proxyURI)+"/socket", nil) - req.Header.Set("Connection", "Upgrade") - req.Header.Set("Upgrade", "websocket") - rec := httptest.NewRecorder() - rr.ServeHTTP(rec, req) - - require.Equal(t, http.StatusForbidden, rec.Code) - hits, _, _ := backend.snapshot() - require.Equal(t, 0, hits) -} - -// A concrete rule never routes on the header but must still strip it, or the -// value reaches a third-party upstream. -func TestConcreteOriginStripsTargetHostAndRejectsDisagreement(t *testing.T) { - backend := newRecordingTLSBackend(t, "a") - rr := newRoutedReflector(t, map[string]*recordingBackend{"a.axon.example.com": backend}) - - proxyURI := rr.ProxyURI("https://a.axon.example.com") - path := proxyPath(t, proxyURI) - - req := httptest.NewRequest("GET", path+"/v1/things", nil) - req.Header.Set(HeaderTargetHost, "a.axon.example.com") - rec := httptest.NewRecorder() - rr.ServeHTTP(rec, req) - require.Equal(t, http.StatusOK, rec.Code) - hits, _, header := backend.snapshot() - require.Equal(t, 1, hits) - require.Empty(t, header.Get(HeaderTargetHost)) - - req = httptest.NewRequest("GET", path+"/v1/things", nil) - req.Header.Set(HeaderTargetHost, "alpha.api.example.net") - rec = httptest.NewRecorder() - rr.ServeHTTP(rec, req) - require.Equal(t, http.StatusForbidden, rec.Code) - require.Contains(t, rec.Body.String(), ErrClassDestinationRejected) - - hits, _, _ = backend.snapshot() - require.Equal(t, 1, hits, "the rejected request must not reach the upstream") -} - -func TestConcreteOriginWithoutTargetHostIsUntouched(t *testing.T) { - env := newTestReflectorEnv(t) - backend := newRecordingBackend(t, "a") - - proxyURI := env.Reflector.ProxyURI(backend.server.URL) - rec := httptest.NewRecorder() - env.Reflector.ServeHTTP(rec, httptest.NewRequest("GET", proxyPath(t, proxyURI)+"/v1/things", nil)) - - require.Equal(t, http.StatusOK, rec.Code) - require.Equal(t, "a", rec.Body.String()) - hits, _, header := backend.snapshot() - require.Equal(t, 1, hits) - require.Empty(t, header.Get(HeaderTargetHost)) -} - -func TestDuplicateTargetHostIsRejected(t *testing.T) { - backend := newRecordingTLSBackend(t, "a") - rr := newRoutedReflector(t, map[string]*recordingBackend{"a.axon.example.com": backend}) - - proxyURI := rr.ProxyURI("https://a.axon.example.com") - req := httptest.NewRequest("GET", proxyPath(t, proxyURI)+"/v1/things", nil) - req.Header.Add(HeaderTargetHost, "a.axon.example.com") - req.Header.Add(HeaderTargetHost, "a.axon.example.com") - rec := httptest.NewRecorder() - rr.ServeHTTP(rec, req) - - require.Equal(t, http.StatusForbidden, rec.Code) - hits, _, _ := backend.snapshot() - require.Equal(t, 0, hits) -} - -func TestWildcardConcurrentRetargets(t *testing.T) { - backendA := newRecordingTLSBackend(t, "a") - backendB := newRecordingTLSBackend(t, "b") - rr := newRoutedReflector(t, map[string]*recordingBackend{ - "a.axon.example.com": backendA, - "b.axon.example.com": backendB, - }) - - proxyURI := rr.ProxyURI("https://*.axon.example.com") - path := proxyPath(t, proxyURI) - - const workers = 16 - const perWorker = 25 - var wg sync.WaitGroup - errs := make(chan error, workers*perWorker) - for w := 0; w < workers; w++ { - wg.Add(1) - go func(w int) { - defer wg.Done() - for i := 0; i < perWorker; i++ { - host, want := "a.axon.example.com", "a" - if (w+i)%2 == 1 { - host, want = "b.axon.example.com", "b" - } - req := httptest.NewRequest("GET", path+"/v1/things", nil) - req.Header.Set(HeaderTargetHost, host) - rec := httptest.NewRecorder() - rr.ServeHTTP(rec, req) - if rec.Code != http.StatusOK || rec.Body.String() != want { - errs <- fmt.Errorf("worker %d req %d: got code=%d body=%q want %q", w, i, rec.Code, rec.Body.String(), want) - return - } - } - }(w) - } - wg.Wait() - close(errs) - for err := range errs { - require.NoError(t, err) - } - - hitsA, _, _ := backendA.snapshot() - hitsB, _, _ := backendB.snapshot() - require.Equal(t, workers*perWorker/2, hitsA) - require.Equal(t, workers*perWorker/2, hitsB) -} diff --git a/agent/server/snykbroker/reflector_failure_class_test.go b/agent/server/snykbroker/reflector_failure_class_test.go deleted file mode 100644 index b5749bbc..00000000 --- a/agent/server/snykbroker/reflector_failure_class_test.go +++ /dev/null @@ -1,88 +0,0 @@ -package snykbroker - -import ( - "fmt" - "net/http" - "net/http/httptest" - "testing" - - "github.com/cortexapps/axon/server/snykbroker/acceptfile" - "github.com/stretchr/testify/require" -) - -// The class travels in a header as well as the body. A body can come from an -// upstream, so a caller that has to tell an agent failure from a Google one -// cannot rely on the body alone. - -func TestDestinationRejectionNamesItselfInAHeader(t *testing.T) { - backend := newRecordingTLSBackend(t, "a") - rr := newRoutedReflector(t, map[string]*recordingBackend{"a.axon.example.com": backend}) - - proxyURI := rr.ProxyURI("https://*.axon.example.com") - req := httptest.NewRequest("GET", proxyPath(t, proxyURI)+"/v1/things", nil) - req.Header.Set(HeaderTargetHost, "evil.example.com") - rec := httptest.NewRecorder() - rr.ServeHTTP(rec, req) - - require.Equal(t, http.StatusForbidden, rec.Code) - require.Equal(t, ErrClassDestinationRejected, rec.Header().Get(HeaderFailureClass)) - hits, _, _ := backend.snapshot() - require.Equal(t, 0, hits) -} - -func TestCredentialProviderFailureNamesTheAgent(t *testing.T) { - dialed := 0 - backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - dialed++ - })) - defer backend.Close() - - headers := acceptfile.ResolverMap{ - "authorization": { - Key: "${plugin:broken}", - Resolve: func() (string, error) { - return "", fmt.Errorf("provider exited 1") - }, - }, - } - entry, err := newProxyEntry(backend.URL, false, 8080, headers, nil) - require.NoError(t, err) - - rec := httptest.NewRecorder() - entry.serve(rec, httptest.NewRequest("GET", "/test", nil)) - - require.Equal(t, http.StatusBadGateway, rec.Code) - require.Equal(t, ErrClassCredentialFailure, rec.Header().Get(HeaderFailureClass)) - // A provider failure that reached the upstream would come back as its 401, - // which is a different class and a different thing to go and fix. - require.Equal(t, 0, dialed) -} - -func TestUnreachableUpstreamNamesTheAgentsNetwork(t *testing.T) { - // Port 1 is reserved and nothing listens on it, so the dial fails locally. - entry, err := newProxyEntry("http://127.0.0.1:1", false, 8080, nil, nil) - require.NoError(t, err) - - rec := httptest.NewRecorder() - entry.serve(rec, httptest.NewRequest("GET", "/test", nil)) - - require.Equal(t, http.StatusBadGateway, rec.Code) - require.Equal(t, ErrClassNetworkFailure, rec.Header().Get(HeaderFailureClass)) -} - -func TestUpstreamCannotNameAFailureClass(t *testing.T) { - backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set(HeaderFailureClass, ErrClassDestinationRejected) - w.WriteHeader(http.StatusOK) - })) - defer backend.Close() - - entry, err := newProxyEntry(backend.URL, false, 8080, nil, nil) - require.NoError(t, err) - - rec := httptest.NewRecorder() - entry.serve(rec, httptest.NewRequest("GET", "/test", nil)) - - require.Equal(t, http.StatusOK, rec.Code) - require.Empty(t, rec.Header().Get(HeaderFailureClass)) -} diff --git a/agent/server/snykbroker/reflector_google_live_test.go b/agent/server/snykbroker/reflector_google_live_test.go deleted file mode 100644 index 0394bedd..00000000 --- a/agent/server/snykbroker/reflector_google_live_test.go +++ /dev/null @@ -1,254 +0,0 @@ -package snykbroker - -import ( - "encoding/json" - "net/http" - "net/http/httptest" - "os" - "path/filepath" - "strings" - "testing" - - "github.com/cortexapps/axon/config" - "github.com/cortexapps/axon/server/snykbroker/acceptfile" - "github.com/prometheus/client_golang/prometheus" - "github.com/stretchr/testify/require" - "go.uber.org/zap" -) - -// Live end-to-end tests for the Google credential source. They use whatever -// Application Default Credentials the machine has and make real requests to -// Google, so they are opt-in: -// -// make plugins -// AXON_GOOGLE_LIVE_TEST=1 go test ./server/snykbroker/ -run Live -v -// -// Nothing is faked and nothing needs brain-backend, a relay token, the -// snyk-broker, or a tunnel: the reflector is an http.Handler and is driven -// directly. -// -// Guarded by an environment variable rather than a build tag, so they still -// compile in the normal build. A live test that has quietly stopped compiling is -// a live test nobody runs. -const liveTestEnv = "AXON_GOOGLE_LIVE_TEST" - -// One label under googleapis.com, so the shipped wildcard origin covers it. Its -// list-projects call needs only an authenticated identity, and is not asserted to -// succeed: a 403 still proves Google accepted the credential, a 401 does not. -const ( - liveGoogleHost = "cloudresourcemanager.googleapis.com" - liveGooglePath = "/v1/projects" -) - -func requireLiveGoogle(t *testing.T) { - t.Helper() - if os.Getenv(liveTestEnv) != "1" { - t.Skipf("set %s=1 to run this against real Google credentials", liveTestEnv) - } -} - -// shippedPluginDir returns the directory `make plugins` installs google-adc into, -// for the accept file's PluginDirs. In the image the same binary sits in -// /agent/plugins alongside the shipped shell plugins. -func shippedPluginDir(t *testing.T) string { - t.Helper() - - // The test's working directory is the package directory. - dir, err := filepath.Abs(filepath.Join("..", "..", "plugins")) - require.NoError(t, err) - - if _, err := os.Stat(filepath.Join(dir, "google-adc")); err != nil { - t.Skipf("run `make plugins` first: %v", err) - } - return dir -} - -// Duplicates the plugin's own constant: it is a separate module, so this is a -// process contract rather than something importable. -const credentialCacheDirEnv = "AXON_CREDENTIAL_CACHE_DIR" - -// useIsolatedCredentialCache keeps the test off any cache a running agent owns, -// and makes the cached token observable so reuse can be asserted. -func useIsolatedCredentialCache(t *testing.T) string { - t.Helper() - dir := t.TempDir() - t.Setenv(credentialCacheDirEnv, dir) - return dir -} - -// cachedTokens returns the credential values currently on disk. -func cachedTokens(t *testing.T, cacheDir string) []string { - t.Helper() - - matches, err := filepath.Glob(filepath.Join(cacheDir, "*.json")) - require.NoError(t, err) - - values := make([]string, 0, len(matches)) - for _, match := range matches { - data, err := os.ReadFile(match) - require.NoError(t, err) - - var entry struct { - Value string `json:"value"` - } - require.NoError(t, json.Unmarshal(data, &entry)) - values = append(values, entry.Value) - } - return values -} - -// liveGoogleEnv renders the shipped accept file into a real reflector, which is -// where the plugin is located and wired into the proxy entry's headers. -func liveGoogleEnv(t *testing.T) (*renderEnv, func() string, string) { - t.Helper() - - cacheDir := useIsolatedCredentialCache(t) - - logger, logged := newCapturingLogger(t) - cfg := config.AgentConfig{ - HttpRelayReflectorMode: config.RelayReflectorAllTraffic, - ReflectorWebSocketUpgrade: true, - PluginDirs: []string{shippedPluginDir(t)}, - } - rr := newReflectorWithDrain(t, RegistrationReflectorParams{ - Logger: logger, - Registry: prometheus.NewRegistry(), - Config: cfg, - }) - t.Cleanup(func() { rr.Stop() }) - env := &renderEnv{ - mgr: &relayInstanceManager{config: cfg, logger: logger, reflector: rr}, - reflector: rr, - } - - content, err := os.ReadFile(filepath.Join("accept_files", "accept.google.json")) - require.NoError(t, err) - - af, err := acceptfile.NewAcceptFile(content, cfg, logger) - require.NoError(t, err) - - _, err = af.Render(zap.NewNop(), env.mgr.reflectorRenderStep) - require.NoError(t, err) - - return env, logged, cacheDir -} - -// requestGoogle drives one request through the reflector to the live host. -func requestGoogle(t *testing.T, env *renderEnv) *httptest.ResponseRecorder { - t.Helper() - - uri, err := env.reflector.getUriForTarget("https://*.googleapis.com") - require.NoError(t, err, "the shipped accept file did not register its wildcard origin") - - req := httptest.NewRequest("GET", proxyPath(t, uri)+liveGooglePath, nil) - req.Header.Set(HeaderTargetHost, liveGoogleHost) - - rec := httptest.NewRecorder() - env.reflector.ServeHTTP(rec, req) - return rec -} - -// The whole path, with a real identity and a real Google API at the end of it. -func TestLiveGoogleAcceptsTheInjectedCredential(t *testing.T) { - requireLiveGoogle(t) - env, _, cacheDir := liveGoogleEnv(t) - - rec := requestGoogle(t, env) - - // Surfaced only on failure: a successful list-projects response carries real - // project and organisation identifiers. - diagnostic := truncate(rec.Body.String(), 400) - t.Logf("%s answered %d", liveGoogleHost, rec.Code) - - // 401 covers two cases the agent cannot yet tell apart: Google refused the - // token, or the plugin failed and the resolver forwarded the unexpanded - // placeholder. Separating them needs the resolver to fail the request instead - // of logging and continuing, which is not this change. - require.NotEqual(t, http.StatusUnauthorized, rec.Code, - "Google refused the authorization header the agent injected: %s", diagnostic) - require.NotEqual(t, http.StatusForbidden, rec.Code, - "Google accepted the identity but refused the call; check the IAM binding or whether "+ - "cloudresourcemanager is enabled: %s", diagnostic) - - tokens := cachedTokens(t, cacheDir) - require.Len(t, tokens, 1, "expected exactly one cached credential") - require.NotEmpty(t, tokens[0]) -} - -// Asserted on the cached value rather than on timing, since Google will not say -// how many tokens it issued. -func TestLiveGoogleReusesTheCachedToken(t *testing.T) { - requireLiveGoogle(t) - env, _, cacheDir := liveGoogleEnv(t) - - first := requestGoogle(t, env) - require.NotEqual(t, http.StatusUnauthorized, first.Code) - - afterFirst := cachedTokens(t, cacheDir) - require.Len(t, afterFirst, 1) - - info, err := os.Stat(filepath.Join(cacheDir, cacheFileName(t, cacheDir))) - require.NoError(t, err) - writtenAt := info.ModTime() - - for i := 0; i < 3; i++ { - rec := requestGoogle(t, env) - require.NotEqual(t, http.StatusUnauthorized, rec.Code, "request %d produced no credential", i+2) - } - - afterMore := cachedTokens(t, cacheDir) - require.Equal(t, afterFirst, afterMore, "the token changed, so a later request minted again") - - info, err = os.Stat(filepath.Join(cacheDir, cacheFileName(t, cacheDir))) - require.NoError(t, err) - require.Equal(t, writtenAt, info.ModTime(), "the cache was rewritten, so a later request minted again") -} - -// The value the agent injected is nowhere in the logs, at debug level, across a -// request that succeeded and a destination that was rejected. -func TestLiveGoogleCredentialIsNeverLogged(t *testing.T) { - requireLiveGoogle(t) - env, logged, cacheDir := liveGoogleEnv(t) - - require.NotEqual(t, http.StatusUnauthorized, requestGoogle(t, env).Code) - - tokens := cachedTokens(t, cacheDir) - require.Len(t, tokens, 1) - - // Both the whole header value and the bare token: a log that printed only the - // second half would still have leaked the credential. - credential := tokens[0] - bare := credential - if _, after, found := strings.Cut(credential, " "); found { - bare = after - } - require.NotEmpty(t, bare) - - // A rejected destination is the path that logs the most. - uri, err := env.reflector.getUriForTarget("https://*.googleapis.com") - require.NoError(t, err) - rejected := httptest.NewRequest("GET", proxyPath(t, uri)+liveGooglePath, nil) - rejected.Header.Set(HeaderTargetHost, "not-google.example.com") - env.reflector.ServeHTTP(httptest.NewRecorder(), rejected) - - contents := logged() - require.NotContains(t, contents, credential, "the injected header value reached the log") - require.NotContains(t, contents, bare, "the access token reached the log") -} - -// cacheFileName returns the single cache file's name, failing if there is not -// exactly one. -func cacheFileName(t *testing.T, cacheDir string) string { - t.Helper() - matches, err := filepath.Glob(filepath.Join(cacheDir, "*.json")) - require.NoError(t, err) - require.Len(t, matches, 1) - return filepath.Base(matches[0]) -} - -func truncate(s string, max int) string { - if len(s) <= max { - return s - } - return s[:max] + "..." -} diff --git a/agent/server/snykbroker/reflector_headers_harness_test.go b/agent/server/snykbroker/reflector_headers_harness_test.go deleted file mode 100644 index e5c0c375..00000000 --- a/agent/server/snykbroker/reflector_headers_harness_test.go +++ /dev/null @@ -1,96 +0,0 @@ -package snykbroker - -import ( - "fmt" - "net/http" - "net/http/httptest" - "os" - "testing" - - "github.com/cortexapps/axon/config" - "github.com/cortexapps/axon/server/snykbroker/acceptfile" - "github.com/stretchr/testify/require" - "go.uber.org/zap" -) - -// Tests the shipped Harness accept file end-to-end through the reflector: -// the x-api-key header is injected from HARNESS_TOKEN on proxied requests, -// and an inbound placeholder x-api-key is replaced (not duplicated). -func TestHarnessAcceptFileInjectsApiKeyHeader(t *testing.T) { - - content, err := os.ReadFile("accept_files/accept.harness.json") - require.NoError(t, err) - - var receivedApiKeys []string - backendServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - receivedApiKeys = r.Header.Values("x-api-key") - w.WriteHeader(http.StatusOK) - w.Write([]byte(`{"status": "ok"}`)) - })) - defer backendServer.Close() - - os.Setenv("HARNESS_API", backendServer.URL) - os.Setenv("HARNESS_TOKEN", "real-harness-api-key") - defer func() { - os.Unsetenv("HARNESS_API") - os.Unsetenv("HARNESS_TOKEN") - }() - - logger := zap.NewNop() - cfg := config.AgentConfig{ - HttpRelayReflectorMode: config.RelayReflectorAllTraffic, - } - reflector := NewRegistrationReflector(RegistrationReflectorParams{ - Logger: logger, - Config: cfg, - }) - - _, err = reflector.Start() - require.NoError(t, err) - defer reflector.Stop() - - af, err := acceptfile.NewAcceptFile(content, cfg, nil) - require.NoError(t, err) - - var proxyURI string - _, err = af.Render( - logger, - func(renderContext acceptfile.RenderContext) error { - for _, entry := range renderContext.AcceptFile.PrivateRules() { - originalURI := entry.Origin() - if originalURI == cfg.HttpBaseUrl() { - continue - } - newURI := reflector.ProxyURI(originalURI, WithHeadersResolver(entry.Headers())) - entry.SetOrigin(newURI) - proxyURI = newURI - } - return nil - }, - ) - require.NoError(t, err) - require.NotEmpty(t, proxyURI) - - t.Run("injects x-api-key when absent", func(t *testing.T) { - resp, err := http.Get(fmt.Sprintf("%s/ng/api/projects", proxyURI)) - require.NoError(t, err) - defer resp.Body.Close() - - require.Equal(t, http.StatusOK, resp.StatusCode) - require.Equal(t, []string{"real-harness-api-key"}, receivedApiKeys) - }) - - t.Run("replaces inbound placeholder x-api-key", func(t *testing.T) { - req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/ng/api/projects", proxyURI), nil) - require.NoError(t, err) - req.Header.Set("x-api-key", "placeholder-from-cortex") - - resp, err := http.DefaultClient.Do(req) - require.NoError(t, err) - defer resp.Body.Close() - - require.Equal(t, http.StatusOK, resp.StatusCode) - // exactly one value: the placeholder is replaced, not appended to - require.Equal(t, []string{"real-harness-api-key"}, receivedApiKeys) - }) -} diff --git a/agent/server/snykbroker/reflector_headers_simple_test.go b/agent/server/snykbroker/reflector_headers_simple_test.go deleted file mode 100644 index 4754ac63..00000000 --- a/agent/server/snykbroker/reflector_headers_simple_test.go +++ /dev/null @@ -1,232 +0,0 @@ -package snykbroker - -import ( - "net/http" - "net/http/httptest" - "os" - "testing" - - "github.com/cortexapps/axon/server/snykbroker/acceptfile" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "go.uber.org/zap" -) - -// TestHeaderApplicationInProxy tests that headers are properly applied to HTTP requests -// going through the reverse proxy created by getProxyWithHeaders -func TestHeaderApplicationInProxy(t *testing.T) { - // Set up environment variables - os.Setenv("TEST_API_KEY", "secret-key-123") - os.Setenv("TEST_TOKEN", "bearer-token-456") - defer func() { - os.Unsetenv("TEST_API_KEY") - os.Unsetenv("TEST_TOKEN") - }() - - // Create a backend server that captures headers - var receivedHeaders http.Header - backendServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - receivedHeaders = r.Header.Clone() - w.WriteHeader(http.StatusOK) - w.Write([]byte(`{"message": "success"}`)) - })) - defer backendServer.Close() - - // Test headers with environment variables resolved - headers := map[string]string{ - "x-api-key": "secret-key-123", // Pre-resolved environment variable - "authorization": "Bearer bearer-token-456", // Pre-resolved environment variable - "x-static": "static-value", // Static value - } - - // Create proxy with headers - proxyEntry, err := newProxyEntry(backendServer.URL, false, 8080, acceptfile.NewResolverMapFromMap(headers), nil) - proxyEntry.addResponseHeader("x-response", "response-value") - require.NoError(t, err) - require.NotNil(t, proxyEntry) - - // Create a test request - req := httptest.NewRequest("GET", "/test", nil) - req.Header.Set("user-agent", "test-client") - - // Create response recorder - rr := httptest.NewRecorder() - - // Send request through the proxy - proxyEntry.serve(rr, req) - - // Verify the request was successful - require.Equal(t, http.StatusOK, rr.Code) - - // Verify that headers were applied to the backend request - require.Equal(t, "secret-key-123", receivedHeaders.Get("x-api-key")) - require.Equal(t, "Bearer bearer-token-456", receivedHeaders.Get("authorization")) - require.Equal(t, "static-value", receivedHeaders.Get("x-static")) - require.Equal(t, "", receivedHeaders.Get("x-response")) - - // Verify original headers are preserved - require.Equal(t, "test-client", receivedHeaders.Get("user-agent")) - - require.Equal(t, "response-value", rr.Header().Get("x-response")) - - // Verify the response body - assert.JSONEq(t, `{"message": "success"}`, rr.Body.String()) -} - -// TestMultipleProxiesWithDifferentHeaders tests that different proxy instances -// can have different headers applied -func TestMultipleProxiesWithDifferentHeaders(t *testing.T) { - // Create two backend servers that capture headers - var server1Headers, server2Headers http.Header - - server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - server1Headers = r.Header.Clone() - w.WriteHeader(http.StatusOK) - w.Write([]byte(`{"server": "1"}`)) - })) - defer server1.Close() - - server2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - server2Headers = r.Header.Clone() - w.WriteHeader(http.StatusOK) - w.Write([]byte(`{"server": "2"}`)) - })) - defer server2.Close() - - // Create first proxy with its headers - headers1 := map[string]string{ - "x-api-key": "key-for-server-1", - "x-service": "service-1", - } - proxy1, err := newProxyEntry(server1.URL, false, 8080, acceptfile.NewResolverMapFromMap(headers1), nil) - require.NoError(t, err) - - // Create second proxy with different headers - headers2 := map[string]string{ - "x-api-key": "key-for-server-2", - "x-service": "service-2", - } - proxy2, err := newProxyEntry(server2.URL, false, 8080, acceptfile.NewResolverMapFromMap(headers2), nil) - require.NoError(t, err) - - // Send requests through both proxies - req1 := httptest.NewRequest("GET", "/test", nil) - rr1 := httptest.NewRecorder() - proxy1.serve(rr1, req1) - - req2 := httptest.NewRequest("GET", "/test", nil) - rr2 := httptest.NewRecorder() - proxy2.serve(rr2, req2) - - // Verify both requests were successful - require.Equal(t, http.StatusOK, rr1.Code) - require.Equal(t, http.StatusOK, rr2.Code) - - // Verify correct headers were sent to each server - require.Equal(t, "key-for-server-1", server1Headers.Get("x-api-key")) - require.Equal(t, "service-1", server1Headers.Get("x-service")) - - require.Equal(t, "key-for-server-2", server2Headers.Get("x-api-key")) - require.Equal(t, "service-2", server2Headers.Get("x-service")) -} - -// TestProxyWithNoHeaders tests that proxies work correctly without headers -func TestProxyWithNoHeaders(t *testing.T) { - // Create a backend server - var receivedHeaders http.Header - backendServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - receivedHeaders = r.Header.Clone() - w.WriteHeader(http.StatusOK) - w.Write([]byte(`{"message": "no headers"}`)) - })) - defer backendServer.Close() - - // Create reflector - logger := zap.NewNop() - reflector := NewRegistrationReflector(RegistrationReflectorParams{ - Logger: logger, - }) - reflector.Start() - defer reflector.Stop() - - // Create proxy without headers - proxyEntry, err := reflector.getProxy(backendServer.URL, false, nil) - require.NoError(t, err) - require.NotNil(t, proxyEntry) - - // Create a test request with some headers - req := httptest.NewRequest("GET", "/test", nil) - req.Header.Set("user-agent", "test-client") - req.Header.Set("content-type", "application/json") - - // Create response recorder - rr := httptest.NewRecorder() - - // Send request through the proxy - proxyEntry.serve(rr, req) - - // Verify the request was successful - require.Equal(t, http.StatusOK, rr.Code) - - // Verify original headers are preserved (no custom headers added) - require.Equal(t, "test-client", receivedHeaders.Get("user-agent")) - require.Equal(t, "application/json", receivedHeaders.Get("content-type")) - - // Verify no custom headers were added - assert.Empty(t, receivedHeaders.Get("x-api-key")) - assert.Empty(t, receivedHeaders.Get("authorization")) - - // Verify the response body - assert.JSONEq(t, `{"message": "no headers"}`, rr.Body.String()) -} - -// TestHeaderOverwriting tests that custom headers can overwrite existing headers -func TestHeaderOverwriting(t *testing.T) { - // Create a backend server - var receivedHeaders http.Header - backendServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - receivedHeaders = r.Header.Clone() - w.WriteHeader(http.StatusOK) - w.Write([]byte(`{"message": "overwritten"}`)) - })) - defer backendServer.Close() - - // Create reflector - logger := zap.NewNop() - reflector := NewRegistrationReflector(RegistrationReflectorParams{ - Logger: logger, - }) - reflector.Start() - defer reflector.Stop() - - // Headers that will overwrite the request headers - headers := map[string]string{ - "user-agent": "proxy-agent", // This should overwrite the original user-agent - "authorization": "Bearer custom-token", - } - - // Create proxy with headers - proxyEntry, err := reflector.getProxy(backendServer.URL, false, acceptfile.NewResolverMapFromMap(headers)) - require.NoError(t, err) - - // Create request with original headers - req := httptest.NewRequest("GET", "/test", nil) - req.Header.Set("user-agent", "original-agent") - req.Header.Set("content-type", "application/json") - - // Create response recorder - rr := httptest.NewRecorder() - - // Send request through the proxy - proxyEntry.serve(rr, req) - - // Verify the request was successful - require.Equal(t, http.StatusOK, rr.Code) - - // Verify that custom headers overwrote original headers - require.Equal(t, "proxy-agent", receivedHeaders.Get("user-agent")) // Should be overwritten - require.Equal(t, "Bearer custom-token", receivedHeaders.Get("authorization")) - - // Verify that non-conflicting headers are preserved - require.Equal(t, "application/json", receivedHeaders.Get("content-type")) -} diff --git a/agent/server/snykbroker/reflector_headers_test.go b/agent/server/snykbroker/reflector_headers_test.go deleted file mode 100644 index e18b47ef..00000000 --- a/agent/server/snykbroker/reflector_headers_test.go +++ /dev/null @@ -1,397 +0,0 @@ -package snykbroker - -import ( - "encoding/json" - "fmt" - "io" - "net/http" - "net/http/httptest" - "os" - "testing" - "time" - - "github.com/cortexapps/axon/config" - "github.com/cortexapps/axon/server/snykbroker/acceptfile" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "go.uber.org/zap" -) - -// Integration tests for accept.json header functionality with live HTTP calls - -func TestAcceptFileHeadersAppliedToLiveRequests(t *testing.T) { - - acceptfile.IgnoreHosts = []string{} - - // Set up environment variables for testing - os.Setenv("TEST_API_KEY", "secret-api-key-123") - os.Setenv("TEST_AUTH_TOKEN", "bearer-token-456") - defer func() { - os.Unsetenv("TEST_API_KEY") - os.Unsetenv("TEST_AUTH_TOKEN") - }() - - tests := []struct { - name string - acceptContent map[string]any - expectedHeaders map[string]string - testPath string - index int - }{ - { - name: "single header with env var", - acceptContent: map[string]any{ - "private": []any{ - map[string]any{ - "method": "GET", - "path": "/api/*", - "origin": "http://example.com", - "headers": map[string]any{ - "x-api-key": "${TEST_API_KEY}", - }, - }, - }, - }, - expectedHeaders: map[string]string{ - "x-api-key": "secret-api-key-123", - }, - testPath: "/api/test", - }, - { - name: "multiple headers with env vars", - acceptContent: map[string]any{ - "private": []any{ - map[string]any{ - "method": "POST", - "path": "/graphql", - "origin": "http://graphql.example.com", - "headers": map[string]any{ - "authorization": "Bearer ${TEST_AUTH_TOKEN}", - "x-api-key": "${TEST_API_KEY}", - "x-static": "static-value", - }, - }, - }, - }, - expectedHeaders: map[string]string{ - "authorization": "Bearer bearer-token-456", - "x-api-key": "secret-api-key-123", - "x-static": "static-value", - }, - testPath: "/graphql", - }, - { - name: "headers with wildcard path", - acceptContent: map[string]any{ - "private": []any{ - map[string]any{ - "method": "any", - "path": "/*", - "origin": "http://api.example.com", - "headers": map[string]any{ - "x-service-key": "${TEST_API_KEY}", - }, - }, - }, - }, - expectedHeaders: map[string]string{ - "x-service-key": "secret-api-key-123", - }, - testPath: "/any/nested/path", - }, - { - name: "multiple routes different headers", - acceptContent: map[string]any{ - "private": []any{ - map[string]any{ - "method": "GET", - "path": "/api/*", - "origin": "http://example.com", - "headers": map[string]any{ - "x-api-key": "route1", - }, - }, - map[string]any{ - "method": "GET", - "path": "/api-v2/*", - "origin": "http://example.com", - "headers": map[string]any{ - "x-api-key": "route2", - }, - }, - }, - }, - expectedHeaders: map[string]string{ - "x-api-key": "route2", - }, - index: 1, - testPath: "/api-v2/test", - }, - { - name: "header with env var and plugin", - acceptContent: map[string]any{ - "private": []any{ - map[string]any{ - "method": "GET", - "path": "/api/*", - "origin": "http://example.com", - "headers": map[string]any{ - "x-api-key": "${TEST_API_KEY}", - "x-plugin-header": "${plugin:plugin.sh}", - }, - }, - }, - }, - expectedHeaders: map[string]string{ - "x-api-key": "secret-api-key-123", - "x-plugin-header": "HOME=" + os.Getenv("HOME"), - }, - testPath: "/api/test", - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - // Create a mock backend server that captures headers - var receivedHeaders http.Header - backendServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - receivedHeaders = r.Header.Clone() - w.WriteHeader(http.StatusOK) - w.Write([]byte(`{"status": "ok"}`)) - })) - defer backendServer.Close() - - // Update the accept content to use the real backend server URL - updateOriginInAcceptContent(tt.acceptContent, backendServer.URL) - - // Create reflector - logger := zap.NewNop() - cfg := config.AgentConfig{ - HttpRelayReflectorMode: config.RelayReflectorAllTraffic, - PluginDirs: []string{".", "./acceptfile"}, - } - reflector := NewRegistrationReflector(RegistrationReflectorParams{ - Logger: logger, - Config: cfg, - }) - - // Start the reflector server - _, err := reflector.Start() - require.NoError(t, err) - defer reflector.Stop() - - // Process the accept file with header extraction - capturedOrigins := make([]string, 0) - capturedHeaders := make([]map[string]string, 0) - - jsonContent, err := json.MarshalIndent(tt.acceptContent, "", " ") - require.NoError(t, err) - - af, err := acceptfile.NewAcceptFile(jsonContent, cfg, nil) - require.NoError(t, err) - proxyUris := []string{} - - _, err = af.Render( - logger, - func(renderContext acceptfile.RenderContext) error { - for _, entry := range renderContext.AcceptFile.PrivateRules() { - originalURI := entry.Origin() - if originalURI == cfg.HttpBaseUrl() { - continue - } - capturedOrigins = append(capturedOrigins, originalURI) - headers := entry.Headers() - resolvedHeaders, err := headers.ToStringMap() - require.NoError(t, err) - capturedHeaders = append(capturedHeaders, resolvedHeaders) - newURI := reflector.ProxyURI(originalURI, WithHeadersResolver(headers)) - entry.SetOrigin(newURI) - proxyUris = append(proxyUris, newURI) - } - return nil - }, - ) - require.NoError(t, err) - - // Verify headers were captured correctly - require.Equal(t, backendServer.URL, capturedOrigins[tt.index]) - require.Equal(t, tt.expectedHeaders, capturedHeaders[tt.index]) - - // Make a live HTTP request through the proxy - proxyURL := fmt.Sprintf("%s%s", proxyUris[tt.index], tt.testPath) - resp, err := http.Get(proxyURL) - require.NoError(t, err) - defer resp.Body.Close() - - // Verify the request was successful - require.Equal(t, http.StatusOK, resp.StatusCode) - - // Verify that all expected headers were received by the backend - for expectedKey, expectedValue := range tt.expectedHeaders { - actualValue := receivedHeaders.Get(expectedKey) - require.Equal(t, expectedValue, actualValue, - "Header %s: expected %s, got %s", expectedKey, expectedValue, actualValue) - } - - // Read response to ensure proxy worked correctly - body, err := io.ReadAll(resp.Body) - require.NoError(t, err) - assert.JSONEq(t, `{"status": "ok"}`, string(body)) - }) - } -} - -func TestMultipleRoutesWithDifferentHeaders(t *testing.T) { - os.Setenv("API_KEY_1", "key-one") - os.Setenv("API_KEY_2", "key-two") - defer func() { - os.Unsetenv("API_KEY_1") - os.Unsetenv("API_KEY_2") - }() - - // Create two mock backend servers - var server1Headers, server2Headers http.Header - - server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - server1Headers = r.Header.Clone() - w.WriteHeader(http.StatusOK) - w.Write([]byte(`{"server": "1"}`)) - })) - defer server1.Close() - - server2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - server2Headers = r.Header.Clone() - w.WriteHeader(http.StatusOK) - w.Write([]byte(`{"server": "2"}`)) - })) - defer server2.Close() - - acceptContent := map[string]any{ - "private": []any{ - map[string]any{ - "method": "GET", - "path": "/api1/*", - "origin": server1.URL, - "headers": map[string]any{ - "x-api-key": "${API_KEY_1}", - "x-service": "service-1", - }, - }, - map[string]any{ - "method": "GET", - "path": "/api2/*", - "origin": server2.URL, - "headers": map[string]any{ - "x-api-key": "${API_KEY_2}", - "x-service": "service-2", - }, - }, - }, - } - - acceptFile := createTempAcceptFile(t, acceptContent) - defer os.Remove(acceptFile) - - logger := zap.NewNop() - cfg := config.AgentConfig{ - HttpRelayReflectorMode: config.RelayReflectorAllTraffic, - } - reflector := NewRegistrationReflector(RegistrationReflectorParams{ - Logger: logger, - Config: cfg, - }) - - _, err := reflector.Start() - require.NoError(t, err) - defer reflector.Stop() - - // Process the accept file - headerExtractionCount := 0 - - capturedOrigins := make([]string, 0) - capturedHeaders := make([]map[string]string, 0) - - jsonContent, err := json.MarshalIndent(acceptContent, "", " ") - require.NoError(t, err) - - af, err := acceptfile.NewAcceptFile(jsonContent, cfg, nil) - require.NoError(t, err) - proxyUris := []string{} - - _, err = af.Render( - logger, - func(renderContext acceptfile.RenderContext) error { - for _, entry := range renderContext.AcceptFile.PrivateRules() { - originalURI := entry.Origin() - if originalURI == cfg.HttpBaseUrl() { - continue - } - headerExtractionCount++ - capturedOrigins = append(capturedOrigins, originalURI) - headers, err := entry.Headers().ToStringMap() - require.NoError(t, err) - capturedHeaders = append(capturedHeaders, headers) - newURI := reflector.ProxyURI(originalURI, WithHeaders(headers)) - entry.SetOrigin(newURI) - proxyUris = append(proxyUris, newURI) - } - return nil - }, - ) - - require.NoError(t, err) - - // Verify that headers were extracted for both routes - require.Equal(t, 2, headerExtractionCount) - - // Make requests to both routes - resp1, err := http.Get(fmt.Sprintf("%s/api1/test", proxyUris[0])) - require.NoError(t, err) - defer resp1.Body.Close() - - resp2, err := http.Get(fmt.Sprintf("%s/api2/test", proxyUris[1])) - require.NoError(t, err) - defer resp2.Body.Close() - - // Verify both requests were successful - require.Equal(t, http.StatusOK, resp1.StatusCode) - require.Equal(t, http.StatusOK, resp2.StatusCode) - - // Give servers time to process requests - time.Sleep(100 * time.Millisecond) - - // Verify correct headers were sent to each server - require.Equal(t, "key-one", server1Headers.Get("x-api-key")) - require.Equal(t, "service-1", server1Headers.Get("x-service")) - - require.Equal(t, "key-two", server2Headers.Get("x-api-key")) - require.Equal(t, "service-2", server2Headers.Get("x-service")) -} - -// Helper functions - -func createTempAcceptFile(t *testing.T, content map[string]any) string { - jsonContent, err := json.MarshalIndent(content, "", " ") - require.NoError(t, err) - - tmpFile, err := os.CreateTemp("", "accept-*.json") - require.NoError(t, err) - - _, err = tmpFile.Write(jsonContent) - require.NoError(t, err) - - err = tmpFile.Close() - require.NoError(t, err) - - return tmpFile.Name() -} - -func updateOriginInAcceptContent(content map[string]any, newOrigin string) { - if private, ok := content["private"].([]any); ok { - for _, entry := range private { - if entryMap, ok := entry.(map[string]any); ok { - entryMap["origin"] = newOrigin - } - } - } -} diff --git a/agent/server/snykbroker/reflector_key_test.go b/agent/server/snykbroker/reflector_key_test.go deleted file mode 100644 index 801bcb8c..00000000 --- a/agent/server/snykbroker/reflector_key_test.go +++ /dev/null @@ -1,136 +0,0 @@ -package snykbroker - -import ( - "fmt" - "net/url" - "sync" - "testing" - - "github.com/cortexapps/axon/server/snykbroker/acceptfile" - "github.com/stretchr/testify/require" -) - -func proxyPath(t *testing.T, proxyURI string) string { - u, err := url.Parse(proxyURI) - require.NoError(t, err) - return u.Path -} - -func TestProxyEntryKeyStableAcrossHeaderOrder(t *testing.T) { - headers := map[string]string{ - "Authorization": "Bearer ${plugin:gcp-token}", - "X-GitHub-Api-Version": "2022-11-28", - "X-Third": "three", - } - first, err := newProxyEntry("https://example.com", false, 8080, acceptfile.NewResolverMapFromMap(headers), nil) - require.NoError(t, err) - // map iteration order is randomized per map instance, so repeated - // construction flushes out order-dependent hashing - for i := 0; i < 20; i++ { - next, err := newProxyEntry("https://example.com", false, 8080, acceptfile.NewResolverMapFromMap(headers), nil) - require.NoError(t, err) - require.Equal(t, first.key(), next.key()) - } -} - -// A wildcard entry has no key component of its own; the family lives in -// TargetURI, already hashed. This pins that two families cannot collide. -func TestProxyEntryKeyDistinguishesWildcardFamilies(t *testing.T) { - keyFor := func(t *testing.T, origin string) string { - t.Helper() - entry, err := newProxyEntry(origin, false, 8080, nil, nil) - require.NoError(t, err) - return entry.key() - } - - family := keyFor(t, "https://*.api.example.net") - otherFamily := keyFor(t, "https://*.api.example.org") - nestedFamily := keyFor(t, "https://*.internal.api.example.net") - concrete := keyFor(t, "https://alpha.api.example.net") - - keys := map[string]string{ - "family": family, - "other family": otherFamily, - "nested family": nestedFamily, - "concrete": concrete, - } - seen := make(map[string]string, len(keys)) - for name, key := range keys { - if previous, collided := seen[key]; collided { - t.Fatalf("%s and %s hash to the same key %q", previous, name, key) - } - seen[key] = name - } - - // Stable across construction, so re-registering reuses the entry. - for i := 0; i < 20; i++ { - require.Equal(t, family, keyFor(t, "https://*.api.example.net")) - } -} - -// TestConcurrentGetProxyAndParseTargetUri reproduces the production race -// between registration writing rr.targets (the broker start path retries -// registration on its own goroutine, so it can register entries long after -// Start returned) and ServeHTTP reading it through parseTargetUri. Mutating -// the map in place makes this a concurrent map read-and-write, which is a Go -// runtime throw rather than a tolerable race. Only meaningful under -race. -func TestConcurrentGetProxyAndParseTargetUri(t *testing.T) { - env := newTestReflectorEnv(t) - - // seed entries so readers resolve real hashes while writers add more - seedPaths := make([]string, 0, 4) - for i := 0; i < 4; i++ { - entry, err := env.Reflector.getProxy(fmt.Sprintf("http://seed-%d.example.com", i), false, nil) - require.NoError(t, err) - seedPaths = append(seedPaths, proxyPath(t, entry.proxyURI)) - } - - const workers = 16 - const perWorker = 50 - var wg sync.WaitGroup - errs := make(chan error, 2*workers*perWorker) - - for w := 0; w < workers; w++ { - wg.Add(1) - go func(w int) { - defer wg.Done() - for i := 0; i < perWorker; i++ { - // a distinct URI per iteration, so every call writes a new entry - _, err := env.Reflector.getProxy(fmt.Sprintf("http://w%d-i%d.example.com", w, i), false, nil) - if err != nil { - errs <- fmt.Errorf("getProxy w=%d i=%d: %w", w, i, err) - return - } - } - }(w) - } - - for r := 0; r < workers; r++ { - wg.Add(1) - go func(r int) { - defer wg.Done() - for i := 0; i < perWorker; i++ { - path := seedPaths[(r+i)%len(seedPaths)] - entry, _, err := env.Reflector.parseTargetUri(path) - if err != nil { - errs <- fmt.Errorf("parseTargetUri r=%d i=%d path=%s: %w", r, i, path, err) - return - } - if entry == nil { - errs <- fmt.Errorf("parseTargetUri r=%d i=%d path=%s: nil entry", r, i, path) - return - } - } - }(r) - } - - wg.Wait() - close(errs) - for err := range errs { - require.NoError(t, err) - } - - // every writer URI registered exactly one entry, plus the seeds. A lost - // copy-on-write update would show up here as a short map. - require.Len(t, *env.Reflector.targets.Load(), 4+workers*perWorker) -} diff --git a/agent/server/snykbroker/reflector_test.go b/agent/server/snykbroker/reflector_test.go deleted file mode 100644 index 2e6c2bf9..00000000 --- a/agent/server/snykbroker/reflector_test.go +++ /dev/null @@ -1,766 +0,0 @@ -package snykbroker - -import ( - "crypto/tls" - "crypto/x509" - "fmt" - "io" - "net" - "net/http" - "net/http/httptest" - "net/url" - "testing" - "time" - - "github.com/cortexapps/axon/config" - "github.com/gorilla/mux" - "github.com/gorilla/websocket" - "github.com/prometheus/client_golang/prometheus" - "github.com/stretchr/testify/require" -) - -type testReflectorEnv struct { - Reflector *RegistrationReflector - Server *httptest.Server - Router *mux.Router -} - -func newTestReflectorEnv(t *testing.T) *testReflectorEnv { - return newTestReflectorEnvWithConfig(t, config.AgentConfig{ - ReflectorWebSocketUpgrade: true, - }) -} - -// waitForTunnelDrain blocks until no WebSocket tunnel is still copying. -// activeConnections is decremented only after both copy goroutines have -// returned, so reaching zero means none of them can log again. -func waitForTunnelDrain(t *testing.T, rr *RegistrationReflector) { - t.Helper() - if rr.wsProxy == nil { - return - } - deadline := time.Now().Add(5 * time.Second) - for rr.wsProxy.ActiveConnections() > 0 { - if time.Now().After(deadline) { - t.Errorf("websocket tunnels did not drain within 5s (%d still active)", - rr.wsProxy.ActiveConnections()) - return - } - time.Sleep(time.Millisecond) - } -} - -// newReflectorWithDrain builds a reflector and registers the tunnel drain in one -// step. Any test that can establish a tunnel must go through this rather than -// calling NewRegistrationReflector directly: closing the servers is not enough, -// because a hijacked WebSocket is not an outstanding request as far as -// httptest.Server.Close is concerned, so Close returns while the copy -// goroutines are still running. This asserts they finish; newTestLogger is what -// makes a log that still slips out afterwards safe. -// -// Registered here rather than at the call site so the drain is always the first -// cleanup registered, and therefore the last to run - after whatever the test -// defers or registers to close its connections and servers. -func newReflectorWithDrain(t *testing.T, params RegistrationReflectorParams) *RegistrationReflector { - t.Helper() - rr := NewRegistrationReflector(params) - t.Cleanup(func() { waitForTunnelDrain(t, rr) }) - return rr -} - -func newTestReflectorEnvWithConfig(t *testing.T, cfg config.AgentConfig) *testReflectorEnv { - logger := newTestLogger(t) - rr := newReflectorWithDrain(t, RegistrationReflectorParams{ - Logger: logger, - Registry: prometheus.NewRegistry(), - Config: cfg, - }) - router := mux.NewRouter() - server := httptest.NewServer(router) - t.Cleanup(server.Close) - t.Cleanup(func() { rr.Stop() }) - return &testReflectorEnv{ - Reflector: rr, - Server: server, - Router: router, - } -} - -func TestGetProxyAndProxyURI(t *testing.T) { - env := newTestReflectorEnv(t) - target := env.Server.URL - proxyEntry, err := env.Reflector.getProxy(target, false, nil) - require.NoError(t, err) - require.NotNil(t, proxyEntry) - require.Equal(t, target, proxyEntry.TargetURI) - - uri := env.Reflector.ProxyURI(target) - require.Contains(t, uri, "127.0.0.1") -} - -func TestDefaultProxyURI(t *testing.T) { - env := newTestReflectorEnv(t) - target := env.Server.URL - uri := env.Reflector.ProxyURI(target, WithDefault(true)) - require.Equal(t, fmt.Sprintf("http://127.0.0.1:%d", env.Reflector.server.Port()), uri) -} - -func TestServeHTTP_Proxy(t *testing.T) { - env := newTestReflectorEnv(t) - - env.Router.Handle("/get", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusAccepted) - _, _ = w.Write([]byte("Proxy response")) - })) - - target := env.Server.URL - // Build a request to the proxy path - proxyUri := env.Reflector.ProxyURI(target) - req, _ := http.NewRequest("GET", proxyUri+"/get", nil) - resp, err := http.DefaultClient.Do(req) - require.NoError(t, err) - defer resp.Body.Close() - body, _ := io.ReadAll(resp.Body) - require.Equal(t, http.StatusAccepted, resp.StatusCode, string(body)) -} - -func TestServeHTTP_InvalidTarget(t *testing.T) { - env := newTestReflectorEnv(t) - env.Reflector.Start() - req, _ := http.NewRequest("GET", fmt.Sprintf("http://127.0.0.1:%d/!99999999!/foo", env.Reflector.server.Port()), nil) - resp, err := http.DefaultClient.Do(req) - require.NoError(t, err) - defer resp.Body.Close() - require.Equal(t, http.StatusBadGateway, resp.StatusCode) -} - -func TestServeHTTP_DefaultTarget(t *testing.T) { - env := newTestReflectorEnv(t) - - env.Router.Handle("/get", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusAccepted) - _, _ = w.Write([]byte("Proxy response")) - })) - - target := env.Server.URL - // Build a request to the proxy path - proxyUri := env.Reflector.ProxyURI(target, WithDefault(true)) - req, _ := http.NewRequest("GET", proxyUri+"/get", nil) - resp, err := http.DefaultClient.Do(req) - require.NoError(t, err) - defer resp.Body.Close() - body, _ := io.ReadAll(resp.Body) - require.Equal(t, http.StatusAccepted, resp.StatusCode, string(body)) -} - -func TestGetHash(t *testing.T) { - env := newTestReflectorEnv(t) - hash := env.Reflector.extractHash("!12345!") - require.Equal(t, "12345", hash) - require.Equal(t, "", env.Reflector.extractHash("12345")) - require.Equal(t, "", env.Reflector.extractHash("!bad")) -} - -func TestStop(t *testing.T) { - env := newTestReflectorEnv(t) - err := env.Reflector.Stop() - require.NoError(t, err) -} - -func TestStartTwice(t *testing.T) { - env := newTestReflectorEnv(t) - port1, err1 := env.Reflector.Start() - port2, err2 := env.Reflector.Start() - require.NoError(t, err1) - require.NoError(t, err2) - require.Equal(t, port1, port2) -} - -func TestModuleStartup(t *testing.T) { - - cases := []struct { - name string - cfg config.AgentConfig - expected bool - }{ - { - name: "Disabled", - cfg: config.AgentConfig{HttpRelayReflectorMode: config.RelayReflectorDisabled}, - expected: false, - }, - { - name: "AllTraffic", - cfg: config.AgentConfig{HttpRelayReflectorMode: config.RelayReflectorAllTraffic}, - expected: true, - }, - { - name: "RegistrationOnly", - cfg: config.AgentConfig{HttpRelayReflectorMode: config.RelayReflectorRegistrationOnly}, - expected: true, - }, - { - name: "TrafficOnly", - cfg: config.AgentConfig{HttpRelayReflectorMode: config.RelayReflectorTrafficOnly}, - expected: true, - }, - } - - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - cfg := config.AgentConfig{ - HttpRelayReflectorMode: tc.cfg.HttpRelayReflectorMode, - } - result := MaybeNewRegistrationReflector(cfg, RegistrationReflectorParams{ - Logger: newTestLogger(t), - }) - if tc.expected { - require.NotNil(t, result, "Expected reflector to be created") - } else { - require.Nil(t, result, "Expected reflector to be nil") - } - }) - } -} - -// WebSocket upgrader for test server -var testUpgrader = websocket.Upgrader{ - CheckOrigin: func(r *http.Request) bool { return true }, -} - -func TestWebSocketUpgradeDetection(t *testing.T) { - _ = newTestReflectorEnv(t) - - // Test that WebSocket upgrade is detected - req, _ := http.NewRequest("GET", "/test", nil) - req.Header.Set("Connection", "Upgrade") - req.Header.Set("Upgrade", "websocket") - require.True(t, IsWebSocketUpgrade(req)) - - // Test that normal request is not detected as WebSocket - req2, _ := http.NewRequest("GET", "/test", nil) - require.False(t, IsWebSocketUpgrade(req2)) - - // Test case insensitivity - req3, _ := http.NewRequest("GET", "/test", nil) - req3.Header.Set("Connection", "upgrade") - req3.Header.Set("Upgrade", "WebSocket") - require.True(t, IsWebSocketUpgrade(req3)) -} - -func TestWebSocketUpgradeDisabled(t *testing.T) { - // Note: The config check for ReflectorWebSocketUpgrade is now done in the - // reflector's ServeHTTP method, not in IsWebSocketUpgrade itself. - // IsWebSocketUpgrade just checks the headers. - - // WebSocket upgrade headers present - IsWebSocketUpgrade returns true - // (the config check happens in the reflector) - req, _ := http.NewRequest("GET", "/test", nil) - req.Header.Set("Connection", "Upgrade") - req.Header.Set("Upgrade", "websocket") - require.True(t, IsWebSocketUpgrade(req), "IsWebSocketUpgrade should return true based on headers") -} - -func TestWebSocketProxyFullFlow(t *testing.T) { - env := newTestReflectorEnv(t) - - // Create a WebSocket echo server - env.Router.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) { - conn, err := testUpgrader.Upgrade(w, r, nil) - if err != nil { - t.Logf("WebSocket upgrade failed: %v", err) - return - } - defer conn.Close() - - // Echo messages back - for { - messageType, message, err := conn.ReadMessage() - if err != nil { - break - } - if err := conn.WriteMessage(messageType, message); err != nil { - break - } - } - }) - - // Get proxy URI for the WebSocket server - proxyURI := env.Reflector.ProxyURI(env.Server.URL) - - // Connect to WebSocket through the reflector - wsURL := "ws" + proxyURI[4:] + "/ws" // Convert http:// to ws:// - dialer := websocket.Dialer{} - conn, resp, err := dialer.Dial(wsURL, nil) - require.NoError(t, err, "WebSocket dial should succeed") - require.Equal(t, http.StatusSwitchingProtocols, resp.StatusCode) - defer conn.Close() - - // Send a message - testMessage := []byte("Hello WebSocket!") - err = conn.WriteMessage(websocket.TextMessage, testMessage) - require.NoError(t, err, "WebSocket write should succeed") - - // Receive the echo - messageType, message, err := conn.ReadMessage() - require.NoError(t, err, "WebSocket read should succeed") - require.Equal(t, websocket.TextMessage, messageType) - require.Equal(t, testMessage, message, "Echo message should match") -} - -func TestWebSocketProxyWithDefaultTarget(t *testing.T) { - env := newTestReflectorEnv(t) - - // Create a WebSocket echo server - env.Router.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) { - conn, err := testUpgrader.Upgrade(w, r, nil) - if err != nil { - t.Logf("WebSocket upgrade failed: %v", err) - return - } - defer conn.Close() - - // Echo with prefix - for { - messageType, message, err := conn.ReadMessage() - if err != nil { - break - } - reply := append([]byte("echo: "), message...) - if err := conn.WriteMessage(messageType, reply); err != nil { - break - } - } - }) - - // Use default proxy (no hash in path) - proxyURI := env.Reflector.ProxyURI(env.Server.URL, WithDefault(true)) - - // Connect to WebSocket through the reflector - wsURL := "ws" + proxyURI[4:] + "/ws" - dialer := websocket.Dialer{} - conn, resp, err := dialer.Dial(wsURL, nil) - require.NoError(t, err, "WebSocket dial should succeed") - require.Equal(t, http.StatusSwitchingProtocols, resp.StatusCode) - defer conn.Close() - - // Send and receive - testMessage := []byte("test") - err = conn.WriteMessage(websocket.TextMessage, testMessage) - require.NoError(t, err) - - _, message, err := conn.ReadMessage() - require.NoError(t, err) - require.Equal(t, []byte("echo: test"), message) -} - -func TestWebSocketProxyConnectionRefused(t *testing.T) { - env := newTestReflectorEnv(t) - - // Register a proxy to a non-existent server (connection refused) - proxyURI := env.Reflector.ProxyURI("http://127.0.0.1:59999") // Port that's not listening - - // Try to connect via WebSocket - wsURL := "ws" + proxyURI[4:] + "/ws" - dialer := websocket.Dialer{} - _, resp, err := dialer.Dial(wsURL, nil) - - // Should get an error with a 502 response - require.Error(t, err) - require.NotNil(t, resp, "Expected HTTP response with status code") - require.Equal(t, http.StatusBadGateway, resp.StatusCode, "Expected 502 Bad Gateway") -} - -func TestRecordTrafficAndLastTrafficTime(t *testing.T) { - env := newTestReflectorEnv(t) - - // The constructor records a startup, not traffic, so LastTrafficTime - // starts unset while LastStartupTime is recent. - initial := env.Reflector.LastTrafficTime() - require.True(t, initial.Before(time.Now().Add(-time.Hour)), "LastTrafficTime should be unset before any traffic") - require.False(t, env.Reflector.LastStartupTime().IsZero(), "LastStartupTime should be initialized by the constructor") - - // Wait briefly and record traffic - time.Sleep(10 * time.Millisecond) - env.Reflector.RecordTraffic() - updated := env.Reflector.LastTrafficTime() - require.True(t, updated.After(initial), "LastTrafficTime should advance after RecordTraffic") -} - -func TestServeHTTPUpdatesLastTrafficTime(t *testing.T) { - env := newTestReflectorEnv(t) - - // Set up a target server - env.Router.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - }) - proxyURI := env.Reflector.ProxyURI(env.Server.URL) - - initial := env.Reflector.LastTrafficTime() - time.Sleep(10 * time.Millisecond) - - // Make a request through the reflector - resp, err := http.Get(proxyURI + "/hello") - require.NoError(t, err) - resp.Body.Close() - require.Equal(t, http.StatusOK, resp.StatusCode) - - // LastTrafficTime should have been updated - afterRequest := env.Reflector.LastTrafficTime() - require.True(t, afterRequest.After(initial), "LastTrafficTime should update on ServeHTTP") -} - -func TestWebSocketProxyInvalidTarget(t *testing.T) { - env := newTestReflectorEnv(t) - env.Reflector.Start() - - // Make a WebSocket request to an invalid hash (no registered target) - req, _ := http.NewRequest("GET", fmt.Sprintf("http://127.0.0.1:%d/!invalid!/ws", env.Reflector.server.Port()), nil) - req.Header.Set("Connection", "Upgrade") - req.Header.Set("Upgrade", "websocket") - - resp, err := http.DefaultClient.Do(req) - require.NoError(t, err) - defer resp.Body.Close() - - // Should get 502 Bad Gateway for invalid target - require.Equal(t, http.StatusBadGateway, resp.StatusCode) -} - -func TestWSTunnelTracking(t *testing.T) { - env := newTestReflectorEnv(t) - - // Initially, tunnel should not be connected - require.False(t, env.Reflector.IsWSTunnelConnected()) - - // Create a WebSocket echo server - env.Router.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) { - conn, err := testUpgrader.Upgrade(w, r, nil) - if err != nil { - t.Logf("WebSocket upgrade failed: %v", err) - return - } - defer conn.Close() - for { - messageType, message, err := conn.ReadMessage() - if err != nil { - break - } - conn.WriteMessage(messageType, message) - } - }) - - proxyURI := env.Reflector.ProxyURI(env.Server.URL, WithDefault(true)) - - wsURL := "ws" + proxyURI[4:] + "/ws" - dialer := websocket.Dialer{} - conn, resp, err := dialer.Dial(wsURL, nil) - require.NoError(t, err) - require.Equal(t, http.StatusSwitchingProtocols, resp.StatusCode) - - // Tunnel should now be connected - time.Sleep(50 * time.Millisecond) - require.True(t, env.Reflector.IsWSTunnelConnected()) - - // Close the WebSocket connection - conn.Close() - - // Wait for the tunnel to detect the close - time.Sleep(100 * time.Millisecond) - require.False(t, env.Reflector.IsWSTunnelConnected()) -} - -func TestWSTunnelCloseCallback(t *testing.T) { - env := newTestReflectorEnv(t) - - callbackCalled := make(chan struct{}, 1) - env.Reflector.SetOnWSTunnelClose(func() { - callbackCalled <- struct{}{} - }) - - env.Router.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) { - conn, err := testUpgrader.Upgrade(w, r, nil) - if err != nil { - t.Logf("WebSocket upgrade failed: %v", err) - return - } - defer conn.Close() - for { - _, _, err := conn.ReadMessage() - if err != nil { - break - } - } - }) - - proxyURI := env.Reflector.ProxyURI(env.Server.URL, WithDefault(true)) - wsURL := "ws" + proxyURI[4:] + "/ws" - dialer := websocket.Dialer{} - conn, _, err := dialer.Dial(wsURL, nil) - require.NoError(t, err) - - time.Sleep(50 * time.Millisecond) - require.True(t, env.Reflector.IsWSTunnelConnected()) - - conn.Close() - - select { - case <-callbackCalled: - // Success - case <-time.After(2 * time.Second): - t.Fatal("Expected tunnel close callback to be called") - } - - require.False(t, env.Reflector.IsWSTunnelConnected()) -} - -func TestWebSocketProxyServerRejectsUpgrade(t *testing.T) { - env := newTestReflectorEnv(t) - - // Create a server that rejects WebSocket upgrades - env.Router.HandleFunc("/reject", func(w http.ResponseWriter, r *http.Request) { - // Don't upgrade, just return a normal HTTP response - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte("WebSocket not supported")) - }) - - proxyURI := env.Reflector.ProxyURI(env.Server.URL) - wsURL := "ws" + proxyURI[4:] + "/reject" - - dialer := websocket.Dialer{} - _, _, err := dialer.Dial(wsURL, nil) - - // Should get an error because server rejected the upgrade - require.Error(t, err, "Expected error when server rejects WebSocket upgrade") -} - -func TestWebSocketProxyThroughHTTPProxy(t *testing.T) { - // Create a WebSocket echo server (the actual target) - targetRouter := mux.NewRouter() - targetRouter.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) { - conn, err := testUpgrader.Upgrade(w, r, nil) - if err != nil { - t.Logf("WebSocket upgrade failed: %v", err) - return - } - defer conn.Close() - - // Echo messages back - for { - messageType, message, err := conn.ReadMessage() - if err != nil { - break - } - if err := conn.WriteMessage(messageType, message); err != nil { - break - } - } - }) - targetServer := httptest.NewServer(targetRouter) - defer targetServer.Close() - - // Create an HTTP CONNECT proxy - proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Method != "CONNECT" { - http.Error(w, "Expected CONNECT", http.StatusMethodNotAllowed) - return - } - - t.Logf("Proxy received CONNECT to %s", r.Host) - - // Connect to the target - targetConn, err := net.Dial("tcp", r.Host) - if err != nil { - http.Error(w, err.Error(), http.StatusBadGateway) - return - } - - // Hijack the client connection first - hijacker, ok := w.(http.Hijacker) - if !ok { - targetConn.Close() - http.Error(w, "Hijacking not supported", http.StatusInternalServerError) - return - } - clientConn, _, err := hijacker.Hijack() - if err != nil { - targetConn.Close() - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - - // Send 200 OK manually after hijacking (proper CONNECT response format) - _, err = clientConn.Write([]byte("HTTP/1.1 200 Connection Established\r\n\r\n")) - if err != nil { - clientConn.Close() - targetConn.Close() - return - } - - // Bidirectional copy - go func() { - io.Copy(targetConn, clientConn) - targetConn.Close() - }() - go func() { - io.Copy(clientConn, targetConn) - clientConn.Close() - }() - })) - defer proxyServer.Close() - - // Create reflector with the proxy configured via transport - logger := newTestLogger(t) - - // Parse proxy URL to set up transport - proxyURL, _ := url.Parse(proxyServer.URL) - transport := &http.Transport{ - Proxy: http.ProxyURL(proxyURL), - } - - rr := newReflectorWithDrain(t, RegistrationReflectorParams{ - Logger: logger, - Registry: prometheus.NewRegistry(), - Transport: transport, - Config: config.AgentConfig{ - ReflectorWebSocketUpgrade: true, - }, - }) - - router := mux.NewRouter() - rr.RegisterRoutes(router) - reflectorServer := httptest.NewServer(router) - defer reflectorServer.Close() - - // Register the target with the reflector - proxyURI := rr.ProxyURI(targetServer.URL) - - // Connect to WebSocket through the reflector (which should use the HTTP proxy) - wsURL := "ws" + proxyURI[4:] + "/ws" - dialer := websocket.Dialer{} - conn, resp, err := dialer.Dial(wsURL, nil) - require.NoError(t, err, "WebSocket dial through proxy should succeed") - require.Equal(t, http.StatusSwitchingProtocols, resp.StatusCode) - defer conn.Close() - - // Send a message - testMessage := []byte("Hello through proxy!") - err = conn.WriteMessage(websocket.TextMessage, testMessage) - require.NoError(t, err, "WebSocket write should succeed") - - // Receive the echo - messageType, message, err := conn.ReadMessage() - require.NoError(t, err, "WebSocket read should succeed") - require.Equal(t, websocket.TextMessage, messageType) - require.Equal(t, testMessage, message, "Echo message should match") -} - -func TestWebSocketProxyTLSConfigFromTransport(t *testing.T) { - logger := newTestLogger(t) - - // Create a transport with custom TLS config - customRoots := x509.NewCertPool() - customTLSConfig := &tls.Config{ - RootCAs: customRoots, - InsecureSkipVerify: false, - } - transport := &http.Transport{ - TLSClientConfig: customTLSConfig, - } - - // Create WebSocketProxy with the transport - wsProxy := NewWebSocketProxy(logger, transport) - - // Get TLS config for a host (using the internal method via reflection or by testing behavior) - // Since getTLSConfig is unexported, we test the behavior indirectly by verifying - // the proxy was created with the transport - require.NotNil(t, wsProxy) - - // The WebSocketProxy should use the transport's TLS config when dialing - // This is tested by the TestWebSocketProxyThroughHTTPProxy test which verifies - // the full flow works with a custom transport -} - -func TestWebSocketProxyWithoutTransport(t *testing.T) { - logger := newTestLogger(t) - - // Create WebSocketProxy without transport - wsProxy := NewWebSocketProxy(logger, nil) - - require.NotNil(t, wsProxy) - require.False(t, wsProxy.IsConnected()) -} - -// The reflector must preserve percent-encoded characters (notably %2F) in the -// path when forwarding to the registered target. Reading from r.URL.Path alone -// and writing back to r.URL.Path without updating r.URL.RawPath causes Go's -// reverse-proxy to emit the decoded path on the wire, which turns a GitLab -// namespace/project identifier like `foo%2Fbar` into `foo/bar` and makes -// GitLab return 404 for anything past the project segment. -func TestServeHTTP_PreservesPercentEncodedSlashMidPath(t *testing.T) { - env := newTestReflectorEnv(t) - - var gotEscapedPath string - env.Router.PathPrefix("/api/").Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - gotEscapedPath = r.URL.EscapedPath() - w.WriteHeader(http.StatusOK) - })) - - proxyURI := env.Reflector.ProxyURI(env.Server.URL) - - const encoded = "/api/v4/projects/test.project%2Fcli-functional-test-xxx/approval_rules" - req, err := http.NewRequest("GET", proxyURI+encoded, nil) - require.NoError(t, err) - resp, err := http.DefaultClient.Do(req) - require.NoError(t, err) - defer resp.Body.Close() - require.Equal(t, http.StatusOK, resp.StatusCode) - - require.Equal(t, encoded, gotEscapedPath, - "mid-path %%2F must survive the reflector hop") -} - -func TestServeHTTP_PreservesPercentEncodedSlashTrailing(t *testing.T) { - env := newTestReflectorEnv(t) - - var gotEscapedPath string - env.Router.PathPrefix("/api/").Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - gotEscapedPath = r.URL.EscapedPath() - w.WriteHeader(http.StatusOK) - })) - - proxyURI := env.Reflector.ProxyURI(env.Server.URL) - - const encoded = "/api/v4/projects/test.project%2Fcli-functional-test-xxx" - req, err := http.NewRequest("GET", proxyURI+encoded, nil) - require.NoError(t, err) - resp, err := http.DefaultClient.Do(req) - require.NoError(t, err) - defer resp.Body.Close() - require.Equal(t, http.StatusOK, resp.StatusCode) - - require.Equal(t, encoded, gotEscapedPath, - "trailing %%2F must survive the reflector hop") -} - -func TestServeHTTP_PreservesPercentEncodedSlashDefaultTarget(t *testing.T) { - env := newTestReflectorEnv(t) - - var gotEscapedPath string - env.Router.PathPrefix("/api/").Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - gotEscapedPath = r.URL.EscapedPath() - w.WriteHeader(http.StatusOK) - })) - - proxyURI := env.Reflector.ProxyURI(env.Server.URL, WithDefault(true)) - - const encoded = "/api/v4/projects/test.project%2Fcli-functional-test-xxx/approval_rules" - req, err := http.NewRequest("GET", proxyURI+encoded, nil) - require.NoError(t, err) - resp, err := http.DefaultClient.Do(req) - require.NoError(t, err) - defer resp.Body.Close() - require.Equal(t, http.StatusOK, resp.StatusCode) - - require.Equal(t, encoded, gotEscapedPath, - "mid-path %%2F must survive the reflector hop in default-target mode") -} diff --git a/agent/server/snykbroker/relay_instance_manager.go b/agent/server/snykbroker/relay_instance_manager.go deleted file mode 100644 index e828b581..00000000 --- a/agent/server/snykbroker/relay_instance_manager.go +++ /dev/null @@ -1,924 +0,0 @@ -package snykbroker - -import ( - "context" - "errors" - "fmt" - "io" - "net" - "net/http" - "os" - "path" - "strings" - "sync" - "sync/atomic" - "time" - - "github.com/cortexapps/axon/common" - "github.com/cortexapps/axon/config" - cortexHttp "github.com/cortexapps/axon/server/http" - "github.com/cortexapps/axon/server/snykbroker/acceptfile" - "github.com/cortexapps/axon/util" - "github.com/gorilla/mux" - "github.com/prometheus/client_golang/prometheus" - "go.uber.org/fx" - "go.uber.org/zap" -) - -const defaultSnykBroker = "snyk-broker" -const brokerPort = 7343 - -// restartRequest is sent to the restart channel by any code path that -// needs to restart the broker. The generation field ties the request -// to the broker lifecycle that triggered it, so the consumer can -// discard stale requests that arrive after a restart has already -// happened. -type restartRequest struct { - reason string - generation int32 -} - -type RelayInstanceManager interface { - Start() error - Restart() error - Close() error -} - -type relayInstanceManager struct { - integrationInfo common.IntegrationInfo - registration Registration - config config.AgentConfig - logger *zap.Logger - // supervisor is written by Start's goroutine and taken by Close, from - // different goroutines; supervisorMu guards it. Use currentSupervisor. - supervisorMu sync.Mutex - supervisor *Supervisor - running atomic.Bool - startCount atomic.Int32 - generation atomic.Int32 // incremented on each Start(), used to deduplicate restart requests - tokenInfo *tokenInfo - operationsCounter *prometheus.CounterVec - transport *http.Transport - - reflector *RegistrationReflector - restartCh chan restartRequest - - // filteredCAPath is the broker's copy of CA_CERT_PATH without distrusted - // CAs, removed when the next broker start writes a new one. - filteredCAPath string -} - -type tokenInfo struct { - ServerUri string - OriginalUri string - Token string - HasChanged bool -} - -func (t *tokenInfo) equals(other *tokenInfo) bool { - if other == nil { - return false - } - if t.OriginalUri != other.OriginalUri { - return false - } - if t.Token != other.Token { - return false - } - return true -} - -type RelayInstanceManagerParams struct { - fx.In - Lifecycle fx.Lifecycle `optional:"true"` - Config config.AgentConfig - Logger *zap.Logger - IntegrationInfo common.IntegrationInfo - HttpServer cortexHttp.Server - Registration Registration - Transport *http.Transport `optional:"true"` - Registry *prometheus.Registry `optional:"true"` - Reflector *RegistrationReflector `optional:"true"` -} - -func NewRelayInstanceManager( - p RelayInstanceManagerParams, -) RelayInstanceManager { - mgr := &relayInstanceManager{ - config: p.Config, - logger: p.Logger, - integrationInfo: p.IntegrationInfo, - registration: p.Registration, - operationsCounter: prometheus.NewCounterVec( - prometheus.CounterOpts{ - Name: "broker_operations", - Help: "Counter for broker operations", - }, - []string{"integration", "alias", "operation", "status"}, - ), - transport: p.Transport, - restartCh: make(chan restartRequest, 1), - } - - p.HttpServer.RegisterHandler(mgr) - - if p.Registry != nil { - p.Registry.MustRegister(mgr.operationsCounter) - } - - mgr.reflector = p.Reflector - go mgr.restartConsumer() - - if p.Lifecycle != nil { - p.Lifecycle.Append(fx.Hook{ - OnStart: func(ctx context.Context) error { - return mgr.Start() - }, - OnStop: func(ctx context.Context) error { - return mgr.Close() - }, - }) - } - return mgr -} - -func (r *relayInstanceManager) RegisterRoutes(mux *mux.Router) error { - subRouter := mux.PathPrefix(fmt.Sprintf("%s/broker", cortexHttp.AxonPathRoot)).Subrouter() - subRouter.HandleFunc("/restart", r.handleRestart) - subRouter.HandleFunc("/reregister", r.handleReregister) - subRouter.HandleFunc("/systemcheck", r.handleSystemCheck) - return nil -} - -func (r *relayInstanceManager) ServeHTTP(w http.ResponseWriter, req *http.Request) { - // should never be called, here just to satisfy the interface - w.WriteHeader(http.StatusNotFound) -} - -func (r *relayInstanceManager) emitOperationCounter(operation string, success bool) { - status := "success" - if !success { - status = "failure" - } - r.operationsCounter.WithLabelValues(r.integrationInfo.Integration.String(), r.integrationInfo.Alias, operation, status).Inc() -} - -func (r *relayInstanceManager) handleRestart(w http.ResponseWriter, req *http.Request) { - if req.Method != http.MethodPost { - w.WriteHeader(http.StatusMethodNotAllowed) - return - } - - err := r.Restart() - if err != nil { - r.logger.Error("Unable to reregister", zap.Error(err)) - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte("Unable to reregister")) - return - } - w.WriteHeader(http.StatusOK) -} - -func (r *relayInstanceManager) handleReregister(w http.ResponseWriter, req *http.Request) { - if req.Method != http.MethodPost { - w.WriteHeader(http.StatusMethodNotAllowed) - return - } - r.logger.Info("Reregistering broker") - info, err := r.refreshTokenInfo() - r.emitOperationCounter("reregister", err == nil) - if err != nil { - r.logger.Error("Unable to reregister", zap.Error(err)) - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte("Unable to reregister")) - return - } - - if info.HasChanged { - r.requestRestart("reregister", r.generation.Load()) - } - w.WriteHeader(http.StatusOK) -} - -func (r *relayInstanceManager) getSnykBrokerPort() int { - if r.config.SnykBrokerPort == 0 { - return brokerPort - } - return r.config.SnykBrokerPort -} - -// systemCheckTimeout bounds the proxied call to the broker's /systemcheck. -// A package variable so tests can shorten it. -var systemCheckTimeout = 10 * time.Second - -func (r *relayInstanceManager) handleSystemCheck(w http.ResponseWriter, req *http.Request) { - if req.Method != http.MethodGet { - w.WriteHeader(http.StatusMethodNotAllowed) - return - } - - ctx, cancel := context.WithTimeout(req.Context(), systemCheckTimeout) - defer cancel() - - upstream, err := http.NewRequestWithContext(ctx, http.MethodGet, - fmt.Sprintf("http://localhost:%d/systemcheck", r.getSnykBrokerPort()), nil) - if err == nil { - var resp *http.Response - resp, err = http.DefaultClient.Do(upstream) - if err == nil { - defer resp.Body.Close() - // Read before writing any header, so a body that dies mid-way is - // one 500 rather than a 200 header followed by a truncated body. - body, readErr := io.ReadAll(resp.Body) - if readErr != nil { - r.logger.Error("Unable to read system check response", zap.Error(readErr)) - w.WriteHeader(http.StatusInternalServerError) - return - } - for k, v := range resp.Header { - w.Header().Set(k, strings.Join(v, ",")) - } - w.WriteHeader(resp.StatusCode) - w.Write(body) - return - } - } - r.logger.Error("Unable to get system check", zap.Error(err)) - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte("Unable to get system check")) -} - -// requestRestart sends a restart request for the given generation. -// If the channel is full (a restart is already pending) the request -// is dropped — the pending restart will cover it. -func (r *relayInstanceManager) requestRestart(reason string, gen int32) { - select { - case r.restartCh <- restartRequest{reason: reason, generation: gen}: - r.logger.Info("Restart requested", zap.String("reason", reason), zap.Int32("generation", gen)) - default: - r.logger.Debug("Restart already pending, dropping duplicate", - zap.String("reason", reason), zap.Int32("generation", gen)) - } -} - -// restartConsumer is the single goroutine that processes restart -// requests. It deduplicates by generation: if the broker has already -// moved to a newer generation by the time we read the request, the -// request is stale and we skip it. -// -// It also doubles as the idle watchdog: every minute it checks -// shouldRestart() and produces a restart request if the broker has -// been idle too long. -func (r *relayInstanceManager) restartConsumer() { - ticker := time.NewTicker(15 * time.Second) - defer ticker.Stop() - - for { - var req restartRequest - select { - case req = <-r.restartCh: - // explicit restart request - case <-ticker.C: - if ok, reason := r.shouldRestart(); ok { - req = restartRequest{reason: reason, generation: r.generation.Load()} - } else { - continue - } - } - - current := r.generation.Load() - if req.generation != current { - r.logger.Info("Ignoring stale restart request", - zap.String("reason", req.reason), - zap.Int32("requestGeneration", req.generation), - zap.Int32("currentGeneration", current)) - continue - } - r.logger.Info("Processing restart request", - zap.String("reason", req.reason), - zap.Int32("generation", req.generation)) - r.emitOperationCounter("restart_"+req.reason, true) - - // Retry with backoff until the restart succeeds or we're - // shut down. This is the persistent outer watchdog: no - // matter how many times the broker or registration fails, - // we keep trying. - for attempt := 0; ; attempt++ { - if err := r.Restart(); err != nil { - delay := r.restartBackoff(attempt) - r.logger.Error("Restart failed, will retry", - zap.String("reason", req.reason), - zap.Int("attempt", attempt+1), - zap.Duration("backoff", delay), - zap.Error(err)) - time.Sleep(delay) - // If we were shut down while sleeping, stop. - if !r.running.Load() { - return - } - continue - } - break - } - } -} - -// shouldRestart checks whether the broker should be restarted due to -// idle timeout. Returns true and the reason string if a restart is needed. -func (r *relayInstanceManager) shouldRestart() (bool, string) { - if r.config.RelayIdleTimeout == 0 || r.reflector == nil { - return false, "" - } - // Each reflecting mode gives the watchdog a signal: relayed requests in - // "traffic", frames on the broker's tunnel in "registration", both in - // "all". Only "disabled" leaves it blind. - mode := r.config.HttpRelayReflectorMode - if !mode.ReflectsTraffic() && !mode.ReflectsRegistration() { - return false, "" - } - if time.Since(r.reflector.LastActivityTime()) >= r.config.RelayIdleTimeout { - return true, "idle_timeout" - } - return false, "" -} - -// restartBackoff returns an exponential backoff duration capped at 60 seconds. -func (r *relayInstanceManager) restartBackoff(attempt int) time.Duration { - base := 5 * time.Second - d := base << uint(attempt) // 5s, 10s, 20s, 40s, 60s ... - if d > 60*time.Second { - d = 60 * time.Second - } - return d -} - -var errSkipBroker = errors.New("NoBrokerToken") - -func (r *relayInstanceManager) Restart() error { - - var err error - - defer func() { - r.emitOperationCounter("restart", err == nil) - }() - - r.logger.Info("Restarting broker, shutting down existing broker") - // re-register and restart supervisor - err = r.Close() - if err != nil { - r.logger.Error("unable to close supervisor on Restart", zap.Error(err)) - } - - // Wait for the broker port to become available. - // After the process exits, TCP sockets may remain in TIME_WAIT state, - // causing EADDRINUSE if we start too quickly. - port := r.getSnykBrokerPort() - if waitErr := r.waitForPortAvailable(port, 10*time.Second); waitErr != nil { - r.logger.Warn("Port not available after timeout, proceeding anyway", - zap.Int("port", port), zap.Error(waitErr)) - } - - r.logger.Info("Restarting broker") - err = r.Start() - if err != nil { - return fmt.Errorf("unable to start supervisor on Restart: %w", err) - } - - // A fresh broker gets a full idle window before the watchdog is allowed - // to suspect it again. Without this, a broker with nothing to relay - // (idle tenant, not a dead tunnel) restarts every tick forever instead - // of once per RelayIdleTimeout. - if r.reflector != nil { - r.reflector.RecordStartup() - } - return nil -} - -// waitForPortAvailable waits until the given port is available for binding, -// or until the timeout expires. This handles the TCP TIME_WAIT issue where -// the OS hasn't released the port yet after the previous process exited. -func (r *relayInstanceManager) waitForPortAvailable(port int, timeout time.Duration) error { - deadline := time.Now().Add(timeout) - addr := fmt.Sprintf("127.0.0.1:%d", port) - - for time.Now().Before(deadline) { - ln, err := net.Listen("tcp", addr) - if err == nil { - ln.Close() - r.logger.Debug("Port is available", zap.Int("port", port)) - return nil - } - r.logger.Debug("Port not yet available, waiting", - zap.Int("port", port), zap.Error(err)) - time.Sleep(100 * time.Millisecond) - } - return fmt.Errorf("port %d not available after %v", port, timeout) -} - -// refreshTokenInfo re-registers and reports whether the registration changed. -// It deliberately does not touch the reflector: callers that only need the -// change signal must not register proxy entries as a side effect. -func (r *relayInstanceManager) refreshTokenInfo() (*tokenInfo, error) { - uri, token, err := r.getUrlAndTokenCore() - if err != nil { - return nil, err - } - - tokenInfo := &tokenInfo{ - ServerUri: uri, - OriginalUri: uri, - Token: token, - } - - if !tokenInfo.equals(r.tokenInfo) { - r.logger.Info("Registration info has changed", - zap.String("uri", tokenInfo.ServerUri), - zap.String("tokenHash", common.TokenHash(tokenInfo.Token)), - ) - tokenInfo.HasChanged = true - r.tokenInfo = tokenInfo - } - - return tokenInfo, nil -} - -// getUrlAndToken additionally registers the reflector's default entry, so it -// belongs to the broker start path only. -func (r *relayInstanceManager) getUrlAndToken() (*tokenInfo, error) { - tokenInfo, err := r.refreshTokenInfo() - if err != nil { - return nil, err - } - - // Route BROKER_SERVER_URL through reflector when mode reflects registration (registration, all). - if r.reflector != nil && r.config.HttpRelayReflectorMode.ReflectsRegistration() { - tokenInfo.ServerUri = r.reflector.ProxyURI(tokenInfo.ServerUri, WithDefault(true)) - } - - return tokenInfo, nil -} - -func (r *relayInstanceManager) getUrlAndTokenCore() (string, string, error) { - - serverUri := os.Getenv("BROKER_SERVER_URL") - token := os.Getenv("BROKER_TOKEN") - if serverUri != "" && token != "" { - return serverUri, token, nil - } - - if r.config.DryRun { - r.logger.Info("Not starting broker due to DRYRUN and missing token") - return "", "", errSkipBroker - } - - reg, err := r.registration.Register(context.Background(), r.integrationInfo.Integration, r.integrationInfo.Alias) - r.emitOperationCounter("register", err == nil) - if err != nil { - return "", "", err - } - - if serverUri == "" { - serverUri = reg.ServerUri - } - - return serverUri, reg.Token, nil -} - -func (r *relayInstanceManager) getAcceptFilePath() string { - return path.Join(os.TempDir(), fmt.Sprintf("axon-accept-file.%s.%s.%v.json", r.integrationInfo.Integration, r.integrationInfo.Alias, os.Getpid())) -} - -// reflectorRenderStep rewrites each private rule's origin to point back at the -// reflector, which is what lets the agent inject headers and retarget hosts on -// traffic the broker would otherwise send straight upstream. The encoded proxy -// URI carries a path segment identifying the original route. -func (r *relayInstanceManager) reflectorRenderStep(renderContext acceptfile.RenderContext) error { - // These are reflector-only features, so a rule using one without the - // reflector would silently not get it. - if !r.config.HttpRelayReflectorMode.ReflectsTraffic() { - for _, route := range renderContext.AcceptFile.PrivateRules() { - if len(route.Headers()) > 0 { - panic("ENABLE_RELAY_REFLECTOR must be set to 'all' or 'traffic' to use custom headers in accept files") - } - if strings.Contains(route.Origin(), "*") { - panic("ENABLE_RELAY_REFLECTOR must be set to 'all' or 'traffic' to use a wildcard origin in accept files") - } - } - return nil - } - - if r.reflector == nil { - return nil - } - - for _, route := range renderContext.AcceptFile.PrivateRules() { - // ProxyURI cannot report failure, and Origin() has already expanded the - // environment, so an expanded value cannot skip these checks. - _, wildcard, err := parseOrigin(route.Origin()) - if err != nil { - return fmt.Errorf("accept file rule has an invalid origin: %w", err) - } - if wildcard != nil && r.config.HttpDisableTLS { - return fmt.Errorf("%w: %s", ErrWildcardOriginRequiresTLSVerification, route.Origin()) - } - routeUri := r.reflector.ProxyURI( - route.Origin(), - WithHeadersResolver(route.Headers()), - ) - route.SetOrigin(routeUri) - } - return nil -} - -func (r *relayInstanceManager) Start() error { - - if !r.running.CompareAndSwap(false, true) { - return fmt.Errorf("already started") - } - - r.generation.Add(1) - - executable := defaultSnykBroker - - if directPath := os.Getenv("SNYK_BROKER_PATH"); directPath != "" { - executable = directPath - } - - af, err := r.integrationInfo.ToAcceptFile(r.config, r.logger) - if err != nil { - r.logger.Error("Error creating accept file", zap.Error(err)) - return fmt.Errorf("error creating accept file: %w", err) - } - - rendered, err := af.Render(r.logger, r.reflectorRenderStep) - - if err != nil { - r.logger.Error("Error rendering accept file", zap.Error(err)) - return fmt.Errorf("error rendering accept file: %w", err) - } - - tmpAcceptFile := r.getAcceptFilePath() - err = os.WriteFile(tmpAcceptFile, rendered, 0644) - - if err != nil { - fmt.Println("Error writing accept file", err) - panic(err) - } - - gen := r.generation.Load() - done := make(chan struct{}) - result := &startResult{} - - // Auto-register: poll for token changes and request restart if changed. - if r.config.AutoRegisterFrequency != 0 { - go func() { - for { - select { - case <-time.After(r.config.AutoRegisterFrequency): - info, err := r.refreshTokenInfo() - if err != nil { - r.logger.Error("Unable to auto register", zap.Error(err)) - continue - } - if info.HasChanged { - r.requestRestart("token_changed", gen) - } - case <-done: - return - } - } - }() - } - - // WebSocket tunnel death: request restart when the primus tunnel closes. - if r.reflector != nil && r.config.HttpRelayReflectorMode.ReflectsRegistration() { - r.reflector.SetOnWSTunnelClose(func() { - if os.Getenv("BROKER_RESTART_ON_WEBSOCKET_CLOSE") == "true" { - r.requestRestart("ws_tunnel_death", gen) - } - }) - } - - go func() { - - defer close(done) - - // On any non-clean exit, request a restart so the watchdog - // picks it up. Only skip for clean shutdown (!running) or - // intentional skip (no token / dry run). - requestRestartOnExit := false - defer func() { - if requestRestartOnExit && r.running.Load() { - r.requestRestart("broker_exit", gen) - } - }() - - var info *tokenInfo - var errx error - - // to allow the agent to start up even if registration isn't available - // we poll for the URI and Token. Once we get this we can then - // start the broker which will generate health and liveness data - // for the backend. - for { - if !r.running.Load() { - return - } - // Check if we've been superseded by a restart (new generation). - // Without this check, after Restart() calls Start() and sets - // running=true, old goroutines would continue making registration - // calls alongside new ones, causing duplicate API calls. - if r.generation.Load() != gen { - return - } - info, errx = r.getUrlAndToken() - - if errx == errSkipBroker { - return - } - - if errx == ErrUnauthorized { - r.logger.Error("Received 401 Unauthorized from Cortex API, check CORTEX_API_TOKEN is valid.", zap.Error(errx)) - break - } - - if errx == nil { - break - } - - r.logger.Error("Error starting broker, will retry", zap.Error(errx)) - time.Sleep(r.config.FailWaitTime * 5) - } - - if errx != nil { - result.set(errx) - requestRestartOnExit = true - return - } - - args := []string{} - if a := os.Getenv("SNYK_BROKER_ARGS"); a != "" { - args = strings.Split(a, " ") - } - - r.logger.Debug("Starting broker", - zap.String("executable", executable), - zap.Strings("args", args), - zap.String("tokenHash", common.TokenHash(info.Token)), - zap.String("uri", info.ServerUri), - zap.String("acceptFile", tmpAcceptFile), - ) - - brokerEnv := map[string]string{ - "ACCEPT": tmpAcceptFile, - "BROKER_SERVER_URL": info.ServerUri, - "BROKER_TOKEN": info.Token, - "PORT": fmt.Sprintf("%d", r.getSnykBrokerPort()), - } - - // pick up any env variables that are prefixed with SNYK_BROKER_ - // and add them to the environment - for _, e := range os.Environ() { - prefix := "SNYKBROKER_" - if strings.HasPrefix(e, prefix) { - parts := strings.SplitN(e, "=", 2) - if len(parts) != 2 { - continue - } - key := strings.TrimPrefix(parts[0], prefix) - value := parts[1] - brokerEnv[key] = value - r.logger.Debug("Adding SNYKBROKER_ environment variable", zap.String("key", key), zap.String("value", value)) - } - } - - r.setHttpProxyEnvVars(brokerEnv) - brokerEnv["NODE_OPTIONS"] = withOpenSSLCA(brokerEnv["NODE_OPTIONS"], os.Getenv("NODE_OPTIONS")) - - validationConfig := r.integrationInfo.GetValidationConfig() - r.applyClientValidationConfig(validationConfig, brokerEnv) - - if r.config.VerboseOutput { - brokerEnv["LOG_LEVEL"] = "debug" - } - - supervisor := NewSupervisor( - executable, - args, - brokerEnv, - r.config.FailWaitTime, - ) - // Only panic on max retries during the very first start. - // On subsequent restarts, return the error so the recovery - // loop can retry. - supervisor.panicOnMaxRetries = r.startCount.Load() == 0 - r.startCount.Add(1) - requestRestartOnExit = true - r.supervisorMu.Lock() - r.supervisor = supervisor - r.supervisorMu.Unlock() - startErr := supervisor.Start(5, 10*time.Second) - result.set(startErr) - r.emitOperationCounter("broker_start", startErr == nil) - if startErr != nil { - r.logger.Warn("Supervisor has exited upon startup", zap.Error(startErr)) - return - } - err := supervisor.Wait() - result.set(err) - r.emitOperationCounter("broker_exit", err == nil) - if err == nil { - r.logger.Info("Supervisor has exited") - } else { - r.logger.Warn("Supervisor has exited", zap.Error(err)) - } - }() - - select { - case <-done: - case <-time.After(r.config.FailWaitTime): - } - return result.get() -} - -// startResult is the outcome Start's goroutine reports: it may still be -// writing it when Start stops waiting and reads it. -type startResult struct { - mu sync.Mutex - err error -} - -func (s *startResult) set(err error) { - s.mu.Lock() - defer s.mu.Unlock() - s.err = err -} - -func (s *startResult) get() error { - s.mu.Lock() - defer s.mu.Unlock() - return s.err -} - -// currentSupervisor returns the running broker's supervisor, or nil. -func (r *relayInstanceManager) currentSupervisor() *Supervisor { - r.supervisorMu.Lock() - defer r.supervisorMu.Unlock() - return r.supervisor -} - -func (r *relayInstanceManager) setHttpProxyEnvVars(brokerEnv map[string]string) { - - // This is mostly for testing so we can validate no traffic goes out from the broker - // directly - if proxyStrictMode := os.Getenv("PROXY_STRICT_MODE"); proxyStrictMode == "true" { - brokerEnv["HTTP_PROXY"] = "http://not-a-real-proxy:1234" - brokerEnv["HTTPS_PROXY"] = "http://not-a-real-proxy:1234" - brokerEnv["NO_PROXY"] = "localhost,127.0.0.1" - r.logger.Warn("PROXY_STRICT_MODE is enabled, setting HTTP_PROXY and HTTPS_PROXY to a dummy value") - return - } - - httpProxy := os.Getenv("HTTP_PROXY") - if httpProxy != "" && brokerEnv["HTTP_PROXY"] == "" { - brokerEnv["HTTP_PROXY"] = httpProxy - } - httpsProxy := os.Getenv("HTTPS_PROXY") - if httpsProxy != "" && brokerEnv["HTTPS_PROXY"] == "" { - brokerEnv["HTTPS_PROXY"] = httpsProxy - } - - brokerEnv["NO_PROXY"] = util.EnsureLocalhostNoProxy(false) - - if certPath := r.getCertFilePath(r.config.HttpCaCertFilePath); certPath != "" { - if trustedPath := r.withoutDistrustedCAs(certPath); trustedPath != "" { - brokerEnv["NODE_EXTRA_CA_CERTS"] = trustedPath - } - } - - if r.config.HttpDisableTLS { - brokerEnv["NODE_TLS_REJECT_UNAUTHORIZED"] = "0" - } -} - -func (r *relayInstanceManager) getCertFilePath(certPath string) string { - - if certPath == "" { - return "" - } - - stat, err := os.Stat(certPath) - - if err != nil { - r.logger.Error("Error checking CA cert file", zap.String("path", certPath), zap.Error(err)) - return "" - } - - // if it's a directory, pick the first .pem file in the directory - if stat.IsDir() { - files, err := os.ReadDir(certPath) - if err != nil { - r.logger.Error("Error reading CA cert directory", zap.String("path", certPath), zap.Error(err)) - return "" - } - for _, file := range files { - if strings.HasSuffix(file.Name(), ".pem") { - certPath = path.Join(certPath, file.Name()) - break - } - } - } - - return certPath -} - -// withoutDistrustedCAs returns a path to the CA certs at certPath with any -// distrusted CA removed. The broker's Node runtime has no blocklist of its own, -// so a customer bundle that still carries one of these CAs would make the -// broker trust certificates that anyone can forge. When nothing is removed the -// original path is returned unchanged. On any error it returns "", so the -// broker gets no extra CAs rather than the distrusted ones. -func (r *relayInstanceManager) withoutDistrustedCAs(certPath string) string { - filtered, removed, err := util.ReadCACertPEM(certPath) - if err != nil { - r.logger.Error("Error reading CA cert file, passing no extra CAs to the broker", zap.String("path", certPath), zap.Error(err)) - return "" - } - if len(removed) == 0 { - return certPath - } - - if r.filteredCAPath != "" { - os.Remove(r.filteredCAPath) - r.filteredCAPath = "" - } - f, err := os.CreateTemp("", "axon-ca-certs-*.pem") - if err != nil { - r.logger.Error("Error creating filtered CA cert file, passing no extra CAs to the broker", zap.Error(err)) - return "" - } - _, err = f.Write(filtered) - if closeErr := f.Close(); err == nil { - err = closeErr - } - if err != nil { - os.Remove(f.Name()) - r.logger.Error("Error writing filtered CA cert file, passing no extra CAs to the broker", - zap.String("path", f.Name()), zap.Error(err)) - return "" - } - r.filteredCAPath = f.Name() - - r.logger.Warn("CA_CERT_PATH contains distrusted CA certificates; they are not passed to the broker. Remove them from the bundle.", - zap.String("path", certPath), zap.Strings("removed", removed)) - return f.Name() -} - -// withOpenSSLCA makes the broker's Node runtime use the OpenSSL (Debian) CA -// store, which has the distrusted CAs removed. Node's bundled store still -// trusts emSign ECC Root CA - G3, so the image's NODE_OPTIONS must not be lost -// when a customer overrides it. An explicit --use-bundled-ca is kept, because -// Node refuses to start with both flags. -func withOpenSSLCA(brokerValue, agentValue string) string { - opts := brokerValue - if opts == "" { - opts = agentValue - } - if strings.Contains(opts, "--use-openssl-ca") || strings.Contains(opts, "--use-bundled-ca") { - return opts - } - return strings.TrimSpace(opts + " --use-openssl-ca") -} - -func (r *relayInstanceManager) applyClientValidationConfig(validationConfig *common.ValidationConfig, brokerEnv map[string]string) { - if validationConfig != nil { - brokerEnv["BROKER_CLIENT_VALIDATION_URL"] = validationConfig.URL - if validationConfig.Method != "" { - brokerEnv["BROKER_CLIENT_VALIDATION_METHOD"] = validationConfig.Method - } - switch validationConfig.Auth.Type { - case "header": - brokerEnv["BROKER_CLIENT_VALIDATION_AUTHORIZATION_HEADER"] = validationConfig.Auth.Value - case "basic": - brokerEnv["BROKER_CLIENT_VALIDATION_BASIC_AUTH"] = validationConfig.Auth.Value - } - } -} - -func (r *relayInstanceManager) Close() error { - - if r.running.CompareAndSwap(true, false) { - r.supervisorMu.Lock() - s := r.supervisor - r.supervisor = nil - r.supervisorMu.Unlock() - if s != nil { - return s.Close() - } - } - acceptfilePath := r.getAcceptFilePath() - if _, err := os.Stat(acceptfilePath); !os.IsNotExist(err) { - os.Remove(acceptfilePath) - } - return nil -} diff --git a/agent/server/snykbroker/relay_instance_manager_test.go b/agent/server/snykbroker/relay_instance_manager_test.go deleted file mode 100644 index c2ee9eee..00000000 --- a/agent/server/snykbroker/relay_instance_manager_test.go +++ /dev/null @@ -1,703 +0,0 @@ -package snykbroker - -import ( - "context" - "fmt" - "net" - "net/http" - "net/http/httptest" - "net/http/httputil" - "net/url" - "os" - "path/filepath" - "testing" - "time" - - "github.com/cortexapps/axon/common" - "github.com/cortexapps/axon/config" - cortex_http "github.com/cortexapps/axon/server/http" - "github.com/cortexapps/axon/util" - "github.com/gorilla/mux" - "github.com/prometheus/client_golang/prometheus" - "github.com/stretchr/testify/require" - "go.uber.org/fx/fxtest" - "go.uber.org/mock/gomock" - "go.uber.org/zap" -) - -var defaultIntegrationInfo = common.IntegrationInfo{ - Integration: common.IntegrationGithub, -} - -func TestManagerSuccess(t *testing.T) { - controller := gomock.NewController(t) - defer controller.Finish() - - mgr := createTestRelayInstanceManager(t, controller, nil, false, defaultIntegrationInfo) - - err := mgr.Close() - require.NoError(t, err) - -} - -func TestManagerSuccessWithReflector(t *testing.T) { - controller := gomock.NewController(t) - defer controller.Finish() - - mgr := createTestRelayInstanceManager(t, controller, nil, true, defaultIntegrationInfo) - - // call the reflector uri - uri := mgr.reflector.ProxyURI(mgr.serverUri) - - req, err := http.NewRequest(http.MethodGet, uri+"/foo/bar", nil) - require.NoError(t, err) - resp, err := http.DefaultClient.Do(req) - require.NoError(t, err) - defer resp.Body.Close() - require.Equal(t, http.StatusOK, resp.StatusCode) - - err = mgr.Close() - require.NoError(t, err) - - require.Equal(t, 1, len(mgr.requestUrls), "Expected one request to the reflector URI") - require.Equal(t, "/foo/bar", mgr.requestUrls[0].Path, "Expected request to the reflector URI to have the correct path") - -} - -func TestManagerSuccessWithReflectorHeadersAndProxy(t *testing.T) { - - var mgr *wrappedRelayInstanceManager - controller := gomock.NewController(t) - defer controller.Finish() - - os.Setenv("PLUGIN_DIRS", "./acceptfile") - - // This is janky but we have a circular dep where we need to know the - // target server URI before we create the file, but we need to create the file - // before calling createTestRelayInstanceManager. So as a hack we create a second - // server that just forwards requests to the test server URI, once we know it. - knownTestServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // forward to the the test server - url, err := url.Parse(mgr.serverUri) - require.NoError(t, err, "Failed to parse test server URL") - proxy := httputil.NewSingleHostReverseProxy(url) - proxy.ServeHTTP(w, r) - })) - - t.Cleanup(knownTestServer.Close) - - content := fmt.Sprintf(` - { - "private": [ - { - "method": "GET", - "origin": "%s", - "path": "/foo/bar", - "headers": { - "x-plugin-value": "${plugin:plugin.sh}", - "x-other-header": "other-value" - } - } - ] - } - `, knownTestServer.URL) - - tmpFile := t.TempDir() + "/github.json" - err := os.WriteFile(tmpFile, []byte(content), 0644) - require.NoError(t, err, "Failed to write test accept file") - - ii := common.IntegrationInfo{ - Integration: common.IntegrationGithub, - AcceptFilePath: tmpFile, - } - - mgr = createTestRelayInstanceManager(t, controller, nil, true, ii) - - t.Cleanup(func() { - os.Remove(tmpFile) - os.Unsetenv("PLUGIN_DIRS") - }) - - // call the reflector uri - uri, err := mgr.reflector.getUriForTarget(knownTestServer.URL) - require.NoError(t, err, "Failed to get URI for target") - - req, err := http.NewRequest(http.MethodGet, uri+"/foo/bar", nil) - require.NoError(t, err) - resp, err := http.DefaultClient.Do(req) - require.NoError(t, err) - defer resp.Body.Close() - require.Equal(t, http.StatusOK, resp.StatusCode) - - err = mgr.Close() - require.NoError(t, err) - - require.Equal(t, 1, len(mgr.requests), "Expected one request to the reflector URI") - require.Equal(t, "/foo/bar", mgr.requests[0].URL.Path, "Expected request to the reflector URI to have the correct path") - require.Equal(t, "HOME="+os.Getenv("HOME"), mgr.requests[0].Header.Get("x-plugin-value"), "Expected request to the reflector URI to have the correct plugin header value") - require.Equal(t, "other-value", mgr.requests[0].Header.Get("x-other-header"), "Expected request to the reflector URI to have the correct header value") - -} - -func TestManagerUnauthorized(t *testing.T) { - controller := gomock.NewController(t) - defer controller.Finish() - - mgr := createTestRelayInstanceManager(t, controller, ErrUnauthorized, false, defaultIntegrationInfo) - - err := mgr.Start() - require.Error(t, err, ErrUnauthorized) - -} - -func TestApplyValidationConfig(t *testing.T) { - - validationConfig := &common.ValidationConfig{ - URL: "https://api.github.com/user", - Method: "POST", - Auth: common.Auth{ - Type: "header", - Value: "bearer the-token", - }, - } - - envVars := map[string]string{} - - mgr := &relayInstanceManager{} - - mgr.applyClientValidationConfig(validationConfig, envVars) - require.Equal(t, "https://api.github.com/user", envVars["BROKER_CLIENT_VALIDATION_URL"]) - require.Equal(t, "POST", envVars["BROKER_CLIENT_VALIDATION_METHOD"]) - require.Equal(t, "bearer the-token", envVars["BROKER_CLIENT_VALIDATION_AUTHORIZATION_HEADER"]) - -} - -func TestLoadCertsDir(t *testing.T) { - mgr := &relayInstanceManager{} - - path := mgr.getCertFilePath("../../test/certs") - require.Equal(t, "../../test/certs/selfsigned-1.pem", path) -} - -func TestLoadCertsFile(t *testing.T) { - mgr := &relayInstanceManager{} - - path := mgr.getCertFilePath("../../test/certs/selfsigned-2.pem") - require.Equal(t, "../../test/certs/selfsigned-2.pem", path) -} - -func TestHttpProxy(t *testing.T) { - oldEnv := util.SaveEnv(false) - defer util.RestoreEnv(oldEnv) - os.Setenv("HTTP_PROXY", "http://proxy.example.com:8080") - os.Setenv("HTTPS_PROXY", "http://proxy.example.com:8080") - os.Setenv("NO_PROXY", "localhost") - - cfg := config.AgentConfig{ - HttpCaCertFilePath: "../../test/certs/selfsigned-1.pem", - } - - mgr := &relayInstanceManager{ - config: cfg, - } - env := map[string]string{} - mgr.setHttpProxyEnvVars(env) - - require.Equal(t, "http://proxy.example.com:8080", env["HTTP_PROXY"]) - require.Equal(t, "http://proxy.example.com:8080", env["HTTPS_PROXY"]) - require.Equal(t, "localhost,127.0.0.1", env["NO_PROXY"]) - require.Equal(t, cfg.HttpCaCertFilePath, env["NODE_EXTRA_CA_CERTS"]) - -} - -func TestHttpProxyDropsDistrustedCAs(t *testing.T) { - trusted, err := os.ReadFile("../../test/certs/selfsigned-1.pem") - require.NoError(t, err) - distrusted, err := os.ReadFile("../../test/certs/distrusted/emsign-ecc-root-ca-g3.pem") - require.NoError(t, err) - bundlePath := filepath.Join(t.TempDir(), "bundle.pem") - require.NoError(t, os.WriteFile(bundlePath, append(distrusted, trusted...), 0o600)) - - mgr := &relayInstanceManager{ - config: config.AgentConfig{HttpCaCertFilePath: bundlePath}, - integrationInfo: common.IntegrationInfo{ - Integration: common.IntegrationGithub, - Alias: "distrusted-ca-test", - }, - logger: zap.NewNop(), - } - env := map[string]string{} - mgr.setHttpProxyEnvVars(env) - - passed := env["NODE_EXTRA_CA_CERTS"] - require.NotEqual(t, bundlePath, passed) - t.Cleanup(func() { os.Remove(passed) }) - got, err := os.ReadFile(passed) - require.NoError(t, err) - require.Equal(t, string(trusted), string(got)) -} - -func distrustedBundle(t *testing.T) string { - t.Helper() - trusted, err := os.ReadFile("../../test/certs/selfsigned-1.pem") - require.NoError(t, err) - distrusted, err := os.ReadFile("../../test/certs/distrusted/emsign-ecc-root-ca-g3.pem") - require.NoError(t, err) - bundlePath := filepath.Join(t.TempDir(), "bundle.pem") - require.NoError(t, os.WriteFile(bundlePath, append(distrusted, trusted...), 0o600)) - return bundlePath -} - -func TestHttpProxyReplacesPreviousFilteredCAFile(t *testing.T) { - mgr := &relayInstanceManager{ - config: config.AgentConfig{HttpCaCertFilePath: distrustedBundle(t)}, - logger: zap.NewNop(), - } - - first := map[string]string{} - mgr.setHttpProxyEnvVars(first) - second := map[string]string{} - mgr.setHttpProxyEnvVars(second) - t.Cleanup(func() { os.Remove(second["NODE_EXTRA_CA_CERTS"]) }) - - require.NotEqual(t, first["NODE_EXTRA_CA_CERTS"], second["NODE_EXTRA_CA_CERTS"]) - require.NoFileExists(t, first["NODE_EXTRA_CA_CERTS"]) - require.FileExists(t, second["NODE_EXTRA_CA_CERTS"]) -} - -// The broker must never fall back to the unfiltered bundle. -func TestHttpProxyPassesNoCAsWhenFilteredCopyCannotBeWritten(t *testing.T) { - t.Setenv("TMPDIR", filepath.Join(t.TempDir(), "missing")) - mgr := &relayInstanceManager{ - config: config.AgentConfig{HttpCaCertFilePath: distrustedBundle(t)}, - logger: zap.NewNop(), - } - env := map[string]string{} - mgr.setHttpProxyEnvVars(env) - - require.NotContains(t, env, "NODE_EXTRA_CA_CERTS") -} - -func TestWithOpenSSLCA(t *testing.T) { - cases := []struct { - name, broker, agent, want string - }{ - {"unset", "", "", "--use-openssl-ca"}, - {"agent value kept", "", "--max-old-space-size=512", "--max-old-space-size=512 --use-openssl-ca"}, - {"broker value wins", "--trace-warnings", "--max-old-space-size=512", "--trace-warnings --use-openssl-ca"}, - {"already set", "", "--use-openssl-ca", "--use-openssl-ca"}, - {"explicit bundled store kept", "--use-bundled-ca", "", "--use-bundled-ca"}, - } - for _, c := range cases { - t.Run(c.name, func(t *testing.T) { - require.Equal(t, c.want, withOpenSSLCA(c.broker, c.agent)) - }) - } -} - -// POST request successfully restarts supervisor and returns 200 OK -func TestRelayRestartServer(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - mgr := createTestRelayInstanceManager(t, ctrl, nil, false, defaultIntegrationInfo) - - w := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/__axon/broker/restart", nil) - httpHandler := (mgr.RelayInstanceManager).(cortex_http.RegisterableHandler) - - mux := mux.NewRouter() - httpHandler.RegisterRoutes(mux) - mux.ServeHTTP(w, req) - - require.Equal(t, http.StatusOK, w.Code) - require.Equal(t, 2, int(mgr.Instance().startCount.Load())) - -} - -func TestRelayReRegisterServer(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - mgr := createTestRelayInstanceManager(t, ctrl, nil, false, defaultIntegrationInfo) - - w := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/__axon/broker/reregister", nil) - httpHandler := (mgr.RelayInstanceManager).(cortex_http.RegisterableHandler) - - mux := mux.NewRouter() - httpHandler.RegisterRoutes(mux) - mux.ServeHTTP(w, req) - - require.Equal(t, http.StatusOK, w.Code) - require.Equal(t, 1, int(mgr.Instance().startCount.Load())) - -} - -// The reregister endpoint runs on an arbitrary HTTP handler goroutine while -// the broker is up and the reflector is serving traffic. It must only report -// whether registration changed, and hand any resulting restart to the single -// restart consumer, so it never registers reflector entries itself. -func TestRelayReRegisterDoesNotTouchReflector(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - mgr := createTestRelayInstanceManager(t, ctrl, nil, true, defaultIntegrationInfo) - - before := len(*mgr.reflector.targets.Load()) - require.NotZero(t, before, "start should have registered entries") - - w := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/__axon/broker/reregister", nil) - httpHandler := (mgr.RelayInstanceManager).(cortex_http.RegisterableHandler) - - mux := mux.NewRouter() - httpHandler.RegisterRoutes(mux) - mux.ServeHTTP(w, req) - - require.Equal(t, http.StatusOK, w.Code) - require.Len(t, *mgr.reflector.targets.Load(), before) -} - -func TestSystemCheck(t *testing.T) { - - jsonPayload := ` - [ - { - "brokerClientValidationUrl": "https://api.github.com/user", - "brokerClientValidationMethod": "GET", - "brokerClientValidationTimeoutMs": 5000, - "brokerClientValidationUrlStatusCode": 401, - "ok": false, - "error": "Failed due to invalid credentials", - "maskedCredentials": "ghp***sIX" - }, - { - "brokerClientValidationUrl": "https://api.github.com/user", - "brokerClientValidationMethod": "GET", - "brokerClientValidationTimeoutMs": 5000, - "brokerClientValidationUrlStatusCode": 200, - "ok": true, - "maskedCredentials": "ghp***ICu" - } - ] - ` - - // Create a mock HTTP server - mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Method == http.MethodGet && r.URL.Path == "/systemcheck" { - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(jsonPayload)) - return - } - http.NotFound(w, r) - })) - defer mockServer.Close() - - mgr := &relayInstanceManager{ - config: config.AgentConfig{ - SnykBrokerPort: mockServer.Listener.Addr().(*net.TCPAddr).Port, - }, - } - - w := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/__axon/broker/systemcheck", nil) - - mux := mux.NewRouter() - mgr.RegisterRoutes(mux) - mux.ServeHTTP(w, req) - - // Verify the response - require.Equal(t, http.StatusOK, w.Code) - require.Equal(t, jsonPayload, w.Body.String()) -} - -// A broker that never answers /systemcheck must not hold the agent's HTTP -// handler open indefinitely. -func TestSystemCheck_UpstreamTimeout(t *testing.T) { - previous := systemCheckTimeout - systemCheckTimeout = 100 * time.Millisecond - t.Cleanup(func() { systemCheckTimeout = previous }) - - release := make(chan struct{}) - mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - <-release - })) - defer mockServer.Close() - defer close(release) - - mgr := &relayInstanceManager{ - config: config.AgentConfig{SnykBrokerPort: mockServer.Listener.Addr().(*net.TCPAddr).Port}, - logger: zap.NewNop(), - } - w := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/__axon/broker/systemcheck", nil) - router := mux.NewRouter() - mgr.RegisterRoutes(router) - - start := time.Now() - router.ServeHTTP(w, req) - - require.Equal(t, http.StatusInternalServerError, w.Code) - require.Equal(t, "Unable to get system check", w.Body.String()) - require.Less(t, time.Since(start), 2*time.Second) -} - -// A broker response that dies mid-body is reported as a single 500, not a -// 200 header followed by a truncated body. -func TestSystemCheck_ReadErrorIsSingle500(t *testing.T) { - mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Length", "100") - w.WriteHeader(http.StatusOK) - w.Write([]byte("short")) - })) - defer mockServer.Close() - - mgr := &relayInstanceManager{ - config: config.AgentConfig{SnykBrokerPort: mockServer.Listener.Addr().(*net.TCPAddr).Port}, - logger: zap.NewNop(), - } - w := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodGet, "/__axon/broker/systemcheck", nil) - router := mux.NewRouter() - mgr.RegisterRoutes(router) - router.ServeHTTP(w, req) - - require.Equal(t, http.StatusInternalServerError, w.Code) -} - -type wrappedRelayInstanceManager struct { - RelayInstanceManager - mockRegistration *MockRegistration - reflector *RegistrationReflector - requestUrls []url.URL - requests []*http.Request - serverUri string -} - -func (w *wrappedRelayInstanceManager) Instance() *relayInstanceManager { - return w.RelayInstanceManager.(*relayInstanceManager) -} - -func createTestRelayInstanceManager(t *testing.T, controller *gomock.Controller, expectedError error, useReflector bool, ii common.IntegrationInfo) *wrappedRelayInstanceManager { - envVars := map[string]string{ - "ACCEPTFILE_DIR": "./accept_files", - "GITHUB_TOKEN": "the-token", - "GITHUB_API": "https://api.github.com", - "GITHUB_GRAPHQL": "https://api.github.com/graphql", - "SNYK_BROKER_PATH": "sleep", - "SNYK_BROKER_ARGS": "60", - } - - common.ApplyEnv(envVars) - - lifecycle := fxtest.NewLifecycle(t) - cfg := config.NewAgentEnvConfig() - cfg.FailWaitTime = time.Millisecond * 100 - cfg.HttpRelayReflectorMode = config.RelayReflectorDisabled - if useReflector { - cfg.HttpRelayReflectorMode = config.RelayReflectorAllTraffic - } - loggerConfig := zap.NewDevelopmentConfig() - loggerConfig.Level = zap.NewAtomicLevelAt(zap.DebugLevel) - logger := zap.Must(loggerConfig.Build()) - mockServer := cortex_http.NewMockServer(controller) - mockServer.EXPECT().RegisterHandler(gomock.Any()).MinTimes(1) - - mockRegistration := NewMockRegistration(controller) - - registry := prometheus.NewRegistry() - - var reflector *RegistrationReflector - if useReflector { - params := RegistrationReflectorParams{ - Lifecycle: lifecycle, - Logger: logger.Named("reflector"), - Config: cfg, - } - reflector = NewRegistrationReflector( - params, - ) - } - - params := RelayInstanceManagerParams{ - Lifecycle: lifecycle, - Config: cfg, - Logger: logger, - IntegrationInfo: ii, - HttpServer: mockServer, - Registration: mockRegistration, - Registry: registry, - Reflector: reflector, - } - - mgr := &wrappedRelayInstanceManager{ - RelayInstanceManager: NewRelayInstanceManager( - params, - ), - mockRegistration: mockRegistration, - reflector: reflector, - } - - testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - mgr.requestUrls = append(mgr.requestUrls, *r.URL) - mgr.requests = append(mgr.requests, r) - })) - - t.Cleanup(testServer.Close) - - response := &RegistrationInfoResponse{ - ServerUri: testServer.URL, - Token: "abcd1234", - } - mgr.serverUri = testServer.URL - - if expectedError != nil { - mockRegistration.EXPECT().Register(gomock.Any(), gomock.Eq(common.IntegrationGithub), gomock.Eq("")).MinTimes(1).Return(nil, expectedError) - } else { - mockRegistration.EXPECT().Register(gomock.Any(), gomock.Eq(common.IntegrationGithub), gomock.Eq("")).MinTimes(1).Return(response, nil) - } - - os.Setenv("TEST_SERVER_URL", testServer.URL) - - lifecycle.Start(context.Background()) - - return mgr -} - -func TestBrokerSelfHealingRestart(t *testing.T) { - controller := gomock.NewController(t) - defer controller.Finish() - - mgr := createTestRelayInstanceManager(t, controller, nil, false, defaultIntegrationInfo) - instance := mgr.Instance() - - // Wait for the broker to be running - require.Eventually(t, func() bool { - s := instance.currentSupervisor() - return s != nil && s.Pid() > 0 - }, 5*time.Second, 10*time.Millisecond, "Broker should be running") - - initialStartCount := instance.startCount.Load() - initialGeneration := instance.generation.Load() - - // Kill the broker process to simulate unexpected death. - // The supervisor will exhaust retries and the restart consumer - // will process the broker_exit restart request. - pid := instance.currentSupervisor().Pid() - if pid > 0 { - process, err := os.FindProcess(pid) - require.NoError(t, err) - process.Kill() - } - - // Verify the restart count and generation both increase, - // indicating the restart consumer processed the request. - require.Eventually(t, func() bool { - return instance.startCount.Load() > initialStartCount - }, 30*time.Second, 100*time.Millisecond, "Broker should have been restarted after unexpected exit") - - require.Greater(t, instance.generation.Load(), initialGeneration, - "Generation should have incremented after restart") - - err := mgr.Close() - require.NoError(t, err) -} - -func TestIdleTimeoutDetectsIdleReflector(t *testing.T) { - controller := gomock.NewController(t) - defer controller.Finish() - - mgr := createTestRelayInstanceManager(t, controller, nil, true, defaultIntegrationInfo) - - // No traffic has been relayed yet, so LastTrafficTime should still be its - // unset zero value, not a recent time (only RecordStartup runs at construction). - lastTraffic := mgr.reflector.LastTrafficTime() - require.True(t, lastTraffic.Before(time.Now().Add(-time.Hour))) - - // Simulate idle: no traffic recorded - // Check that time.Since(lastTraffic) grows - time.Sleep(50 * time.Millisecond) - idle := time.Since(mgr.reflector.LastTrafficTime()) - require.True(t, idle >= 50*time.Millisecond, "Should detect idle duration") - - // Record traffic and verify idle resets - mgr.reflector.RecordTraffic() - idle = time.Since(mgr.reflector.LastTrafficTime()) - require.True(t, idle < 10*time.Millisecond, "Idle should reset after RecordTraffic") - - err := mgr.Close() - require.NoError(t, err) -} - -// Only the newest client for a token gets relayed requests, so a healthy -// replica can go a long time without traffic. Frames from the broker server -// keep it out of the idle watchdog; a tunnel that has gone quiet does not. -func TestShouldRestartCountsTunnelActivity(t *testing.T) { - cfg := config.NewAgentEnvConfig() - cfg.HttpRelayReflectorMode = config.RelayReflectorAllTraffic - cfg.RelayIdleTimeout = time.Minute - - rr := NewRegistrationReflector(RegistrationReflectorParams{ - Logger: zap.NewNop(), - Config: cfg, - }) - r := &relayInstanceManager{config: cfg, reflector: rr} - - stale := time.Now().Add(-2 * time.Minute).UnixMilli() - rr.lastStartupTime.Store(stale) - rr.lastTrafficTime.Store(stale) - - restart, reason := r.shouldRestart() - require.True(t, restart, "no traffic, no startup and no tunnel frames within the window is idle") - require.Equal(t, "idle_timeout", reason) - - rr.RecordTunnelActivity() - restart, _ = r.shouldRestart() - require.False(t, restart, "a frame from the broker server shows the tunnel is alive") - - rr.lastTunnelTime.Store(stale) - restart, _ = r.shouldRestart() - require.True(t, restart, "a tunnel that has gone quiet is idle again") - - // "registration" routes the broker's tunnel through the reflector but no - // relayed requests, so tunnel frames are its only signal. - r.config.HttpRelayReflectorMode = config.RelayReflectorRegistrationOnly - restart, _ = r.shouldRestart() - require.True(t, restart, "registration mode watches the tunnel too") - rr.RecordTunnelActivity() - restart, _ = r.shouldRestart() - require.False(t, restart, "registration mode counts tunnel frames") - - // With the reflector off the agent sees neither, so it must not guess. - rr.lastTunnelTime.Store(stale) - r.config.HttpRelayReflectorMode = config.RelayReflectorDisabled - restart, _ = r.shouldRestart() - require.False(t, restart, "disabled mode has no signal and never restarts") -} - -// A broker with nothing to relay looks identical, idle-wise, to one whose -// tunnel died silently: shouldRestart() can only see "no activity recorded." -// A restart must reset the idle clock (LastStartupTime) so a healthy-but-idle -// broker isn't immediately re-suspected on the next watchdog tick, but it -// must not touch LastTrafficTime, which should keep meaning "the last time -// real traffic was relayed" rather than "the last restart." -func TestRestartResetsIdleClock(t *testing.T) { - controller := gomock.NewController(t) - defer controller.Finish() - - mgr := createTestRelayInstanceManager(t, controller, nil, true, defaultIntegrationInfo) - - time.Sleep(50 * time.Millisecond) - require.True(t, time.Since(mgr.reflector.LastStartupTime()) >= 50*time.Millisecond, - "Precondition: reflector should look idle before the restart") - trafficTimeBeforeRestart := mgr.reflector.LastTrafficTime() - - err := mgr.Restart() - require.NoError(t, err) - - require.True(t, time.Since(mgr.reflector.LastStartupTime()) < 10*time.Millisecond, - "Restart should reset the idle clock") - require.Equal(t, trafficTimeBeforeRestart, mgr.reflector.LastTrafficTime(), - "Restart must not touch LastTrafficTime") - - err = mgr.Close() - require.NoError(t, err) -} diff --git a/agent/server/snykbroker/supervisor.go b/agent/server/snykbroker/supervisor.go deleted file mode 100644 index b6caba88..00000000 --- a/agent/server/snykbroker/supervisor.go +++ /dev/null @@ -1,388 +0,0 @@ -package snykbroker - -import ( - "bufio" - _ "embed" - "errors" - "fmt" - "io" - "os" - "os/exec" - "os/signal" - "sync" - "sync/atomic" - "syscall" - "time" - - "go.uber.org/zap" -) - -type Supervisor struct { - sync.Mutex - output io.Writer - fastFailTime time.Duration - panicOnMaxRetries bool - executable string - args []string - env map[string]string - done chan struct{} - // firstStart closes once the first child process exists, so Start can - // promise a live Pid to its caller. - firstStart chan struct{} - firstStartOnce sync.Once - // outputMu serialises writes to output: a restart can start the next - // process's line pump before the previous one has drained, and the - // destination (a bytes.Buffer under test) is not concurrency-safe. - outputMu sync.Mutex - // stopFunc, pid and runCount are written by the supervising goroutine and - // read by whoever called Start, so they are synchronised. - stopFunc func() - pid atomic.Int32 - runCount atomic.Int32 - // lastRunNanos is the child process's own lifetime (exec to exit) for the - // most recent run. - lastRunNanos atomic.Int64 - lastError error -} - -func NewSupervisor( - executable string, - args []string, - env map[string]string, - fastFailTime time.Duration, -) *Supervisor { - return &Supervisor{ - output: os.Stdout, - executable: executable, - args: args, - env: env, - fastFailTime: fastFailTime * 2, - done: make(chan struct{}), - firstStart: make(chan struct{}), - stopFunc: func() {}, - } -} - -var errKilled = errors.New("killed") -var errMaxRetries = errors.New("max retries reached") - -func (b *Supervisor) Start(maxRetries int, window time.Duration) error { - - if b.runCount.Load() > 0 { - return errors.New("already started, cannot start again") - } - - if err := b.runExecutionLoop(maxRetries, window); err != nil { - return err - } - return b.err() -} - -// setStopFunc / stopper guard stopFunc, which the supervising goroutine -// replaces as processes come and go while callers may invoke Close at any time. -func (b *Supervisor) setStopFunc(fn func()) { - b.Lock() - defer b.Unlock() - b.stopFunc = fn -} - -func (b *Supervisor) stopper() func() { - b.Lock() - defer b.Unlock() - return b.stopFunc -} - -func (b *Supervisor) err() error { - b.Lock() - defer b.Unlock() - return b.lastError -} - -func (b *Supervisor) runExecutionLoop(maxRetries int, window time.Duration) error { - - tracker := newEventTracker() - - finish := func(err error) { - b.Lock() - defer b.Unlock() - b.lastError = err - if b.done != nil { - close(b.done) - } - } - - fastfail := make(chan struct{}) - // we run this off thread, looping to restart - // the process if it crashes, but exiting - // if too many happen in the restart window - b.runCount.Store(1) - go func() { - defer close(fastfail) - for maxRetries > 0 { - tracker.AddEvent() - err := b.runCommand() - // Use the child's own lifetime, not this loop's wall time. - // Tearing down the pipes and draining the scanners can dwarf - // fastFailTime on a loaded machine (or under -race), which would - // otherwise mask a genuinely instant failure. - runTime := time.Duration(b.lastRunNanos.Load()) - - if errors.Is(err, errKilled) { - finish(nil) - return - } - - if err != nil && b.runCount.Load() == 1 && runTime < b.fastFailTime { - finish(fmt.Errorf("run failed immediately: %v", err)) - return - } - - if err == nil { - fmt.Printf("Process exited with code 0\n") - } else { - fmt.Printf("Process exited with error: %v\n", err) - } - - if tracker.CountEventsWithinWindow(window) > maxRetries { - finish(errMaxRetries) - if b.panicOnMaxRetries { - panic("max retries reached: " + b.executable) - } - return - } - b.runCount.Add(1) - } - }() - - // Wait for the first process to actually exist before returning. Callers - // read Pid() straight after Start(), and fastFailTime is a "did it die on - // the spot" window, not a "process is up" signal — on a loaded machine the - // fork can easily outlast it, handing back a zero pid. - select { - case <-fastfail: - return b.err() - case <-b.firstStart: - } - - // Then the fast-fail observation window proper. - select { - case <-fastfail: - case <-time.After(b.fastFailTime): - } - return b.err() -} - -func (b *Supervisor) Wait() error { - done := b.done - if done == nil { - return b.lastError - } - <-done - return b.lastError -} - -//go:embed watchdog.sh -var watchdog string - -func (b *Supervisor) runWatchdog(pid int) func() { - // get this process pid - - // write the watchdog script to a file - watchdogPath := "/tmp/watchdog.sh" - err := os.WriteFile(watchdogPath, []byte(watchdog), 0755) - if err != nil { - fmt.Println("Error writing watchdog script", zap.Error(err)) - return func() {} - } - - // run the watchdog script - cmd := exec.Command(watchdogPath, fmt.Sprintf("%v", os.Getpid()), fmt.Sprintf("%d", pid)) - err = cmd.Start() - if err != nil { - fmt.Println("Error running watchdog script", zap.Error(err)) - return func() {} - } - return func() { - cmd.Process.Kill() - } -} - -// runCommand runs a single command and returns the result of the command after it exits, -// or errKilled if it was intentionally shut down. -func (b *Supervisor) runCommand() error { - - cmd := exec.Command(b.executable) - cmd.Args = append(cmd.Args, b.args...) - - cmd.Env = os.Environ() - for k, v := range b.env { - cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", k, v)) - } - - output := make(chan string) - - stdout, _ := cmd.StdoutPipe() - stderr, _ := cmd.StderrPipe() - wg := &sync.WaitGroup{} - - stopStdOut := b.scanLines(stdout, output, wg) - stopStdErr := b.scanLines(stderr, output, wg) - - go func() { - for line := range output { - b.writeLine(line) - } - }() - - // sigChan triggers shutdown - sigChan := make(chan os.Signal, 1) - signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM) - - running := make(chan struct{}) - - go func() { - <-sigChan - b.stopper()() - }() - - var killed atomic.Bool - // procMu orders a stop against the start: cmd.Start writes cmd.Process - // on this goroutine while a stop may arrive on any other, so the stop - // reads the process only through proc, under the lock, and a stop that - // lands before the process exists is honoured as soon as it does. - var procMu sync.Mutex - var proc *os.Process - kill := func(p *os.Process) { - if err := p.Kill(); err != nil { - fmt.Printf("Error killing process: %v\n", err) - } - } - - // our stopfunc allows anyone to close the process - // and wait for it to finish - b.setStopFunc(func() { - procMu.Lock() - killed.Store(true) - p := proc - procMu.Unlock() - - // if process is running trigger a kill - if p != nil { - kill(p) - } - - // wait for it to actually finish - <-running - }) - - procStart := time.Now() - procMu.Lock() - err := cmd.Start() - if err == nil { - proc = cmd.Process - if killed.Load() { - kill(proc) - } - } - procMu.Unlock() - - if err != nil { - b.lastRunNanos.Store(0) - return err - } - pid := cmd.Process.Pid - b.pid.Store(int32(pid)) - b.firstStartOnce.Do(func() { close(b.firstStart) }) - - // We want to make sure the broker is killed if the agent dies or is killed. This is - // mostly useful in the debugger but prevents port from being held open. - cancelWatchdog := b.runWatchdog(cmd.Process.Pid) - defer cancelWatchdog() - - // here we wait for it to start then fully finish - go func() { - cmd.Wait() - // Store before closing running: the run loop reads this the moment it - // unblocks. - b.lastRunNanos.Store(int64(time.Since(procStart))) - b.pid.Store(0) - b.setStopFunc(func() {}) - close(running) - }() - - // block until the process is done - <-running - stopStdOut() - stopStdErr() - wg.Wait() - - if killed.Load() { - err = errKilled - fmt.Printf("Process %v (pid=%v) killed\n", cmd.Path, pid) - } - - if err == nil && cmd.ProcessState.ExitCode() != 0 { - err = fmt.Errorf("command failed with exit code %d", cmd.ProcessState.ExitCode()) - } - return err -} - -func (b *Supervisor) writeLine(line string) { - b.outputMu.Lock() - defer b.outputMu.Unlock() - fmt.Fprintln(b.output, line) -} - -func (b *Supervisor) Pid() int { - return int(b.pid.Load()) -} - -func (b *Supervisor) Close() error { - b.stopper()() - return nil -} - -func (b *Supervisor) scanLines(reader io.Reader, output chan string, refCount *sync.WaitGroup) func() { - - // done is set by the returned stop closure on the caller's goroutine and - // read by the scanning goroutine, so it has to be atomic. - var done atomic.Bool - - refCount.Add(1) - - // increase buffer size from default of 60K to 1MB - buffer := make([]byte, 1024*1024) - go func() { - for !done.Load() { - scanner := bufio.NewScanner(reader) - scanner.Buffer(buffer, cap(buffer)-1) - for scanner.Scan() { - ln := scanner.Text() - output <- ln - if done.Load() { - return - } - } - err := scanner.Err() - - if err == nil { - return - } - - if err == io.EOF { - return - } - - output <- fmt.Sprintf("Warning (non-fatal), failed to read from scanner to pipe output: %v", err) - - // dump what we have in the buffer, first 16K, then continue - output <- string(buffer[0:16*1024]) + "...[END OF BUFFER]" - } - - }() - - return func() { - done.Store(true) - refCount.Done() - } -} diff --git a/agent/server/snykbroker/supervisor_test.go b/agent/server/snykbroker/supervisor_test.go deleted file mode 100644 index b79796fe..00000000 --- a/agent/server/snykbroker/supervisor_test.go +++ /dev/null @@ -1,109 +0,0 @@ -package snykbroker - -import ( - "regexp" - "testing" - "time" - - "github.com/stretchr/testify/require" -) - -func TestStart_SuccessExit(t *testing.T) { - - supervisor := NewSupervisor( - "bash", - []string{"-c", "echo \"$BROKER_TOKEN $BROKER_SERVER_URL\""}, - map[string]string{ - "BROKER_TOKEN": "test_token", - "BROKER_SERVER_URL": "http://example.com", - }, - time.Millisecond*10, - ) - output := syncBuffer{} - supervisor.output = &output - - err := supervisor.Start(1, 1) - require.NoError(t, err) -} - -func TestStart_Restart(t *testing.T) { - - supervisor := NewSupervisor( - "bash", - []string{"-c", "sleep 300"}, - map[string]string{ - "BROKER_TOKEN": "test_token", - "BROKER_SERVER_URL": "http://example.com", - }, - time.Millisecond*10, - ) - output := syncBuffer{} - supervisor.output = &output - - err := supervisor.Start(1, 1) - require.NoError(t, err) - require.NotEqual(t, 0, supervisor.Pid()) - err = supervisor.Close() - require.NoError(t, err) - require.Equal(t, 0, supervisor.Pid()) - - err = supervisor.Start(1, 1) - require.Error(t, err) - require.Contains(t, err.Error(), "already started") -} - -func TestStart_FastFail(t *testing.T) { - - // test that if the command fails quickly off the bat, we don't retry anymore - - // NewSupervisor doubles this, so 50ms gave the process 100ms to spawn, - // run and exit before it stopped counting as an immediate failure — which - // a loaded CI runner can exceed just forking bash, failing the test for - // reasons unrelated to what it checks. A process meant to run - // indefinitely that dies inside a second is still immediate by any - // reading, so the wider budget costs the assertion nothing. - supervisor := NewSupervisor( - "bash", - []string{"-c", "exit 1"}, - map[string]string{ - "BROKER_TOKEN": "test_token", - "BROKER_SERVER_URL": "http://example.com", - }, - time.Millisecond*500, - ) - output := syncBuffer{} - supervisor.output = &output - - err := supervisor.Start(2, 1) - require.Error(t, err) - require.Contains(t, err.Error(), "failed immediately") -} - -func TestStart_MaxRetries(t *testing.T) { - - // Test that the command will be re run unless it hits the max retries - // in the window - - supervisor := NewSupervisor( - "bash", - []string{"-c", "echo run;sleep .05; exit 1"}, - map[string]string{ - "BROKER_TOKEN": "test_token", - "BROKER_SERVER_URL": "http://example.com", - }, - time.Second, - ) - output := syncBuffer{} - supervisor.output = &output - supervisor.panicOnMaxRetries = false - supervisor.fastFailTime = 1 * time.Millisecond - - err := supervisor.Start(2, time.Second) - require.NoError(t, err) - err = supervisor.Wait() - require.Error(t, err) - require.Contains(t, err.Error(), "max retries") - println(output.contents()) - runRegEx := regexp.MustCompile("run") - require.GreaterOrEqual(t, len(runRegEx.FindAllString(output.contents(), -1)), 3) -} diff --git a/agent/server/snykbroker/token_logging_test.go b/agent/server/snykbroker/token_logging_test.go deleted file mode 100644 index dee38bef..00000000 --- a/agent/server/snykbroker/token_logging_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package snykbroker - -import ( - "strings" - "testing" - - "github.com/cortexapps/axon/common" - "github.com/prometheus/client_golang/prometheus" - "github.com/stretchr/testify/require" - "go.uber.org/mock/gomock" - "go.uber.org/zap" - "go.uber.org/zap/zapcore" - "go.uber.org/zap/zaptest/observer" -) - -// The broker token is the sole credential on the relay path, and the agent -// writes its logs into the customer's log sink. So no log line may carry the -// raw token. It is logged as the token hash on both the relay server and -// BROKER_SERVER log for the same token, which keeps the lines joinable. -func TestRefreshTokenInfo_LogsTokenHashNotRawToken(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - - const rawToken = "4f49654b-1111-2222-3333-9deef1d9f2f6" - - t.Setenv("BROKER_SERVER_URL", "") - t.Setenv("BROKER_TOKEN", "") - - mockRegistration := NewMockRegistration(ctrl) - mockRegistration.EXPECT().Register(gomock.Any(), gomock.Any(), gomock.Any()).Return( - &RegistrationInfoResponse{ - ServerUri: "https://relay.example.com", - Token: rawToken, - }, nil, - ) - - core, logs := observer.New(zapcore.DebugLevel) - - mgr := &relayInstanceManager{ - logger: zap.New(core), - registration: mockRegistration, - integrationInfo: defaultIntegrationInfo, - operationsCounter: prometheus.NewCounterVec( - prometheus.CounterOpts{Name: "broker_operations_test"}, - []string{"integration", "alias", "operation", "status"}, - ), - } - - info, err := mgr.refreshTokenInfo() - require.NoError(t, err) - require.True(t, info.HasChanged, "the first registration is a change") - - entries := logs.All() - require.NotEmpty(t, entries, "refreshTokenInfo should log the change") - - for _, entry := range entries { - require.NotContains(t, entry.Message, rawToken) - for key, value := range entry.ContextMap() { - s, ok := value.(string) - if !ok { - continue - } - require.NotContains(t, s, rawToken, "field %q leaks the raw token", key) - require.False(t, strings.Contains(rawToken, s) && s != "", - "field %q leaks part of the raw token", key) - } - } - - changed := logs.FilterMessage("Registration info has changed").All() - require.Len(t, changed, 1) - require.Equal(t, common.TokenHash(rawToken), changed[0].ContextMap()["tokenHash"]) -} diff --git a/agent/server/snykbroker/watchdog.sh b/agent/server/snykbroker/watchdog.sh deleted file mode 100644 index a76ba386..00000000 --- a/agent/server/snykbroker/watchdog.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/bin/sh - -# Usage: watchdog.sh -# This script monitors the first process and kills the second process if the first process exits. - -# Check if two arguments are provided -if [ "$#" -ne 2 ]; then - echo "Usage: $0 " - exit 1 -fi - -PID1=$1 -PID2=$2 - -# Function to check if a process is running -is_running() { - ps -p $1 > /dev/null 2>&1 -} - -# Monitor the first process -while is_running $PID1; do - - if ! is_running $PID2; then - echo "Process $PID2 is not running." - exit 0 - fi - sleep 1 -done - -# If the first process exits, kill the second process -if is_running $PID2; then - echo "Process $PID1 has exited. Killing process $PID2." - kill $PID2 -else - echo "Process $PID1 has exited. Process $PID2 is not running." -fi \ No newline at end of file diff --git a/agent/server/snykbroker/ws_proxy.go b/agent/server/snykbroker/ws_proxy.go deleted file mode 100644 index 6a0ef9ae..00000000 --- a/agent/server/snykbroker/ws_proxy.go +++ /dev/null @@ -1,333 +0,0 @@ -package snykbroker - -import ( - "context" - "crypto/tls" - "fmt" - "io" - "net" - "net/http" - "net/url" - "strings" - "sync/atomic" - "time" - - "github.com/cortexapps/axon/util" - "go.uber.org/zap" -) - -// WebSocketProxy handles proxying WebSocket connections through HTTP CONNECT proxies. -// It manages the TCP tunnel between client and target, respecting proxy settings -// and TLS configuration from the provided http.Transport. -type WebSocketProxy struct { - logger *zap.Logger - transport *http.Transport - - // Timeouts - DialTimeout time.Duration - HandshakeTimeout time.Duration - IdleTimeout time.Duration - - // Callbacks - OnTunnelEstablished func(target string) - OnTunnelClosed func(target string, duration time.Duration) - - // State tracking - use Int32 to properly track multiple concurrent tunnels - activeConnections atomic.Int32 -} - -// NewWebSocketProxy creates a WebSocket proxy that uses the given transport's -// proxy and TLS settings. -func NewWebSocketProxy(logger *zap.Logger, transport *http.Transport) *WebSocketProxy { - return &WebSocketProxy{ - logger: logger, - transport: transport, - DialTimeout: 30 * time.Second, - HandshakeTimeout: 30 * time.Second, - IdleTimeout: 5 * time.Minute, - } -} - -// IsConnected returns true if any WebSocket tunnel is currently active. -func (wp *WebSocketProxy) IsConnected() bool { - return wp.activeConnections.Load() > 0 -} - -// ActiveConnections returns the number of currently active WebSocket tunnels. -func (wp *WebSocketProxy) ActiveConnections() int32 { - return wp.activeConnections.Load() -} - -// Proxy handles a WebSocket upgrade request by establishing a tunnel to the target. -// It hijacks the client connection and proxies bidirectionally. -// -// onActivity, if set, is called whenever bytes arrive from the target. Bytes -// sent to the target don't count: writing into a dead tunnel can still succeed. -func (wp *WebSocketProxy) Proxy(w http.ResponseWriter, r *http.Request, targetURI string, onActivity func()) error { - targetURL, err := url.Parse(targetURI) - if err != nil { - return fmt.Errorf("invalid target URI: %w", err) - } - - // Determine target address - targetAddr := wp.resolveTargetAddr(targetURL) - - // Dial the target (through proxy if configured) - targetConn, err := wp.dialTarget(targetURL, targetAddr) - if err != nil { - http.Error(w, "Bad Gateway", http.StatusBadGateway) - return fmt.Errorf("dial failed: %w", err) - } - - // Forward the upgrade request to target - if err := wp.forwardUpgradeRequest(r, targetConn, targetURL); err != nil { - targetConn.Close() - http.Error(w, "Bad Gateway", http.StatusBadGateway) - return err - } - - // Hijack client connection - clientConn, err := wp.hijackConnection(w) - if err != nil { - targetConn.Close() - return err - } - - // Run the bidirectional tunnel - wp.runTunnel(clientConn, targetConn, targetAddr, onActivity) - return nil -} - -func (wp *WebSocketProxy) resolveTargetAddr(targetURL *url.URL) string { - host := targetURL.Hostname() - port := targetURL.Port() - if port == "" { - if targetURL.Scheme == "https" || targetURL.Scheme == "wss" { - port = "443" - } else { - port = "80" - } - } - return net.JoinHostPort(host, port) -} - -func (wp *WebSocketProxy) dialTarget(targetURL *url.URL, targetAddr string) (net.Conn, error) { - proxyURL, err := wp.getProxyURL(targetURL) - if err != nil { - return nil, err - } - - requiresTLS := targetURL.Scheme == "https" || targetURL.Scheme == "wss" - tlsConfig := wp.getTLSConfig(targetURL.Hostname(), requiresTLS) - - if proxyURL != nil { - wp.logger.Info("Connecting to WebSocket target through proxy", - zap.String("proxy", proxyURL.Host), - zap.String("target", targetAddr)) - return wp.dialThroughProxy(proxyURL, targetAddr, tlsConfig) - } - - wp.logger.Info("Connecting to WebSocket target directly", - zap.String("target", targetAddr), - zap.Bool("tls", requiresTLS)) - return wp.dialDirect(targetAddr, tlsConfig) -} - -func (wp *WebSocketProxy) getProxyURL(targetURL *url.URL) (*url.URL, error) { - if wp.transport != nil && wp.transport.Proxy != nil { - return wp.transport.Proxy(&http.Request{URL: targetURL}) - } - return http.ProxyFromEnvironment(&http.Request{URL: targetURL}) -} - -func (wp *WebSocketProxy) getTLSConfig(serverName string, requiresTLS bool) *tls.Config { - if !requiresTLS { - return nil - } - - if wp.transport != nil && wp.transport.TLSClientConfig != nil { - cfg := wp.transport.TLSClientConfig.Clone() - cfg.ServerName = serverName - return cfg - } - - return &tls.Config{ServerName: serverName} -} - -func (wp *WebSocketProxy) dialDirect(addr string, tlsConfig *tls.Config) (net.Conn, error) { - dialer := &net.Dialer{Timeout: wp.DialTimeout} - - if tlsConfig != nil { - return tls.DialWithDialer(dialer, "tcp", addr, tlsConfig) - } - return dialer.Dial("tcp", addr) -} - -func (wp *WebSocketProxy) dialThroughProxy(proxyURL *url.URL, targetAddr string, tlsConfig *tls.Config) (net.Conn, error) { - // Dial the proxy and establish the CONNECT tunnel via the shared - // helper (also used by the gRPC tunnel dialer), which preserves any - // bytes buffered past the CONNECT response. - ctx, cancel := context.WithTimeout(context.Background(), wp.DialTimeout) - defer cancel() - - var proxyTLS *tls.Config - if proxyURL.Scheme == "https" { - proxyTLS = wp.getTLSConfig(proxyURL.Hostname(), true) - } - - proxyConn, err := util.DialProxyConnect(ctx, proxyURL, targetAddr, proxyTLS, wp.HandshakeTimeout) - if err != nil { - return nil, err - } - - // Upgrade to TLS if needed - if tlsConfig != nil { - wp.logger.Debug("Starting TLS handshake through proxy tunnel", - zap.String("serverName", tlsConfig.ServerName)) - - tlsConn := tls.Client(proxyConn, tlsConfig) - if err := tlsConn.HandshakeContext(ctx); err != nil { - tlsConn.Close() - return nil, fmt.Errorf("TLS handshake failed: %w", err) - } - - // Log TLS connection details for debugging - state := tlsConn.ConnectionState() - wp.logger.Debug("TLS handshake completed", - zap.String("serverName", state.ServerName), - zap.String("negotiatedProtocol", state.NegotiatedProtocol), - zap.Uint16("version", state.Version), - zap.Bool("handshakeComplete", state.HandshakeComplete), - zap.Int("peerCertificates", len(state.PeerCertificates))) - - if len(state.PeerCertificates) > 0 { - wp.logger.Debug("TLS peer certificate", - zap.String("subject", state.PeerCertificates[0].Subject.String()), - zap.String("issuer", state.PeerCertificates[0].Issuer.String())) - } - - return tlsConn, nil - } - - return proxyConn, nil -} - -func (wp *WebSocketProxy) forwardUpgradeRequest(r *http.Request, targetConn net.Conn, targetURL *url.URL) error { - r.URL.Scheme = targetURL.Scheme - r.URL.Host = targetURL.Host - r.Host = targetURL.Host - - targetConn.SetWriteDeadline(time.Now().Add(wp.HandshakeTimeout)) - if err := r.Write(targetConn); err != nil { - return fmt.Errorf("forward upgrade failed: %w", err) - } - targetConn.SetWriteDeadline(time.Time{}) - - return nil -} - -func (wp *WebSocketProxy) hijackConnection(w http.ResponseWriter) (net.Conn, error) { - hijacker, ok := w.(http.Hijacker) - if !ok { - http.Error(w, "Hijacking not supported", http.StatusInternalServerError) - return nil, fmt.Errorf("ResponseWriter does not support hijacking") - } - - conn, _, err := hijacker.Hijack() - if err != nil { - http.Error(w, "Hijack failed", http.StatusInternalServerError) - return nil, fmt.Errorf("hijack failed: %w", err) - } - - return conn, nil -} - -func (wp *WebSocketProxy) runTunnel(clientConn, targetConn net.Conn, targetAddr string, onActivity func()) { - start := time.Now() - wp.activeConnections.Add(1) - - if wp.OnTunnelEstablished != nil { - wp.OnTunnelEstablished(targetAddr) - } - - defer func() { - wp.activeConnections.Add(-1) - if wp.OnTunnelClosed != nil { - wp.OnTunnelClosed(targetAddr, time.Since(start)) - } - }() - - done := make(chan struct{}, 2) - - copy := func(dst, src net.Conn, direction string, onRead func()) { - defer func() { done <- struct{}{} }() - wp.copyWithIdleTimeout(dst, src, direction, onRead) - } - - go copy(clientConn, targetConn, "target->client", onActivity) - go copy(targetConn, clientConn, "client->target", nil) - - <-done - clientConn.Close() - targetConn.Close() - <-done -} - -func (wp *WebSocketProxy) copyWithIdleTimeout(dst, src net.Conn, direction string, onRead func()) { - buf := make([]byte, 32*1024) - isFirstRead := true - for { - src.SetReadDeadline(time.Now().Add(wp.IdleTimeout)) - n, err := src.Read(buf) - - // Log first read details for debugging tunnel startup issues - if isFirstRead { - isFirstRead = false - if err != nil { - wp.logger.Debug("Tunnel first read failed", - zap.String("direction", direction), - zap.Int("bytesRead", n), - zap.Error(err), - zap.String("srcType", fmt.Sprintf("%T", src)), - zap.String("srcAddr", src.RemoteAddr().String())) - } else if n > 0 { - // Log the start of what was received (may be HTTP response) - preview := string(buf[:min(n, 200)]) - wp.logger.Debug("Tunnel first read successful", - zap.String("direction", direction), - zap.Int("bytesRead", n), - zap.String("preview", preview)) - } - } - - if n > 0 { - if onRead != nil { - onRead() - } - dst.SetWriteDeadline(time.Now().Add(wp.HandshakeTimeout)) - if _, writeErr := dst.Write(buf[:n]); writeErr != nil { - return - } - } - if err != nil { - if !isTimeoutError(err) && err != io.EOF { - wp.logger.Debug("Tunnel read error", zap.String("direction", direction), zap.Error(err)) - } - return - } - } -} - -// IsWebSocketUpgrade checks if a request is a WebSocket upgrade request. -func IsWebSocketUpgrade(r *http.Request) bool { - return strings.EqualFold(r.Header.Get("Upgrade"), "websocket") && - strings.Contains(strings.ToLower(r.Header.Get("Connection")), "upgrade") -} - -// isTimeoutError checks if an error is a network timeout error. -func isTimeoutError(err error) bool { - if netErr, ok := err.(net.Error); ok { - return netErr.Timeout() - } - return false -} diff --git a/agent/server/snykbroker/ws_proxy_test.go b/agent/server/snykbroker/ws_proxy_test.go deleted file mode 100644 index 906ff7b0..00000000 --- a/agent/server/snykbroker/ws_proxy_test.go +++ /dev/null @@ -1,910 +0,0 @@ -package snykbroker - -import ( - "crypto/tls" - "crypto/x509" - "io" - "net" - "net/http" - "net/http/httptest" - "net/url" - "sync/atomic" - "testing" - "time" - - "github.com/cortexapps/axon/config" - "github.com/gorilla/mux" - "github.com/gorilla/websocket" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestNewWebSocketProxy(t *testing.T) { - logger := newTestLogger(t) - - t.Run("with transport", func(t *testing.T) { - transport := &http.Transport{} - wsProxy := NewWebSocketProxy(logger, transport) - - require.NotNil(t, wsProxy) - assert.Equal(t, 30*time.Second, wsProxy.DialTimeout) - assert.Equal(t, 30*time.Second, wsProxy.HandshakeTimeout) - assert.Equal(t, 5*time.Minute, wsProxy.IdleTimeout) - assert.False(t, wsProxy.IsConnected()) - }) - - t.Run("without transport", func(t *testing.T) { - wsProxy := NewWebSocketProxy(logger, nil) - - require.NotNil(t, wsProxy) - assert.False(t, wsProxy.IsConnected()) - }) -} - -func TestIsWebSocketUpgrade(t *testing.T) { - tests := []struct { - name string - headers map[string]string - wantResult bool - }{ - { - name: "valid websocket upgrade", - headers: map[string]string{ - "Upgrade": "websocket", - "Connection": "Upgrade", - }, - wantResult: true, - }, - { - name: "case insensitive upgrade header", - headers: map[string]string{ - "Upgrade": "WebSocket", - "Connection": "upgrade", - }, - wantResult: true, - }, - { - name: "connection with keep-alive", - headers: map[string]string{ - "Upgrade": "websocket", - "Connection": "keep-alive, Upgrade", - }, - wantResult: true, - }, - { - name: "missing upgrade header", - headers: map[string]string{ - "Connection": "Upgrade", - }, - wantResult: false, - }, - { - name: "missing connection header", - headers: map[string]string{ - "Upgrade": "websocket", - }, - wantResult: false, - }, - { - name: "wrong upgrade value", - headers: map[string]string{ - "Upgrade": "h2c", - "Connection": "Upgrade", - }, - wantResult: false, - }, - { - name: "no headers", - headers: map[string]string{}, - wantResult: false, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - req := httptest.NewRequest("GET", "/ws", nil) - for k, v := range tt.headers { - req.Header.Set(k, v) - } - - result := IsWebSocketUpgrade(req) - assert.Equal(t, tt.wantResult, result) - }) - } -} - -func TestWebSocketProxyResolveTargetAddr(t *testing.T) { - logger := newTestLogger(t) - wsProxy := NewWebSocketProxy(logger, nil) - - tests := []struct { - name string - targetURI string - wantAddr string - }{ - { - name: "http with explicit port", - targetURI: "http://example.com:8080", - wantAddr: "example.com:8080", - }, - { - name: "http default port", - targetURI: "http://example.com", - wantAddr: "example.com:80", - }, - { - name: "https default port", - targetURI: "https://example.com", - wantAddr: "example.com:443", - }, - { - name: "wss default port", - targetURI: "wss://example.com", - wantAddr: "example.com:443", - }, - { - name: "ws default port", - targetURI: "ws://example.com", - wantAddr: "example.com:80", - }, - { - name: "https with explicit port", - targetURI: "https://example.com:9443", - wantAddr: "example.com:9443", - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - targetURL, err := url.Parse(tt.targetURI) - require.NoError(t, err) - - addr := wsProxy.resolveTargetAddr(targetURL) - assert.Equal(t, tt.wantAddr, addr) - }) - } -} - -func TestWebSocketProxyGetTLSConfig(t *testing.T) { - logger := newTestLogger(t) - - t.Run("no TLS required", func(t *testing.T) { - wsProxy := NewWebSocketProxy(logger, nil) - cfg := wsProxy.getTLSConfig("example.com", false) - assert.Nil(t, cfg) - }) - - t.Run("TLS required without transport", func(t *testing.T) { - wsProxy := NewWebSocketProxy(logger, nil) - cfg := wsProxy.getTLSConfig("example.com", true) - - require.NotNil(t, cfg) - assert.Equal(t, "example.com", cfg.ServerName) - }) - - t.Run("TLS required with transport but no TLS config", func(t *testing.T) { - transport := &http.Transport{} - wsProxy := NewWebSocketProxy(logger, transport) - cfg := wsProxy.getTLSConfig("example.com", true) - - require.NotNil(t, cfg) - assert.Equal(t, "example.com", cfg.ServerName) - }) - - t.Run("TLS required with custom transport TLS config", func(t *testing.T) { - customRoots := x509.NewCertPool() - transport := &http.Transport{ - TLSClientConfig: &tls.Config{ - RootCAs: customRoots, - InsecureSkipVerify: true, // just for testing - }, - } - wsProxy := NewWebSocketProxy(logger, transport) - cfg := wsProxy.getTLSConfig("example.com", true) - - require.NotNil(t, cfg) - assert.Equal(t, "example.com", cfg.ServerName) - assert.True(t, cfg.InsecureSkipVerify, "should inherit InsecureSkipVerify") - assert.Equal(t, customRoots, cfg.RootCAs, "should inherit RootCAs") - }) -} - -func TestWebSocketProxyGetProxyURL(t *testing.T) { - logger := newTestLogger(t) - - t.Run("transport with proxy function", func(t *testing.T) { - proxyURL, _ := url.Parse("http://proxy.example.com:8080") - transport := &http.Transport{ - Proxy: http.ProxyURL(proxyURL), - } - wsProxy := NewWebSocketProxy(logger, transport) - - targetURL, _ := url.Parse("http://target.example.com") - result, err := wsProxy.getProxyURL(targetURL) - - require.NoError(t, err) - require.NotNil(t, result) - assert.Equal(t, "proxy.example.com:8080", result.Host) - }) - - t.Run("transport with nil proxy function", func(t *testing.T) { - transport := &http.Transport{ - Proxy: nil, - } - wsProxy := NewWebSocketProxy(logger, transport) - - targetURL, _ := url.Parse("http://target.example.com") - result, err := wsProxy.getProxyURL(targetURL) - - require.NoError(t, err) - // Result depends on environment variables, but shouldn't error - _ = result - }) - - t.Run("nil transport falls back to environment", func(t *testing.T) { - wsProxy := NewWebSocketProxy(logger, nil) - - targetURL, _ := url.Parse("http://target.example.com") - result, err := wsProxy.getProxyURL(targetURL) - - require.NoError(t, err) - // Result depends on environment variables - _ = result - }) -} - -func TestWebSocketProxyDialDirect(t *testing.T) { - logger := newTestLogger(t) - - t.Run("successful connection", func(t *testing.T) { - // Create a simple TCP server - listener, err := net.Listen("tcp", "127.0.0.1:0") - require.NoError(t, err) - defer listener.Close() - - go func() { - conn, _ := listener.Accept() - if conn != nil { - conn.Close() - } - }() - - wsProxy := NewWebSocketProxy(logger, nil) - wsProxy.DialTimeout = 5 * time.Second - - conn, err := wsProxy.dialDirect(listener.Addr().String(), nil) - require.NoError(t, err) - require.NotNil(t, conn) - conn.Close() - }) - - t.Run("connection refused", func(t *testing.T) { - wsProxy := NewWebSocketProxy(logger, nil) - wsProxy.DialTimeout = 1 * time.Second - - conn, err := wsProxy.dialDirect("127.0.0.1:59999", nil) - require.Error(t, err) - assert.Nil(t, conn) - }) -} - -// newConnectProxy is a minimal HTTP CONNECT proxy that tunnels bytes to -// whatever host the client asked for. -func newConnectProxy(t *testing.T) *httptest.Server { - t.Helper() - return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Method != "CONNECT" { - http.Error(w, "Expected CONNECT", http.StatusMethodNotAllowed) - return - } - - targetConn, err := net.Dial("tcp", r.Host) - if err != nil { - http.Error(w, err.Error(), http.StatusBadGateway) - return - } - - hijacker, ok := w.(http.Hijacker) - if !ok { - targetConn.Close() - http.Error(w, "Hijacking not supported", http.StatusInternalServerError) - return - } - - clientConn, _, err := hijacker.Hijack() - if err != nil { - targetConn.Close() - return - } - - clientConn.Write([]byte("HTTP/1.1 200 Connection Established\r\n\r\n")) - - go func() { - io.Copy(targetConn, clientConn) - targetConn.Close() - }() - go func() { - io.Copy(clientConn, targetConn) - clientConn.Close() - }() - })) -} - -func TestWebSocketProxyDialThroughProxy(t *testing.T) { - logger := newTestLogger(t) - - t.Run("successful CONNECT through proxy", func(t *testing.T) { - // Create target server - targetListener, err := net.Listen("tcp", "127.0.0.1:0") - require.NoError(t, err) - defer targetListener.Close() - - var targetConnected atomic.Bool - go func() { - conn, _ := targetListener.Accept() - if conn != nil { - targetConnected.Store(true) - io.Copy(io.Discard, conn) - conn.Close() - } - }() - - proxyServer := newConnectProxy(t) - defer proxyServer.Close() - - proxyURL, _ := url.Parse(proxyServer.URL) - wsProxy := NewWebSocketProxy(logger, nil) - wsProxy.DialTimeout = 5 * time.Second - wsProxy.HandshakeTimeout = 5 * time.Second - - conn, err := wsProxy.dialThroughProxy(proxyURL, targetListener.Addr().String(), nil) - require.NoError(t, err) - require.NotNil(t, conn) - - // Write something to trigger the target connection - conn.Write([]byte("test")) - conn.Close() - - time.Sleep(100 * time.Millisecond) - assert.True(t, targetConnected.Load(), "should have connected to target through proxy") - }) - - t.Run("TLS handshake times out", func(t *testing.T) { - // A target that accepts the tunnelled connection and never answers - // the ClientHello. Without a deadline on the handshake, the dial - // would block forever. - targetListener, err := net.Listen("tcp", "127.0.0.1:0") - require.NoError(t, err) - defer targetListener.Close() - go func() { - for { - conn, err := targetListener.Accept() - if err != nil { - return - } - defer conn.Close() - } - }() - - proxyServer := newConnectProxy(t) - defer proxyServer.Close() - - proxyURL, _ := url.Parse(proxyServer.URL) - wsProxy := NewWebSocketProxy(logger, nil) - wsProxy.DialTimeout = 300 * time.Millisecond - wsProxy.HandshakeTimeout = 300 * time.Millisecond - - start := time.Now() - conn, err := wsProxy.dialThroughProxy(proxyURL, targetListener.Addr().String(), - &tls.Config{ServerName: "target", InsecureSkipVerify: true}) - - require.Error(t, err) - assert.Nil(t, conn) - assert.Contains(t, err.Error(), "TLS handshake failed") - assert.Less(t, time.Since(start), 2*time.Second) - }) - - t.Run("proxy rejects CONNECT", func(t *testing.T) { - proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - http.Error(w, "Forbidden", http.StatusForbidden) - })) - defer proxyServer.Close() - - proxyURL, _ := url.Parse(proxyServer.URL) - wsProxy := NewWebSocketProxy(logger, nil) - wsProxy.DialTimeout = 5 * time.Second - wsProxy.HandshakeTimeout = 5 * time.Second - - conn, err := wsProxy.dialThroughProxy(proxyURL, "target.example.com:443", nil) - require.Error(t, err) - assert.Nil(t, conn) - assert.Contains(t, err.Error(), "proxy rejected CONNECT") - }) - - t.Run("proxy with basic auth", func(t *testing.T) { - var receivedAuth string - proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - receivedAuth = r.Header.Get("Proxy-Authorization") - http.Error(w, "Auth checked", http.StatusForbidden) - })) - defer proxyServer.Close() - - proxyURL, _ := url.Parse(proxyServer.URL) - proxyURL.User = url.UserPassword("user", "pass") - - wsProxy := NewWebSocketProxy(logger, nil) - wsProxy.DialTimeout = 5 * time.Second - wsProxy.HandshakeTimeout = 5 * time.Second - - _, err := wsProxy.dialThroughProxy(proxyURL, "target.example.com:443", nil) - require.Error(t, err) // Will fail auth, but we just check auth was sent - - assert.NotEmpty(t, receivedAuth, "should have sent Proxy-Authorization header") - assert.Contains(t, receivedAuth, "Basic ") - }) -} - -func TestWebSocketProxyCallbacks(t *testing.T) { - logger := newTestLogger(t) - - // Create a simple WebSocket echo server - var upgrader = websocket.Upgrader{ - CheckOrigin: func(r *http.Request) bool { return true }, - } - - router := mux.NewRouter() - router.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) { - conn, err := upgrader.Upgrade(w, r, nil) - if err != nil { - return - } - defer conn.Close() - - // Just close immediately for this test - time.Sleep(50 * time.Millisecond) - }) - targetServer := httptest.NewServer(router) - defer targetServer.Close() - - // Create reflector with the WebSocket proxy - wsProxy := NewWebSocketProxy(logger, nil) - wsProxy.IdleTimeout = 100 * time.Millisecond - - var establishedTarget string - var closedTarget string - var closedDuration time.Duration - - wsProxy.OnTunnelEstablished = func(target string) { - establishedTarget = target - } - wsProxy.OnTunnelClosed = func(target string, duration time.Duration) { - closedTarget = target - closedDuration = duration - } - - // Create a reflector to test through - rr := NewRegistrationReflector(RegistrationReflectorParams{ - Logger: logger, - Config: config.AgentConfig{ - ReflectorWebSocketUpgrade: true, - }, - }) - - reflectorRouter := mux.NewRouter() - rr.RegisterRoutes(reflectorRouter) - reflectorServer := httptest.NewServer(reflectorRouter) - defer reflectorServer.Close() - - // Inject our WebSocket proxy with callbacks - rr.wsProxy = wsProxy - - // Register target - proxyURI := rr.ProxyURI(targetServer.URL) - - // Connect - wsURL := "ws" + proxyURI[4:] + "/ws" - dialer := websocket.Dialer{} - conn, _, err := dialer.Dial(wsURL, nil) - require.NoError(t, err) - - // Wait for tunnel to establish - time.Sleep(50 * time.Millisecond) - assert.NotEmpty(t, establishedTarget, "OnTunnelEstablished should have been called") - - // Close connection - conn.Close() - - // Wait for tunnel to close - time.Sleep(200 * time.Millisecond) - assert.NotEmpty(t, closedTarget, "OnTunnelClosed should have been called") - assert.True(t, closedDuration > 0, "duration should be positive") -} - -// Frames from the broker server on the default entry (the broker's own -// tunnel) count as tunnel activity. Our own writes don't, since writing into a -// dead tunnel can still succeed, and neither does a websocket to a customer -// origin, which says nothing about the broker's tunnel. -func TestReflectorRecordsTunnelActivityForBrokerTunnelOnly(t *testing.T) { - logger := newTestLogger(t) - - // A websocket server that sends one frame when told to. - newTarget := func(t *testing.T) (*httptest.Server, chan struct{}) { - send := make(chan struct{}) - upgrader := websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }} - router := mux.NewRouter() - router.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) { - conn, err := upgrader.Upgrade(w, r, nil) - if err != nil { - return - } - defer conn.Close() - go func() { - for { - if _, _, err := conn.ReadMessage(); err != nil { - return - } - } - }() - <-send - _ = conn.WriteMessage(websocket.TextMessage, []byte("primus::ping::1")) - time.Sleep(200 * time.Millisecond) - }) - server := httptest.NewServer(router) - t.Cleanup(server.Close) - return server, send - } - - rr := NewRegistrationReflector(RegistrationReflectorParams{ - Logger: logger, - Config: config.AgentConfig{ReflectorWebSocketUpgrade: true}, - }) - reflectorRouter := mux.NewRouter() - rr.RegisterRoutes(reflectorRouter) - reflectorServer := httptest.NewServer(reflectorRouter) - defer reflectorServer.Close() - - // Dial through the reflector, write one frame of our own, then have the - // target send one. Returns the tunnel watermark after each step. - exchange := func(t *testing.T, proxyURI string, send chan struct{}) (afterOwnWrite, afterTargetFrame int64) { - conn, _, err := (&websocket.Dialer{}).Dial("ws"+proxyURI[4:]+"/ws", nil) - require.NoError(t, err) - defer conn.Close() - - // The upgrade response is the first read from the target; only frames - // after it are under test. - time.Sleep(50 * time.Millisecond) - before := rr.lastTunnelTime.Load() - - require.NoError(t, conn.WriteMessage(websocket.TextMessage, []byte("primus::pong::1"))) - time.Sleep(50 * time.Millisecond) - afterOwnWrite = rr.lastTunnelTime.Load() - require.Equal(t, before, afterOwnWrite, "our own writes must not count as tunnel activity") - - // Millisecond watermark: make sure a new stamp can differ from the old. - time.Sleep(5 * time.Millisecond) - close(send) - _, msg, err := conn.ReadMessage() - require.NoError(t, err) - require.Equal(t, "primus::ping::1", string(msg)) - return afterOwnWrite, rr.lastTunnelTime.Load() - } - - t.Run("customer origin", func(t *testing.T) { - target, send := newTarget(t) - before, after := exchange(t, rr.ProxyURI(target.URL), send) - require.Equal(t, before, after, "a websocket to a customer origin must not count as tunnel activity") - }) - - t.Run("broker tunnel", func(t *testing.T) { - target, send := newTarget(t) - before, after := exchange(t, rr.ProxyURI(target.URL, WithDefault(true)), send) - require.Greater(t, after, before, "a frame from the broker server must count as tunnel activity") - }) -} - -func TestWebSocketProxyIsConnected(t *testing.T) { - logger := newTestLogger(t) - - wsProxy := NewWebSocketProxy(logger, nil) - assert.False(t, wsProxy.IsConnected(), "should not be connected initially") - assert.Equal(t, int32(0), wsProxy.ActiveConnections(), "should have 0 active connections") - - // Manually increment active connections for testing - wsProxy.activeConnections.Add(1) - assert.True(t, wsProxy.IsConnected(), "should report connected with 1 connection") - assert.Equal(t, int32(1), wsProxy.ActiveConnections(), "should have 1 active connection") - - // Add another connection - wsProxy.activeConnections.Add(1) - assert.True(t, wsProxy.IsConnected(), "should report connected with 2 connections") - assert.Equal(t, int32(2), wsProxy.ActiveConnections(), "should have 2 active connections") - - // Remove one connection - wsProxy.activeConnections.Add(-1) - assert.True(t, wsProxy.IsConnected(), "should still report connected with 1 connection") - assert.Equal(t, int32(1), wsProxy.ActiveConnections(), "should have 1 active connection") - - // Remove last connection - wsProxy.activeConnections.Add(-1) - assert.False(t, wsProxy.IsConnected(), "should report disconnected with 0 connections") - assert.Equal(t, int32(0), wsProxy.ActiveConnections(), "should have 0 active connections") -} - -func TestIsTimeoutError(t *testing.T) { - t.Run("timeout error", func(t *testing.T) { - // Create a connection and set a very short deadline - listener, err := net.Listen("tcp", "127.0.0.1:0") - require.NoError(t, err) - defer listener.Close() - - go func() { - conn, _ := listener.Accept() - if conn != nil { - // Don't write anything, let it timeout - time.Sleep(time.Second) - conn.Close() - } - }() - - conn, err := net.Dial("tcp", listener.Addr().String()) - require.NoError(t, err) - defer conn.Close() - - conn.SetReadDeadline(time.Now().Add(1 * time.Millisecond)) - time.Sleep(5 * time.Millisecond) - - buf := make([]byte, 1) - _, err = conn.Read(buf) - require.Error(t, err) - assert.True(t, isTimeoutError(err), "should be a timeout error") - }) - - t.Run("non-timeout error", func(t *testing.T) { - // io.EOF is not a timeout error - assert.False(t, isTimeoutError(io.EOF)) - }) - - t.Run("nil error", func(t *testing.T) { - assert.False(t, isTimeoutError(nil)) - }) -} - -func TestWebSocketProxyFullFlowThroughHTTPProxy(t *testing.T) { - // Create a WebSocket echo server (the actual target) - var upgrader = websocket.Upgrader{ - CheckOrigin: func(r *http.Request) bool { return true }, - } - - targetRouter := mux.NewRouter() - targetRouter.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) { - conn, err := upgrader.Upgrade(w, r, nil) - if err != nil { - t.Logf("WebSocket upgrade failed: %v", err) - return - } - defer conn.Close() - - // Echo messages back - for { - messageType, message, err := conn.ReadMessage() - if err != nil { - break - } - if err := conn.WriteMessage(messageType, message); err != nil { - break - } - } - }) - targetServer := httptest.NewServer(targetRouter) - defer targetServer.Close() - - // Create an HTTP CONNECT proxy - proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Method != "CONNECT" { - http.Error(w, "Expected CONNECT", http.StatusMethodNotAllowed) - return - } - - t.Logf("Proxy received CONNECT to %s", r.Host) - - targetConn, err := net.Dial("tcp", r.Host) - if err != nil { - http.Error(w, err.Error(), http.StatusBadGateway) - return - } - - hijacker, ok := w.(http.Hijacker) - if !ok { - targetConn.Close() - http.Error(w, "Hijacking not supported", http.StatusInternalServerError) - return - } - clientConn, _, err := hijacker.Hijack() - if err != nil { - targetConn.Close() - return - } - - clientConn.Write([]byte("HTTP/1.1 200 Connection Established\r\n\r\n")) - - go func() { - io.Copy(targetConn, clientConn) - targetConn.Close() - }() - go func() { - io.Copy(clientConn, targetConn) - clientConn.Close() - }() - })) - defer proxyServer.Close() - - // Create WebSocketProxy with the proxy configured via transport - logger := newTestLogger(t) - proxyURL, _ := url.Parse(proxyServer.URL) - transport := &http.Transport{ - Proxy: http.ProxyURL(proxyURL), - } - - wsProxy := NewWebSocketProxy(logger, transport) - - // Test dialTarget directly - targetURL, _ := url.Parse(targetServer.URL) - targetAddr := wsProxy.resolveTargetAddr(targetURL) - - conn, err := wsProxy.dialTarget(targetURL, targetAddr) - require.NoError(t, err, "dialTarget through proxy should succeed") - require.NotNil(t, conn) - conn.Close() -} - -func TestWebSocketProxyFullFlowThroughHTTPProxyWithTLS(t *testing.T) { - // Create a TLS WebSocket echo server (the actual target) - var upgrader = websocket.Upgrader{ - CheckOrigin: func(r *http.Request) bool { return true }, - } - - targetRouter := mux.NewRouter() - targetRouter.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) { - t.Logf("Target received request: %s %s", r.Method, r.URL) - t.Logf("Target headers: Host=%s Upgrade=%s Connection=%s", - r.Host, r.Header.Get("Upgrade"), r.Header.Get("Connection")) - - conn, err := upgrader.Upgrade(w, r, nil) - if err != nil { - t.Logf("WebSocket upgrade failed: %v", err) - return - } - defer conn.Close() - - // Echo messages back - for { - messageType, message, err := conn.ReadMessage() - if err != nil { - t.Logf("Target read error: %v", err) - break - } - t.Logf("Target received message: %s", message) - if err := conn.WriteMessage(messageType, message); err != nil { - t.Logf("Target write error: %v", err) - break - } - } - }) - - // Use NewTLSServer for HTTPS target - targetServer := httptest.NewTLSServer(targetRouter) - defer targetServer.Close() - - t.Logf("TLS Target server at: %s", targetServer.URL) - - // Create an HTTP CONNECT proxy (transparent tunnel - doesn't inspect TLS) - proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Method != "CONNECT" { - http.Error(w, "Expected CONNECT", http.StatusMethodNotAllowed) - return - } - - t.Logf("Proxy received CONNECT to %s", r.Host) - - // Connect to the target (TLS server) - targetConn, err := net.Dial("tcp", r.Host) - if err != nil { - t.Logf("Proxy failed to connect to target: %v", err) - http.Error(w, err.Error(), http.StatusBadGateway) - return - } - - hijacker, ok := w.(http.Hijacker) - if !ok { - targetConn.Close() - http.Error(w, "Hijacking not supported", http.StatusInternalServerError) - return - } - clientConn, _, err := hijacker.Hijack() - if err != nil { - targetConn.Close() - return - } - - // Send 200 OK to establish the tunnel - clientConn.Write([]byte("HTTP/1.1 200 Connection Established\r\n\r\n")) - t.Log("Proxy sent 200 Connection Established") - - // Bidirectional copy - TLS traffic passes through transparently - // Note: Don't use t.Logf in goroutines - test may complete before they finish - done := make(chan struct{}, 2) - go func() { - io.Copy(targetConn, clientConn) - targetConn.Close() - done <- struct{}{} - }() - go func() { - io.Copy(clientConn, targetConn) - clientConn.Close() - done <- struct{}{} - }() - <-done - <-done - })) - defer proxyServer.Close() - - t.Logf("Proxy server at: %s", proxyServer.URL) - - // Create WebSocketProxy with the proxy configured via transport - // Use InsecureSkipVerify since the target uses a self-signed test certificate - logger := newTestLogger(t) - proxyURL, _ := url.Parse(proxyServer.URL) - transport := &http.Transport{ - Proxy: http.ProxyURL(proxyURL), - TLSClientConfig: &tls.Config{ - InsecureSkipVerify: true, - }, - } - - wsProxy := NewWebSocketProxy(logger, transport) - - // Test dialTarget - this establishes TCP -> CONNECT -> TLS - targetURL, _ := url.Parse(targetServer.URL) - targetAddr := wsProxy.resolveTargetAddr(targetURL) - - t.Logf("Dialing target URL: %s, addr: %s", targetServer.URL, targetAddr) - - conn, err := wsProxy.dialTarget(targetURL, targetAddr) - require.NoError(t, err, "dialTarget through proxy to TLS target should succeed") - require.NotNil(t, conn) - - // Verify it's a TLS connection - tlsConn, ok := conn.(*tls.Conn) - require.True(t, ok, "connection should be a TLS connection") - - state := tlsConn.ConnectionState() - t.Logf("TLS state: version=%d, handshakeComplete=%v, serverName=%s", - state.Version, state.HandshakeComplete, state.ServerName) - require.True(t, state.HandshakeComplete, "TLS handshake should be complete") - - // Now send a WebSocket upgrade request through the TLS tunnel - upgradeReq := "GET /ws HTTP/1.1\r\n" + - "Host: " + targetURL.Host + "\r\n" + - "Upgrade: websocket\r\n" + - "Connection: Upgrade\r\n" + - "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n" + - "Sec-WebSocket-Version: 13\r\n" + - "\r\n" - - t.Log("Sending WebSocket upgrade request") - _, err = conn.Write([]byte(upgradeReq)) - require.NoError(t, err, "write upgrade request should succeed") - - // Read the response - buf := make([]byte, 4096) - conn.SetReadDeadline(time.Now().Add(5 * time.Second)) - n, err := conn.Read(buf) - require.NoError(t, err, "read upgrade response should succeed") - - response := string(buf[:n]) - t.Logf("Received response:\n%s", response) - require.Contains(t, response, "101 Switching Protocols", "should receive WebSocket upgrade response") - require.Contains(t, response, "Upgrade: websocket", "response should have Upgrade header") - - conn.Close() -} diff --git a/agent/test/conformance/README.md b/agent/test/conformance/README.md index 894eb06c..6d4c4d13 100644 --- a/agent/test/conformance/README.md +++ b/agent/test/conformance/README.md @@ -1,12 +1,8 @@ # Accept-file conformance fixtures -These fixtures pin the semantics of accept-file matching and rewriting so -they cannot diverge between the two relay transports (design doc -`docs/design/grpc-tunnel-v2.md` §9): - -- **snyk-broker mode**: rules are enforced by the Node broker itself. -- **grpc-tunnel mode**: rules are enforced by the Go matcher - (`acceptfile.MatchRule`) via the gRPC tunnel Router. +These fixtures pin the semantics of accept-file matching and rewriting +(design doc `docs/design/grpc-tunnel-v2.md` §9). Rules are enforced by the +Go matcher (`acceptfile.MatchRule`) via the gRPC tunnel Router. Each fixture is one JSON file: @@ -42,16 +38,12 @@ Each fixture is one JSON file: - `expect.absentHeaders` asserts headers that must NOT reach the upstream — internal routing metadata, chiefly. -Runners: +Runner: `agent/server/grpctunnel/conformance_test.go` runs every fixture +through the Go path (accept-file render → Router.Route) on every test run. -1. `agent/server/grpctunnel/conformance_test.go` runs every fixture - through the Go path (accept-file render → Router.Route) on every test - run. -2. A second runner playing the same cases through a live broker - (`agent/test/relay/`) is **not built yet**. Until it is, divergence - from the Node broker is caught by review and by the fixtures below - rather than by the build, so a fixture that encodes broker parity - should say so in its case names. +Accept files come from snyk-broker, and many fixtures encode parity with +its behaviour, so that accept files written for it keep working. A fixture +that encodes broker parity should say so in its case names. Deliberate divergences from snyk-broker, so they are not mistaken for bugs: @@ -61,19 +53,18 @@ bugs: compares case-sensitively and an empty array rejects everything. Both differences are more permissive, so a request the broker routed still routes. -- **Nothing in an accept file stops the agent.** Enabling the tunnel - switches deployments that run on snyk-broker today, and a file the - broker accepts has to still start. Constructs the Router cannot carry — +- **Nothing in an accept file stops the agent.** Deployments that moved + from snyk-broker keep their accept files, and a file the broker + accepted has to still start. Constructs the Router cannot carry — body and query `valid` filters, `requiredCapabilities`, unrecognized auth schemes, inbound `public` rules — are warned about and ignored. A warning that changes what a rule matches says so. - The one exception is a malformed wildcard origin, which the - snyk-broker path refuses too (at render, or by panicking when the - reflector is off), so no working deployment carries one. + The one exception is a malformed wildcard origin, which snyk-broker + refused too, so no working deployment carries one. - `${VAR}` in a `path` is a **segment placeholder, not a filter**: it matches whatever the caller sent there and the configured value is substituted into the outgoing URL. That is snyk-broker's behaviour, quirks included. When adding an accept-file feature, add fixture cases FIRST — they define -the semantics both transports must implement. +the semantics the tunnel must implement. diff --git a/agent/test/load/docker-compose.load.yml b/agent/test/load/docker-compose.load.yml index 910313b7..adfed9c0 100644 --- a/agent/test/load/docker-compose.load.yml +++ b/agent/test/load/docker-compose.load.yml @@ -84,7 +84,6 @@ services: volumes: - .:/src:ro environment: &agent-env - RELAY_MODE: grpc-tunnel ECHO_ORIGIN: http://echo-server-a:8080 BROKER_SERVER_URL: grpc-tunnel-server:50052 BROKER_TOKEN: tok-a diff --git a/agent/test/relay/Dockerfile.snyk-broker-server b/agent/test/relay/Dockerfile.snyk-broker-server deleted file mode 100644 index 27863b20..00000000 --- a/agent/test/relay/Dockerfile.snyk-broker-server +++ /dev/null @@ -1,24 +0,0 @@ -FROM debian:stable-slim - -# Install NodeJS and Snyk Broker -ENV NODE_VERSION=20 -ARG SNYK_BROKER_VERSION=v1.0.25-axon -RUN apt update && apt install -y git wget && \ - wget -q -O - https://deb.nodesource.com/setup_${NODE_VERSION}.x | bash - && \ - apt install -y nodejs && \ - npm install --global npm@11.18.0 typescript@4.9.3 - -RUN git clone https://github.com/cortexapps/snyk-broker.git /tmp/snyk-broker && \ - cd /tmp/snyk-broker && \ - git checkout ${SNYK_BROKER_VERSION} && \ - npm ci && \ - cp -r . /usr/local/snyk-broker && \ - cd /usr/local/snyk-broker && \ - npm install --global . && \ - npm prune --omit=dev && \ - rm -rf /tmp/snyk-broker - -ENV PATH="/usr/local/lib/node_modules/.bin:${PATH}" - -ENTRYPOINT ["snyk-broker"] -CMD ["server"] diff --git a/agent/test/relay/accept-server.json b/agent/test/relay/accept-server.json deleted file mode 100644 index 160c4e6c..00000000 --- a/agent/test/relay/accept-server.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "public": [ - { - "method": "any", - "path": "/*" - } - ] , - "private": [ - - ] -} - - diff --git a/agent/test/relay/docker-compose.grpc.noproxy.yml b/agent/test/relay/docker-compose.grpc.noproxy.yml deleted file mode 100644 index 24e9df2c..00000000 --- a/agent/test/relay/docker-compose.grpc.noproxy.yml +++ /dev/null @@ -1,12 +0,0 @@ -# Override for PROXY=0 testing - adds external network for direct access -# -# Usage: docker compose -f docker-compose.grpc.yml -f docker-compose.grpc.noproxy.yml up -# -# Without this override, axon-relay can only reach grpc-tunnel-server through mitmproxy. -# This adds the external network so axon-relay can connect directly. - -services: - axon-relay: - networks: - - internal - - external diff --git a/agent/test/relay/docker-compose.grpc.yml b/agent/test/relay/docker-compose.grpc.yml deleted file mode 100644 index 3d49a2c2..00000000 --- a/agent/test/relay/docker-compose.grpc.yml +++ /dev/null @@ -1,132 +0,0 @@ -services: - grpc-tunnel-server: - build: - context: ../../.. - dockerfile: server/docker/Dockerfile - image: cortex-axon-tunnel-server:local - ports: - - "${GRPC_PORT}:443" - - "${HTTP_PORT}:8080" - environment: - # 443, like production: the agent gets a port-less serverUri from - # registration (see cortex-fake) and must default the port itself. - GRPC_PORT: 443 - HTTP_PORT: 8080 - SERVER_ID: test-server-1 - DISPATCH_TIMEOUT: 60s - HEARTBEAT_INTERVAL: 10s - ENV: development - TOKEN: ${TOKEN:-0e481b34-76ac-481a-a92f-c94a6cf6f6c1} - networks: - - external # grpc-tunnel-server is on external network only - - mitmproxy: - image: mitmproxy/mitmproxy:12 - ports: - - "9980:8080" - - "9981:8081" - volumes: - # Mount to /certs (not /home/mitmproxy/.mitmproxy) to avoid entrypoint usermod failure in CI - - ./.mitmproxy:/certs - - ./mitmproxy_addon_header.py:/home/mitmproxy/addon.py - # Use confdir=/certs so mitmproxy uses our CA files from /certs instead of default location - # This avoids the entrypoint script trying to chown files (which fails in CI) - command: mitmdump --set confdir=/certs -s /home/mitmproxy/addon.py - healthcheck: - test: ["CMD", "python3", "-c", "import socket; s=socket.socket(); s.connect(('localhost', 8080)); s.close()"] - interval: 2s - timeout: 5s - retries: 10 - networks: - - internal # mitmproxy bridges both networks - - external - - axon-relay: - build: - context: ../../.. - dockerfile: docker/Dockerfile - # CI points this at the go-only image (make docker-build-grpc). - image: ${AXON_AGENT_IMAGE:-cortex-axon-agent:local} - volumes: - - .:/src - - ./.mitmproxy:/certs - - ../../server/snykbroker/acceptfile:/agent/plugins - environment: - CORTEX_API_TOKEN: fake-token - CORTEX_API_BASE_URL: http://cortex-fake:8081 - GITHUB_RAW_API: https://raw.githubusercontent.com - # GITLAB_TOKEN drives the /gitlab/* Basic-auth rule in accept-client.json. - # GITLAB_USERNAME is intentionally left unset to exercise the ${GITLAB_USERNAME:oauth2} default. - GITLAB_TOKEN: gitlab-test-token - PORT: 7433 - PLUGIN_DIRS: /agent/plugins - RELAY_MODE: grpc-tunnel - AXON_GRPC_TUNNEL_CONNS: 2 - # No BROKER_SERVER_URL here: the agent must use the serverUri from - # registration, as it does in production. - GRPC_INSECURE: "true" - CORTEX_TENANT_ID: test-tenant - TOKEN: ${TOKEN:-0e481b34-76ac-481a-a92f-c94a6cf6f6c1} - env_file: ${ENVFILE:-noproxy.env} - # --verbose because relay_test.grpc.sh asserts on "Tunnel stream - # established", which tunnel_client.go logs at debug: opening a stream is - # routine, so it is deliberately not Info. The proxy-dial line the test - # also greps for is Info, which is why only this assertion broke when the - # stream line was demoted. - command: relay --verbose -f /src/accept-client.json -i github -a axon-test - depends_on: - mitmproxy: - condition: service_healthy - grpc-tunnel-server: - condition: service_started - cortex-fake: - condition: service_healthy - healthcheck: - test: ["CMD", "curl", "-f", "http://localhost:7433/healthcheck"] - interval: 5s - timeout: 5s - retries: 6 - networks: - - internal - # For PROXY=1: this is the only network, forcing traffic through mitmproxy - # For PROXY=0: docker-compose.grpc.noproxy.yml adds external network - - python-server: - image: python:3.12-alpine - volumes: - - /tmp:/tmp - command: sh -c "apk add curl && python3 -m http.server 80 -d /tmp" - healthcheck: - test: ["CMD", "sh", "-c", "curl -f http://localhost:80/ || true"] # just check server is up - interval: 5s - timeout: 5s - retries: 6 - stop_grace_period: 1s # SIGKILL after 1s - networks: - - internal # python-server is a local customer service - - cortex-fake: - image: golang:1.24-alpine - volumes: - - .:/src - environment: - PORT: 8081 - # Same shape brain-backend returns (https://relay.cortex.io): a scheme - # and no port. - BROKER_SERVER_URL: https://grpc-tunnel-server - TOKEN: ${TOKEN:-0e481b34-76ac-481a-a92f-c94a6cf6f6c1} - command: sh -c "apk add curl && cd /src && go run cortex-registration-fake.go" - healthcheck: - test: ["CMD", "curl", "-f", "http://localhost:8081/healthcheck"] - interval: 1s - timeout: 1s - retries: 30 - networks: - - internal # cortex-fake is accessed by axon-relay for registration - -networks: - internal: - # Internal network - axon-relay, python-server, cortex-fake - # axon-relay can only reach external network via mitmproxy - external: - # External network - grpc-tunnel-server (mimics Cortex side) diff --git a/agent/test/relay/docker-compose.noproxy.yml b/agent/test/relay/docker-compose.noproxy.yml index a8528606..75cb4020 100644 --- a/agent/test/relay/docker-compose.noproxy.yml +++ b/agent/test/relay/docker-compose.noproxy.yml @@ -2,7 +2,7 @@ # # Usage: docker compose -f docker-compose.yml -f docker-compose.noproxy.yml up # -# Without this override, axon-relay can only reach snyk-broker through mitmproxy. +# Without this override, axon-relay can only reach grpc-tunnel-server through mitmproxy. # This adds the external network so axon-relay can connect directly. services: diff --git a/agent/test/relay/docker-compose.proxy.yml b/agent/test/relay/docker-compose.proxy.yml deleted file mode 100644 index e7bc5daf..00000000 --- a/agent/test/relay/docker-compose.proxy.yml +++ /dev/null @@ -1,17 +0,0 @@ -# Override for PROXY=1 testing - enables HTTPS broker connection through proxy -# -# Usage: docker compose -f docker-compose.yml -f docker-compose.proxy.yml up -# -# This enables the full TLS-through-proxy scenario: -# 1. axon-relay connects via HTTP CONNECT proxy (mitmproxy) -# 2. Establishes TLS tunnel to snyk-broker-tls (nginx TLS termination) -# 3. WebSocket upgrade happens over HTTPS/WSS -# -# This matches the production scenario where customers connect through -# corporate proxies to relay.cortex.io:443 - -services: - cortex-fake: - environment: - # Override to use HTTPS endpoint via TLS proxy - BROKER_SERVER_URL: https://snyk-broker-tls:7341 diff --git a/agent/test/relay/docker-compose.yml b/agent/test/relay/docker-compose.yml index 94299860..acf19691 100644 --- a/agent/test/relay/docker-compose.yml +++ b/agent/test/relay/docker-compose.yml @@ -1,31 +1,24 @@ services: - snyk-broker: + grpc-tunnel-server: build: - context: . - dockerfile: Dockerfile.snyk-broker-server - image: cortex-snyk-broker-server:local + context: ../../.. + dockerfile: server/docker/Dockerfile + image: cortex-axon-tunnel-server:local ports: - # Expose HTTP for direct test script access (curl commands in relay_test.sh) - - "${SERVER_PORT}:7341" - volumes: - - .:/src + - "${GRPC_PORT}:443" + - "${HTTP_PORT}:8080" environment: - ACCEPT: /src/accept-server.json - networks: - - external # snyk-broker is on external network only - - # TLS proxy in front of snyk-broker (mimics production relay.cortex.io setup) - # axon-relay connects here via proxy to test TLS-through-proxy scenario - snyk-broker-tls: - image: nginx:alpine - # No external port needed - accessed internally via mitmproxy - volumes: - - ./nginx-tls-proxy.conf:/etc/nginx/nginx.conf:ro - - ./.mitmproxy:/certs:ro - depends_on: - - snyk-broker + # 443, like production: the agent gets a port-less serverUri from + # registration (see cortex-fake) and must default the port itself. + GRPC_PORT: 443 + HTTP_PORT: 8080 + SERVER_ID: test-server-1 + DISPATCH_TIMEOUT: 60s + HEARTBEAT_INTERVAL: 10s + ENV: development + TOKEN: ${TOKEN:-0e481b34-76ac-481a-a92f-c94a6cf6f6c1} networks: - - external # TLS proxy is on external network + - external # grpc-tunnel-server is on external network only mitmproxy: image: mitmproxy/mitmproxy:12 @@ -38,7 +31,7 @@ services: - ./mitmproxy_addon_header.py:/home/mitmproxy/addon.py # Use confdir=/certs so mitmproxy uses our CA files from /certs instead of default location # This avoids the entrypoint script trying to chown files (which fails in CI) - command: mitmdump --set confdir=/certs -s /home/mitmproxy/addon.py --set ssl_verify_upstream_trusted_ca=/certs/combined-ca-bundle.crt + command: mitmdump --set confdir=/certs -s /home/mitmproxy/addon.py healthcheck: test: ["CMD", "python3", "-c", "import socket; s=socket.socket(); s.connect(('localhost', 8080)); s.close()"] interval: 2s @@ -56,7 +49,7 @@ services: volumes: - .:/src - ./.mitmproxy:/certs - - ../../server/snykbroker/acceptfile:/agent/plugins + - ../../server/acceptfile:/agent/plugins environment: CORTEX_API_TOKEN: fake-token CORTEX_API_BASE_URL: http://cortex-fake:8081 @@ -66,12 +59,23 @@ services: GITLAB_TOKEN: gitlab-test-token PORT: 7433 PLUGIN_DIRS: /agent/plugins + AXON_GRPC_TUNNEL_CONNS: 2 + # No BROKER_SERVER_URL here: the agent must use the serverUri from + # registration, as it does in production. + GRPC_INSECURE: "true" + CORTEX_TENANT_ID: test-tenant + TOKEN: ${TOKEN:-0e481b34-76ac-481a-a92f-c94a6cf6f6c1} env_file: ${ENVFILE:-noproxy.env} - command: relay -f /src/accept-client.json -i github -a axon-test + # --verbose because relay_test.sh asserts on "Tunnel stream + # established", which tunnel_client.go logs at debug: opening a stream is + # routine, so it is deliberately not Info. The proxy-dial line the test + # also greps for is Info, which is why only this assertion broke when the + # stream line was demoted. + command: relay --verbose -f /src/accept-client.json -i github -a axon-test depends_on: mitmproxy: condition: service_healthy - snyk-broker-tls: + grpc-tunnel-server: condition: service_started cortex-fake: condition: service_healthy @@ -85,9 +89,8 @@ services: # For PROXY=1: this is the only network, forcing traffic through mitmproxy # For PROXY=0: docker-compose.noproxy.yml adds external network - python-server: - image: python:3.8-alpine + image: python:3.12-alpine volumes: - /tmp:/tmp command: sh -c "apk add curl && python3 -m http.server 80 -d /tmp" @@ -101,15 +104,15 @@ services: - internal # python-server is a local customer service cortex-fake: - image: golang:1.26.1-alpine + image: golang:1.24-alpine volumes: - .:/src environment: PORT: 8081 - # Default: HTTP for non-proxy mode (direct connection) - # Override in docker-compose.proxy.yml for HTTPS through proxy - BROKER_SERVER_URL: http://snyk-broker:7341 - TOKEN: ${TOKEN:-0e481b34-76ac-481a-a92f-c94a6cf6f6c2} + # Same shape brain-backend returns (https://relay.cortex.io): a scheme + # and no port. + BROKER_SERVER_URL: https://grpc-tunnel-server + TOKEN: ${TOKEN:-0e481b34-76ac-481a-a92f-c94a6cf6f6c1} command: sh -c "apk add curl && cd /src && go run cortex-registration-fake.go" healthcheck: test: ["CMD", "curl", "-f", "http://localhost:8081/healthcheck"] @@ -124,4 +127,4 @@ networks: # Internal network - axon-relay, python-server, cortex-fake # axon-relay can only reach external network via mitmproxy external: - # External network - snyk-broker (mimics Cortex side) + # External network - grpc-tunnel-server (mimics Cortex side) diff --git a/agent/test/relay/generate-certs.sh b/agent/test/relay/generate-certs.sh deleted file mode 100755 index f8aa8bbf..00000000 --- a/agent/test/relay/generate-certs.sh +++ /dev/null @@ -1,67 +0,0 @@ -#!/bin/bash -# Generate TLS certificates for the relay E2E test -# This creates a broker server cert signed by the mitmproxy CA - -set -e - -CERT_DIR="$(dirname "$0")/.mitmproxy" - -# Check if mitmproxy CA exists (created by mitmproxy on first run) -if [ ! -f "$CERT_DIR/mitmproxy-ca.pem" ]; then - echo "Error: mitmproxy CA not found at $CERT_DIR/mitmproxy-ca.pem" - echo "Run mitmproxy once to generate the CA, or copy existing certs." - exit 1 -fi - -cd "$CERT_DIR" - -# Always create combined CA bundle (needed even if broker certs exist) -# This must be done on each machine since system CAs differ -echo "Creating combined CA bundle..." -if [ -f /etc/ssl/certs/ca-certificates.crt ]; then - # Linux (Debian/Ubuntu) - cat /etc/ssl/certs/ca-certificates.crt mitmproxy-ca-cert.pem > combined-ca-bundle.crt -elif [ -f /etc/pki/tls/certs/ca-bundle.crt ]; then - # Linux (RHEL/CentOS) - cat /etc/pki/tls/certs/ca-bundle.crt mitmproxy-ca-cert.pem > combined-ca-bundle.crt -elif [ -f /etc/ssl/cert.pem ]; then - # macOS - cat /etc/ssl/cert.pem mitmproxy-ca-cert.pem > combined-ca-bundle.crt -else - echo "Warning: Could not find system CA bundle, using only mitmproxy CA" - cp mitmproxy-ca-cert.pem combined-ca-bundle.crt -fi -echo "Combined CA bundle: $(grep -c 'BEGIN CERTIFICATE' combined-ca-bundle.crt) certificates" - -# Check if broker cert already exists -if [ -f "$CERT_DIR/broker-server-cert.pem" ] && [ -f "$CERT_DIR/broker-server-key.pem" ]; then - echo "Broker certificates already exist, skipping generation" - exit 0 -fi - -echo "Generating broker server certificates..." - -# Extract mitmproxy CA key -openssl pkey -in mitmproxy-ca.pem -out mitmproxy-ca-key.pem 2>/dev/null - -# Generate broker server key -openssl genrsa -out broker-server-key.pem 2048 2>/dev/null - -# Create broker server CSR -openssl req -new -key broker-server-key.pem -out broker-server.csr \ - -subj "/CN=snyk-broker-tls/O=test" 2>/dev/null - -# Create extensions file with SAN -cat > broker-server-ext.cnf << 'EOF' -subjectAltName = DNS:snyk-broker-tls, DNS:snyk-broker, DNS:localhost -EOF - -# Sign with mitmproxy CA -openssl x509 -req -in broker-server.csr -CA mitmproxy-ca-cert.pem -CAkey mitmproxy-ca-key.pem \ - -CAcreateserial -out broker-server-cert.pem -days 3650 -extfile broker-server-ext.cnf 2>/dev/null - -# Clean up temp files -rm -f broker-server.csr broker-server-ext.cnf mitmproxy-ca-key.pem - -echo "Certificates generated successfully:" -openssl x509 -in broker-server-cert.pem -noout -subject -issuer diff --git a/agent/test/relay/nginx-tls-proxy.conf b/agent/test/relay/nginx-tls-proxy.conf deleted file mode 100644 index d863c1e9..00000000 --- a/agent/test/relay/nginx-tls-proxy.conf +++ /dev/null @@ -1,42 +0,0 @@ -events { - worker_connections 1024; -} - -http { - # WebSocket upgrade support - map $http_upgrade $connection_upgrade { - default upgrade; - '' close; - } - - server { - listen 7341 ssl; - server_name snyk-broker-tls; - - ssl_certificate /certs/broker-server-cert.pem; - ssl_certificate_key /certs/broker-server-key.pem; - ssl_protocols TLSv1.2 TLSv1.3; - - location / { - proxy_pass http://snyk-broker:7341; - proxy_http_version 1.1; - - # WebSocket support - proxy_set_header Upgrade $http_upgrade; - proxy_set_header Connection $connection_upgrade; - - # Standard proxy headers - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; - - # Disable buffering for WebSocket - proxy_buffering off; - - # Timeouts for long-lived WebSocket connections - proxy_read_timeout 86400s; - proxy_send_timeout 86400s; - } - } -} diff --git a/agent/test/relay/proxy.env b/agent/test/relay/proxy.env index 11f6a636..898bd29f 100644 --- a/agent/test/relay/proxy.env +++ b/agent/test/relay/proxy.env @@ -2,7 +2,6 @@ HTTP_PROXY=http://mitmproxy:8080 HTTPS_PROXY=http://mitmproxy:8080 NO_PROXY=cortex-fake,python-server,localhost,127.0.0.1 CA_CERT_PATH=/certs/mitmproxy-ca.pem -ENABLE_RELAY_REFLECTOR=all PROXY_STRICT_MODE=true HEADER_PROXY_VALUE=github-proxy LOG_LEVEL=debug \ No newline at end of file diff --git a/agent/test/relay/relay_scenarios.sh b/agent/test/relay/relay_scenarios.sh index 97066d65..b0eb8e1f 100644 --- a/agent/test/relay/relay_scenarios.sh +++ b/agent/test/relay/relay_scenarios.sh @@ -1,23 +1,16 @@ -# Shared end-to-end scenarios, run identically against both relay transports. -# -# snyk-broker and the gRPC tunnel are meant to be interchangeable: the same -# accept files, the same rewriting, the same credential injection. The only -# way that claim stays true is if the same assertions run against both, so -# these live here rather than being copied into each transport's script. -# They had already drifted once — the gRPC copy had quietly lost the agent -# endpoint and GitLab credential-injection checks. +# End-to-end relay scenarios: accept file matching, rewriting and credential +# injection, checked through the tunnel. relay_test.sh sources this file. # # Contract for callers, set before sourcing: -# DISPATCH_URL ingress for this transport, ending in /broker/ +# DISPATCH_URL tunnel server ingress, ending in /broker/ # TOKEN the broker token # PROXY 1 when running the proxied topology -# EXPECT_RELAY_MODE the transport this script drives, as __axon/info reports it +# EXPECT_RELAY_MODE the transport __axon/info must report # COMPOSE_FILES compose -f flags, for log dumps on failure # curlw a curl wrapper that fails the run on transport errors # -# Scenarios that are genuinely transport-specific — snyk's raw WebSocket -# tunnel, the gRPC stream handshake, which container to SIGKILL — stay in the -# per-transport scripts. Everything here must hold for both. +# Scenarios specific to the test topology (the gRPC stream handshake, which +# container to SIGKILL) stay in relay_test.sh. # Dumps whatever context is likely to explain a failure, then exits. scenario_fail() { @@ -50,9 +43,7 @@ scenario_axon_endpoints() { fi # The backend reads these to track what the fleet is actually running, so - # they have to be right per transport rather than merely present. Asserting - # the transport here is what makes this scenario differ between the two - # scripts that share it — everything else must match. + # they have to be right rather than merely present. local mode build mode=$(echo "$info" | jq -r '.relay_mode') if [ "$mode" != "$EXPECT_RELAY_MODE" ]; then @@ -100,11 +91,11 @@ scenario_unclean_path_reaches_agent() { done } -# A payload large enough to be split across frames in either transport, so +# A payload large enough to be split across frames, so # chunking and reassembly are covered rather than assumed. Compared by # checksum: a corrupted byte anywhere fails. # -# $1 optional extra curl args (snyk-broker needs a response-mode header). +# $1 optional extra curl args. scenario_binary_passthrough() { echo "Checking binary file relay passthrough..." local name original downloaded orig_sum dl_sum diff --git a/agent/test/relay/relay_test.grpc.sh b/agent/test/relay/relay_test.grpc.sh deleted file mode 100755 index ec9cb1fc..00000000 --- a/agent/test/relay/relay_test.grpc.sh +++ /dev/null @@ -1,250 +0,0 @@ -#!/bin/bash -set -e - -# End-to-end test for the gRPC tunnel relay stack. -# This mirrors relay_test.sh but uses the gRPC tunnel server instead of snyk-broker. -# -# Components: -# - [server-side] grpc-tunnel-server: gRPC tunnel server with HTTP dispatch endpoint -# - [server-side] cortex-fake: mimics the Cortex registration API -# - [client-side] axon-relay: agent in gRPC tunnel mode (RELAY_MODE=grpc-tunnel) -# - [client-side] python-server: mimics an API that Cortex is calling out to -# - [optional] mitmproxy: HTTP proxy for proxy-mode testing - -export TOKEN=0e481b34-76ac-481a-a92f-c94a6cf6f6c1 -# Host ports are kept BELOW the ephemeral range (32768-60999 on Linux, -# 49152-65535 on macOS). The test opens many outbound connections, and one of -# them transiently claiming a listener's port as its source port makes the -# next `compose up` fail with "address already in use". load_test.sh hit this -# and pins its ports the same way. -export GRPC_PORT=17152 -export HTTP_PORT=17180 - -if [ "$PROXY" == "1" ]; then - echo "TESTING WITH PROXY" - export ENVFILE=proxy.env - # Base docker-compose.grpc.yml has axon-relay on internal network only - # This enforces that gRPC connections MUST go through mitmproxy - export COMPOSE_FILES="-f docker-compose.grpc.yml" -else - echo "TESTING WITHOUT PROXY" - export ENVFILE=noproxy.env - # Add external network so axon-relay can connect directly to grpc-tunnel-server - export COMPOSE_FILES="-f docker-compose.grpc.yml -f docker-compose.grpc.noproxy.yml" - - # Also set the HTTP_PORT to a different value to ensure we respect that port - export HTTP_PORT=17280 -fi - -function cleanup { - echo "Cleanup: Stopping docker-compose" - docker compose $COMPOSE_FILES down - rm -f /tmp/token-* /tmp/axon-test-token /tmp/binary-test-*.bin /tmp/binary-test-*.downloaded -} -trap cleanup EXIT - -echo "Starting docker compose (gRPC tunnel)..." -docker compose $COMPOSE_FILES up -d -sleep 5 - -function get_container_status { - result_status=$(docker inspect -f '{{.State.Status}}' $1) - echo "Status $1 = $result_status" >&2 - echo $result_status -} - -if [ -n "$DEBUG" ]; then - echo "Debug mode enabled, sleeping indefinitely" - while true; do - sleep 5 - done -fi - -COUNTER=30 -SERVER_STATUS=$(get_container_status relay-grpc-tunnel-server-1) -AXON_STATUS=$(get_container_status relay-axon-relay-1) - -while [ "$SERVER_STATUS" != "running" ] || [ "$AXON_STATUS" != "running" ]; do - if [ $COUNTER -eq 0 ]; then - echo "Containers did not start in time" - docker compose $COMPOSE_FILES logs - exit 1 - fi - - echo "Waiting for containers to start" - sleep 1 - SERVER_STATUS=$(get_container_status relay-grpc-tunnel-server-1) - AXON_STATUS=$(get_container_status relay-axon-relay-1) - COUNTER=$((COUNTER-1)) -done - -# Wait for grpc-tunnel-server healthz (exposed to host via HTTP_PORT). -echo "Waiting for grpc-tunnel-server healthz..." -COUNTER=30 -while ! curl -sf http://localhost:$HTTP_PORT/healthz > /dev/null 2>&1; do - if [ $COUNTER -eq 0 ]; then - echo "grpc-tunnel-server healthz did not pass in time" - docker compose $COMPOSE_FILES logs grpc-tunnel-server - exit 1 - fi - sleep 1 - COUNTER=$((COUNTER-1)) -done -echo "grpc-tunnel-server is healthy" - -# Wait for at least one tunnel stream to register (agent connects via gRPC). -echo "Waiting for tunnel stream registration..." -COUNTER=60 -while true; do - HEALTH=$(curl -sf http://localhost:$HTTP_PORT/healthz 2>/dev/null || echo '{}') - STREAMS=$(echo "$HEALTH" | grep -o '"streams":[0-9]*' | grep -o '[0-9]*' || echo "0") - if [ "$STREAMS" -gt 0 ]; then - echo "Tunnel has $STREAMS active stream(s)" - break - fi - if [ $COUNTER -eq 0 ]; then - echo "No tunnel streams registered in time" - echo "Server health: $HEALTH" - docker compose $COMPOSE_FILES logs - exit 1 - fi - sleep 1 - COUNTER=$((COUNTER-1)) -done - -real_curl=$(which curl) - -function curlw { - [ -n "$DEBUG" ] && echo "Executing: $real_curl $@" >&2 - if ! curl_result=$($real_curl -s "$@" 2>&1); then - echo "Curl command failed: $@ ==> $curl_result" - exit 1 - else - [ -n "$DEBUG" ] && echo "curl $@ ==> $curl_result" >&2 - fi - echo "$curl_result" -} - -# Ingress for this transport: the tunnel server's HTTP dispatch port. -# Everything the shared scenarios assert is addressed relative to it, so the -# same checks run here as against snyk-broker. -export DISPATCH_URL="http://localhost:$HTTP_PORT/broker/$TOKEN" -export EXPECT_RELAY_MODE=grpc-tunnel -source ./relay_scenarios.sh - -run_shared_scenarios - -if [ "$PROXY" == "1" ]; then - # The point of the proxied topology for this transport: the agent's - # OUTBOUND gRPC dial has to work through an HTTP proxy, via CONNECT. - # That is the deployment shape most customers actually have, and it is - # the one thing snyk-broker's websocket path cannot tell us anything - # about. - # - # Network isolation already makes it structurally true — axon-relay is on - # the internal network only, so it cannot reach the tunnel server except - # through mitmproxy. But asserting only on "a stream appeared" would - # report a proxy regression as a confusing connection timeout. These two - # checks separate the questions: did we dial through the proxy, and did - # the tunnel then work. - echo "Checking gRPC outbound connection through the HTTP proxy..." - axon_logs=$(docker compose $COMPOSE_FILES logs axon-relay 2>&1) - - if ! echo "$axon_logs" | grep -q "gRPC connection dialed through HTTP proxy"; then - echo "FAIL: Agent did not route its gRPC dial through the HTTP proxy" - echo " Expected 'gRPC connection dialed through HTTP proxy' in the agent logs." - echo " Without it, any stream below connected by some other path." - echo "=== Axon Relay Logs (last 50) ===" - echo "$axon_logs" | tail -50 - exit 1 - fi - echo "Success: gRPC dial routed through the HTTP proxy (CONNECT)" - - if ! echo "$axon_logs" | grep -q "Tunnel stream established"; then - echo "FAIL: Expected 'Tunnel stream established' in agent logs but not found" - echo "=== Axon Relay Logs (last 50) ===" - echo "$axon_logs" | tail -50 - exit 1 - fi - echo "Success: gRPC tunnel stream established over the proxied connection" -fi - -echo "=== gRPC tunnel reconnection after SIGKILL ===" - -# Force-kill the grpc-tunnel-server container to simulate a non-graceful disconnect. -# This tears down the TCP connection without sending a gRPC GoAway frame, which -# is what happens when the tunnel server crashes or the network drops. -echo "Force-killing grpc-tunnel-server container..." -docker kill --signal=KILL relay-grpc-tunnel-server-1 - -# Wait for the container to be fully dead -sleep 2 -SERVER_STATUS=$(get_container_status relay-grpc-tunnel-server-1) -if [ "$SERVER_STATUS" == "running" ]; then - echo "FAIL: grpc-tunnel-server should be dead after SIGKILL" - exit 1 -fi -echo "grpc-tunnel-server is stopped (status=$SERVER_STATUS)" - -# Restart the tunnel server -echo "Restarting grpc-tunnel-server container..." -docker compose $COMPOSE_FILES up -d grpc-tunnel-server - -# Wait for the tunnel server to be healthy again -COUNTER=30 -while [ $COUNTER -gt 0 ]; do - SERVER_STATUS=$(get_container_status relay-grpc-tunnel-server-1) - if [ "$SERVER_STATUS" == "running" ]; then - if curl -s -f http://localhost:$HTTP_PORT/healthz > /dev/null 2>&1; then - break - fi - fi - echo "Waiting for grpc-tunnel-server to be healthy ($COUNTER)..." - sleep 1 - COUNTER=$((COUNTER-1)) -done - -if [ $COUNTER -eq 0 ]; then - echo "FAIL: grpc-tunnel-server did not become healthy in time" - docker compose $COMPOSE_FILES logs grpc-tunnel-server - exit 1 -fi -echo "grpc-tunnel-server is back up" - -# Give the axon relay time to detect the disconnect and reconnect. -# The gRPC tunnel client uses exponential backoff so 15s should be enough -# for the first reconnect attempt. -echo "Waiting for axon relay to reconnect..." -COUNTER=60 -while [ $COUNTER -gt 0 ]; do - HEALTH=$(curl -sf http://localhost:$HTTP_PORT/healthz 2>/dev/null || echo '{}') - STREAMS=$(echo "$HEALTH" | grep -o '"streams":[0-9]*' | grep -o '[0-9]*' || echo "0") - if [ "$STREAMS" -gt 0 ]; then - break - fi - echo "Waiting for tunnel stream re-establishment ($COUNTER)..." - sleep 1 - COUNTER=$((COUNTER-1)) -done - -if [ $COUNTER -eq 0 ]; then - echo "FAIL: Tunnel stream did not re-establish in time" - docker compose $COMPOSE_FILES logs --tail=80 axon-relay - exit 1 -fi -echo "Tunnel re-established with $STREAMS active stream(s)" - -# Now verify the relay is working again by sending a request through the tunnel -FILENAME="token-reconnect-$(date +%s)" -echo "$TOKEN" > /tmp/$FILENAME -result=$(curlw $DISPATCH_URL/$FILENAME) - -if [ "$result" != "$TOKEN" ]; then - echo "FAIL: Expected $TOKEN after reconnect, got '$result'" - echo "=== Axon Relay Logs (last 80) ===" - docker compose $COMPOSE_FILES logs --tail=80 axon-relay - exit 1 -fi -echo "Success: gRPC tunnel passthrough works after SIGKILL + restart" - -echo "Success! gRPC tunnel e2e test passed!" diff --git a/agent/test/relay/relay_test.sh b/agent/test/relay/relay_test.sh index f5a26288..4549fc10 100755 --- a/agent/test/relay/relay_test.sh +++ b/agent/test/relay/relay_test.sh @@ -1,216 +1,246 @@ -#! /bin/bash +#!/bin/bash set -e -# This is a full end-to-end test of the relay broker system that does the following: -# 1. Setups a a docker compose with the these components -# - [server-side] snyk broker, which mimics to broker that lives on the cortex side -# - [server-side] a go webserver that mimics the cortex registration API -# - [client-side] A axon relay, which an instance of relay in customer's data enviroment -# - [client-side] a python webserver that mimics an API that cortex is calling out to -# 2. Starts the server-side components to mimic the cortex API -# 3. Starts the client-side components to mimic the customer's data enviroment -# 4. Sends a request to the snyk broker, which should end up calling the python API +# End-to-end test for the gRPC tunnel relay stack. # -# The python API simply reads a file that we write to /tmp which includes the token -# Once this is validated, the test is considered successful and the docker-compose is stopped +# Components: +# - [server-side] grpc-tunnel-server: gRPC tunnel server with HTTP dispatch endpoint +# - [server-side] cortex-fake: mimics the Cortex registration API +# - [client-side] axon-relay: the agent +# - [client-side] python-server: mimics an API that Cortex is calling out to +# - [optional] mitmproxy: HTTP proxy for proxy-mode testing -# Start a snyk broker, capture the ID export TOKEN=0e481b34-76ac-481a-a92f-c94a6cf6f6c1 # Host ports are kept BELOW the ephemeral range (32768-60999 on Linux, # 49152-65535 on macOS). The test opens many outbound connections, and one of # them transiently claiming a listener's port as its source port makes the # next `compose up` fail with "address already in use". load_test.sh hit this # and pins its ports the same way. -export SERVER_PORT=17341 +export GRPC_PORT=17152 +export HTTP_PORT=17180 -if [ "$PROXY" == "1" ] -then +if [ "$PROXY" == "1" ]; then echo "TESTING WITH PROXY" export ENVFILE=proxy.env # Base docker-compose.yml has axon-relay on internal network only - # This enforces that WebSocket connections MUST go through mitmproxy - # docker-compose.proxy.yml enables HTTPS broker connection through proxy (TLS-through-proxy) - export COMPOSE_FILES="-f docker-compose.yml -f docker-compose.proxy.yml" - - # Generate TLS certificates if needed (for CI environments) - ./generate-certs.sh - - # Verify required files exist - echo "=== Verifying certificate files ===" - ls -la .mitmproxy/*.pem .mitmproxy/*.crt 2>/dev/null || echo "Warning: some cert files missing" - if [ ! -f .mitmproxy/combined-ca-bundle.crt ]; then - echo "ERROR: combined-ca-bundle.crt not found!" - exit 1 - fi - echo "combined-ca-bundle.crt size: $(wc -c < .mitmproxy/combined-ca-bundle.crt) bytes" + # This enforces that gRPC connections MUST go through mitmproxy + export COMPOSE_FILES="-f docker-compose.yml" else echo "TESTING WITHOUT PROXY" export ENVFILE=noproxy.env - # Add external network so axon-relay can connect directly to snyk-broker + # Add external network so axon-relay can connect directly to grpc-tunnel-server export COMPOSE_FILES="-f docker-compose.yml -f docker-compose.noproxy.yml" - # just for fun also set the HTTP_PORT to a different value to ensure - # we respect that port as well - export HTTP_PORT=17080 + # Also set the HTTP_PORT to a different value to ensure we respect that port + export HTTP_PORT=17280 fi -# Create an exit trap to stop the broker when the script exits function cleanup { - echo "Cleanup: Stopping docker-compose" - docker compose $COMPOSE_FILES down - rm -f /tmp/token-* /tmp/axon-test-token /tmp/binary-test-*.bin /tmp/binary-test-*.downloaded + echo "Cleanup: Stopping docker-compose" + docker compose $COMPOSE_FILES down + rm -f /tmp/token-* /tmp/axon-test-token /tmp/binary-test-*.bin /tmp/binary-test-*.downloaded } trap cleanup EXIT -echo "Starting docker compose ..." -if ! docker compose $COMPOSE_FILES up -d; then - echo "=== Docker compose failed, checking mitmproxy logs ===" - docker compose $COMPOSE_FILES logs mitmproxy 2>&1 || true - echo "=== Checking mounted files in mitmproxy container ===" - docker compose $COMPOSE_FILES run --rm --entrypoint="" mitmproxy ls -la /home/mitmproxy/.mitmproxy/ 2>&1 || true - exit 1 -fi +echo "Starting docker compose (gRPC tunnel)..." +docker compose $COMPOSE_FILES up -d sleep 5 -# Loop until healthcheck for server broker passes function get_container_status { result_status=$(docker inspect -f '{{.State.Status}}' $1) echo "Status $1 = $result_status" >&2 echo $result_status } -# Now we send a request to the server broker, and expect it to be relayed to the axon relay out -# to a local http port - -if [ -n "$DEBUG" ] -then - echo "Debug mode enabled, sleeping indefinitely" - while true - do - sleep 5 - done +if [ -n "$DEBUG" ]; then + echo "Debug mode enabled, sleeping indefinitely" + while true; do + sleep 5 + done fi COUNTER=30 -SNYK_STATUS=$(get_container_status relay-snyk-broker-1) +SERVER_STATUS=$(get_container_status relay-grpc-tunnel-server-1) AXON_STATUS=$(get_container_status relay-axon-relay-1) - -while [ "$SNYK_STATUS" != "running" ] || [ "$AXON_STATUS" != "running" ]; do - + +while [ "$SERVER_STATUS" != "running" ] || [ "$AXON_STATUS" != "running" ]; do if [ $COUNTER -eq 0 ]; then echo "Containers did not start in time" docker compose $COMPOSE_FILES logs exit 1 fi - + echo "Waiting for containers to start" sleep 1 - SNYK_STATUS=$(get_container_status relay-snyk-broker-1) + SERVER_STATUS=$(get_container_status relay-grpc-tunnel-server-1) AXON_STATUS=$(get_container_status relay-axon-relay-1) COUNTER=$((COUNTER-1)) done +# Wait for grpc-tunnel-server healthz (exposed to host via HTTP_PORT). +echo "Waiting for grpc-tunnel-server healthz..." +COUNTER=30 +while ! curl -sf http://localhost:$HTTP_PORT/healthz > /dev/null 2>&1; do + if [ $COUNTER -eq 0 ]; then + echo "grpc-tunnel-server healthz did not pass in time" + docker compose $COMPOSE_FILES logs grpc-tunnel-server + exit 1 + fi + sleep 1 + COUNTER=$((COUNTER-1)) +done +echo "grpc-tunnel-server is healthy" + +# Wait for at least one tunnel stream to register (agent connects via gRPC). +echo "Waiting for tunnel stream registration..." +COUNTER=60 +while true; do + HEALTH=$(curl -sf http://localhost:$HTTP_PORT/healthz 2>/dev/null || echo '{}') + STREAMS=$(echo "$HEALTH" | grep -o '"streams":[0-9]*' | grep -o '[0-9]*' || echo "0") + if [ "$STREAMS" -gt 0 ]; then + echo "Tunnel has $STREAMS active stream(s)" + break + fi + if [ $COUNTER -eq 0 ]; then + echo "No tunnel streams registered in time" + echo "Server health: $HEALTH" + docker compose $COMPOSE_FILES logs + exit 1 + fi + sleep 1 + COUNTER=$((COUNTER-1)) +done + real_curl=$(which curl) function curlw { [ -n "$DEBUG" ] && echo "Executing: $real_curl $@" >&2 - if ! curl_result=$($real_curl -s -H "x-broker-ws-response: true" "$@" 2>&1) - then + if ! curl_result=$($real_curl -s "$@" 2>&1); then echo "Curl command failed: $@ ==> $curl_result" exit 1 - else + else [ -n "$DEBUG" ] && echo "curl $@ ==> $curl_result" >&2 fi echo "$curl_result" } -# Ingress for this transport. Everything the shared scenarios assert is -# addressed relative to it, so the same checks run against both relays. -export DISPATCH_URL="http://localhost:$SERVER_PORT/broker/$TOKEN" -export EXPECT_RELAY_MODE=snyk-broker +# Ingress: the tunnel server's HTTP dispatch port. Everything the shared +# scenarios assert is addressed relative to it. +export DISPATCH_URL="http://localhost:$HTTP_PORT/broker/$TOKEN" +export EXPECT_RELAY_MODE=grpc-tunnel source ./relay_scenarios.sh -# snyk-broker only returns a relayed body when asked for a raw response. -run_shared_scenarios -H "x-broker-ws-response: true" +run_shared_scenarios if [ "$PROXY" == "1" ]; then - # Transport-specific: proves the reflector established a real WebSocket - # tunnel rather than falling back to primus's XHR polling. Network - # isolation enforces it — axon-relay can only reach snyk-broker through - # mitmproxy, so a bypass fails at the network level instead of silently - # degrading to a slower transport. - echo "Checking WebSocket tunnel..." + # The point of the proxied topology: the agent's + # OUTBOUND gRPC dial has to work through an HTTP proxy, via CONNECT. + # That is the deployment shape most customers actually have. + # + # Network isolation already makes it structurally true — axon-relay is on + # the internal network only, so it cannot reach the tunnel server except + # through mitmproxy. But asserting only on "a stream appeared" would + # report a proxy regression as a confusing connection timeout. These two + # checks separate the questions: did we dial through the proxy, and did + # the tunnel then work. + echo "Checking gRPC outbound connection through the HTTP proxy..." axon_logs=$(docker compose $COMPOSE_FILES logs axon-relay 2>&1) - if ! echo "$axon_logs" | grep -q "WebSocket tunnel established"; then - echo "FAIL: Expected 'WebSocket tunnel established' in reflector logs but not found" - echo " The broker client may not be upgrading to raw WebSocket (staying on XHR polling)" + + if ! echo "$axon_logs" | grep -q "gRPC connection dialed through HTTP proxy"; then + echo "FAIL: Agent did not route its gRPC dial through the HTTP proxy" + echo " Expected 'gRPC connection dialed through HTTP proxy' in the agent logs." + echo " Without it, any stream below connected by some other path." + echo "=== Axon Relay Logs (last 50) ===" + echo "$axon_logs" | tail -50 + exit 1 + fi + echo "Success: gRPC dial routed through the HTTP proxy (CONNECT)" + + if ! echo "$axon_logs" | grep -q "Tunnel stream established"; then + echo "FAIL: Expected 'Tunnel stream established' in agent logs but not found" echo "=== Axon Relay Logs (last 50) ===" echo "$axon_logs" | tail -50 exit 1 fi - echo "Success: WebSocket tunnel established through reflector" + echo "Success: gRPC tunnel stream established over the proxied connection" fi -echo "=== Broker reconnection after SIGKILL ===" +echo "=== gRPC tunnel reconnection after SIGKILL ===" -# Force-kill the snyk-broker container to simulate a non-graceful disconnect. -# This tears down the TCP connection without sending a WS close frame, which -# is what happens when the broker server crashes or the network drops. -echo "Force-killing snyk-broker container..." -docker kill --signal=KILL relay-snyk-broker-1 +# Force-kill the grpc-tunnel-server container to simulate a non-graceful disconnect. +# This tears down the TCP connection without sending a gRPC GoAway frame, which +# is what happens when the tunnel server crashes or the network drops. +echo "Force-killing grpc-tunnel-server container..." +docker kill --signal=KILL relay-grpc-tunnel-server-1 # Wait for the container to be fully dead sleep 2 -BROKER_STATUS=$(get_container_status relay-snyk-broker-1) -if [ "$BROKER_STATUS" == "running" ]; then - echo "FAIL: snyk-broker should be dead after SIGKILL" +SERVER_STATUS=$(get_container_status relay-grpc-tunnel-server-1) +if [ "$SERVER_STATUS" == "running" ]; then + echo "FAIL: grpc-tunnel-server should be dead after SIGKILL" exit 1 fi -echo "snyk-broker is stopped (status=$BROKER_STATUS)" +echo "grpc-tunnel-server is stopped (status=$SERVER_STATUS)" -# Restart the broker server -echo "Restarting snyk-broker container..." -docker compose up -d snyk-broker +# Restart the tunnel server +echo "Restarting grpc-tunnel-server container..." +docker compose $COMPOSE_FILES up -d grpc-tunnel-server -# Wait for the broker to be healthy again +# Wait for the tunnel server to be healthy again COUNTER=30 while [ $COUNTER -gt 0 ]; do - BROKER_STATUS=$(get_container_status relay-snyk-broker-1) - if [ "$BROKER_STATUS" == "running" ]; then - # Also check the healthcheck endpoint - if curl -s -f http://localhost:$SERVER_PORT/healthcheck > /dev/null 2>&1; then + SERVER_STATUS=$(get_container_status relay-grpc-tunnel-server-1) + if [ "$SERVER_STATUS" == "running" ]; then + if curl -s -f http://localhost:$HTTP_PORT/healthz > /dev/null 2>&1; then break fi fi - echo "Waiting for snyk-broker to be healthy ($COUNTER)..." + echo "Waiting for grpc-tunnel-server to be healthy ($COUNTER)..." sleep 1 COUNTER=$((COUNTER-1)) done if [ $COUNTER -eq 0 ]; then - echo "FAIL: snyk-broker did not become healthy in time" - docker compose logs snyk-broker + echo "FAIL: grpc-tunnel-server did not become healthy in time" + docker compose $COMPOSE_FILES logs grpc-tunnel-server exit 1 fi -echo "snyk-broker is back up" +echo "grpc-tunnel-server is back up" # Give the axon relay time to detect the disconnect and reconnect. -# The relay uses exponential backoff (5s, 10s, ...) so 15s should be enough +# The gRPC tunnel client uses exponential backoff so 15s should be enough # for the first reconnect attempt. -echo "Waiting 15s for axon relay to reconnect..." -sleep 15 +echo "Waiting for axon relay to reconnect..." +COUNTER=60 +while [ $COUNTER -gt 0 ]; do + HEALTH=$(curl -sf http://localhost:$HTTP_PORT/healthz 2>/dev/null || echo '{}') + STREAMS=$(echo "$HEALTH" | grep -o '"streams":[0-9]*' | grep -o '[0-9]*' || echo "0") + if [ "$STREAMS" -gt 0 ]; then + break + fi + echo "Waiting for tunnel stream re-establishment ($COUNTER)..." + sleep 1 + COUNTER=$((COUNTER-1)) +done + +if [ $COUNTER -eq 0 ]; then + echo "FAIL: Tunnel stream did not re-establish in time" + docker compose $COMPOSE_FILES logs --tail=80 axon-relay + exit 1 +fi +echo "Tunnel re-established with $STREAMS active stream(s)" -# Now verify the relay is working again by sending a request through the broker +# Now verify the relay is working again by sending a request through the tunnel FILENAME="token-reconnect-$(date +%s)" echo "$TOKEN" > /tmp/$FILENAME -result=$(curlw http://localhost:$SERVER_PORT/broker/$TOKEN/$FILENAME) +result=$(curlw $DISPATCH_URL/$FILENAME) if [ "$result" != "$TOKEN" ]; then echo "FAIL: Expected $TOKEN after reconnect, got '$result'" echo "=== Axon Relay Logs (last 80) ===" - docker compose logs --tail=80 axon-relay + docker compose $COMPOSE_FILES logs --tail=80 axon-relay exit 1 fi -echo "Success: Broker passthrough works after SIGKILL + restart" +echo "Success: gRPC tunnel passthrough works after SIGKILL + restart" -echo "Success! Done!" \ No newline at end of file +echo "Success! gRPC tunnel e2e test passed!" diff --git a/agent/test/validate_filters.sh b/agent/test/validate_filters.sh index 4a92b5a3..fea89dd8 100755 --- a/agent/test/validate_filters.sh +++ b/agent/test/validate_filters.sh @@ -5,11 +5,11 @@ set -e SOURCE_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -files=$(find $SOURCE_DIR/../server/snykbroker/accept_files -type f -name "accept*.json" | xargs -I{} basename "{}";) +files=$(find $SOURCE_DIR/../server/acceptfile/accept_files -type f -name "accept*.json" | xargs -I{} basename "{}";) # for each file, run the validation for file in $files; do - if ! docker run -v "${SOURCE_DIR}/../:/agent" 3scale/ajv validate -s /agent/test/filter.schema.json -d /agent/server/snykbroker/accept_files/$file; + if ! docker run -v "${SOURCE_DIR}/../:/agent" 3scale/ajv validate -s /agent/test/filter.schema.json -d /agent/server/acceptfile/accept_files/$file; then echo "Validation failed for $file" exit 1 diff --git a/agent/util/proxyconnect.go b/agent/util/proxyconnect.go index 15227a55..42d49fd3 100644 --- a/agent/util/proxyconnect.go +++ b/agent/util/proxyconnect.go @@ -41,9 +41,8 @@ func ProxyAddr(proxyURL *url.URL) string { // DialProxyConnect dials an HTTP proxy and establishes a CONNECT tunnel to // targetAddr, returning a conn positioned just past the proxy's response. -// Shared by the gRPC tunnel dialer and the relay reflector's WebSocket -// proxy so CONNECT mechanics (auth, response handling, buffered bytes) -// live in one place. +// The gRPC tunnel dialer uses it. CONNECT mechanics (auth, response +// handling, buffered bytes) live in one place. // // proxyTLS, when non-nil, wraps the proxy connection itself in TLS // (https:// proxies). handshakeTimeout bounds the CONNECT exchange; <= 0 diff --git a/docker/Dockerfile b/docker/Dockerfile index 59673dd4..1290aa72 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -1,12 +1,3 @@ -# VARIANT selects the image flavor: -# full - the default. Both relay transports: snyk-broker (Node) and grpc-tunnel. -# grpc - go-only. No Node or snyk-broker, and the agent binary is pinned to -# AXON_RELAY_TRANSPORT=grpc-tunnel (see config.ForcedRelayMode). -# Published with a -grpc tag suffix, e.g. cortex-axon-agent:3.1.1-grpc. -# BuildKit only builds the stages the selected variant reaches, so the grpc -# build never runs the Node install at all. -ARG VARIANT=full - # Stage 1: Build the Go agent binary FROM debian:stable-slim AS builder @@ -29,19 +20,10 @@ RUN cd /build-plugins/google-adc && go build -o /plugins/google-adc . COPY agent/. /build/. COPY proto/ /proto/ RUN make -C /build setup proto - -FROM builder AS bin-full RUN cd /build && go build -o /agent/cortex-axon-agent -FROM builder AS bin-grpc -RUN cd /build && go build \ - -ldflags "-X github.com/cortexapps/axon/config.ForcedRelayMode=grpc-tunnel" \ - -o /agent/cortex-axon-agent - -FROM bin-${VARIANT} AS bin - -# Stage 2: Runtime base, shared by both variants -FROM debian:stable-slim AS runtime-base +# Stage 2: Final image +FROM debian:stable-slim WORKDIR /agent # APT_CACHE_BUST participates in buildx's layer cache key for the RUN below. @@ -49,7 +31,7 @@ WORKDIR /agent # force `apt-get update && upgrade` to re-fetch from Debian's archive. Use this # when the scheduled Trivy scan flags OS-package CVEs whose fixes are already # in the archive — the cache is just serving a stale layer. Leaves the rest of -# the build (Go, Node + snyk-broker install) hitting cache as normal. +# the build hitting cache as normal. ARG APT_CACHE_BUST=2026-11-30 # NOTE: build-essential is deliberately NOT installed here. It pulls in a full # C/C++ toolchain whose libc6-dev dependency drags in linux-libc-dev (the Linux @@ -57,8 +39,7 @@ ARG APT_CACHE_BUST=2026-11-30 # kernel CVEs that redden the Trivy scan every day — none of which are # reachable in a container that never runs its own kernel. Nothing in this # image needs a C compiler at runtime: the agent binary is compiled in the -# builder stage, snyk-broker's npm install ships no native addons, and scaffold -# Go apps build with CGO_ENABLED=0 (set below). If a future scaffold genuinely +# builder stage, and scaffold Go apps build with CGO_ENABLED=0 (set below). If a future scaffold genuinely # needs cgo, add a scoped `gcc`/`libc6-dev` layer to that scaffold's Dockerfile # rather than putting the toolchain back into this shared base image. # @@ -90,67 +71,13 @@ ENV PATH="${GOROOT}/bin:${GOPATH}/bin:${PATH}:/agent" # builds working and produces static binaries. ENV CGO_ENABLED=0 -# Variant layers. They sit after the shared base but before the COPYs below, -# so a scaffold or script change does not invalidate the Node install. -FROM runtime-base AS deps-grpc -ENV AXON_RELAY_TRANSPORT=grpc-tunnel - -FROM runtime-base AS deps-full -# Install NodeJS and Snyk Broker -# -# NODE_VERSION is the NodeSource major. Node 20 is end of life and will never -# get the CVE-2026-111497 fix; 22.23.4 has it. NODE_MIN_VERSION, when set, -# fails the build if NodeSource serves anything older, so the image can never -# quietly ship an unpatched 22.x. -ARG NODE_VERSION=22 -ARG NODE_MIN_VERSION=22.23.4 -ENV NODE_VERSION=${NODE_VERSION} - -ARG SNYK_BROKER_VERSION=v1.0.25-axon -# npm is only a build tool here: nothing in the agent or the scaffolds runs npm -# or npx at runtime, the agent just execs the installed `snyk-broker` bin. So -# npm (and npx, which lives inside it) is deleted once the broker is installed. -# It has to happen in this same RUN: the nodejs package itself installs npm -# under /usr/lib/node_modules/npm, and removing it in a later layer would leave -# it in the image's lower layers, where customers' scanners still find it. -# The broker is installed with `npm ci`, so the image gets exactly the -# dependency tree in the broker tag's lockfile. Do not patch dependencies here -# (for example with `npm pkg set`): `npm ci` stops when package.json and the -# lockfile do not agree, so such a pin fails the build. To fix a vulnerable -# dependency, bump it on the `axon` branch of cortexapps/snyk-broker, release a -# new tag, and update SNYK_BROKER_VERSION. -RUN wget -q -O - https://deb.nodesource.com/setup_${NODE_VERSION}.x | bash - && apt-get install -y nodejs && \ - node -e 'const want = process.argv[1]; if (!want) process.exit(0); \ - const have = process.versions.node.split(".").map(Number), min = want.split(".").map(Number); \ - for (let i = 0; i < 3; i++) { if (have[i] !== min[i]) { if (have[i] > min[i]) process.exit(0); \ - console.error(`node ${process.versions.node} < ${want}`); process.exit(1); } }' \ - "${NODE_MIN_VERSION}" && \ - npm install --global npm@11.18.0 typescript@4.9.3 && \ - git clone https://github.com/cortexapps/snyk-broker.git /tmp/snyk-broker && \ - cd /tmp/snyk-broker && \ - git checkout ${SNYK_BROKER_VERSION} && \ - npm ci && \ - cp -r . /usr/local/snyk-broker && \ - cd /usr/local/snyk-broker && \ - npm install --global . && \ - npm prune --omit=dev && \ - rm -rf /tmp/snyk-broker && \ - rm -rf /usr/lib/node_modules/npm /usr/bin/npm /usr/bin/npx /root/.npm - -# Add npm global bin to PATH -ENV PATH="/usr/local/lib/node_modules/.bin:${PATH}" -ENV NODE_OPTIONS=--use-openssl-ca - -# Stage 3: Final image -FROM deps-${VARIANT} - # Copy the built binary from the builder stage -COPY --from=bin /agent/cortex-axon-agent /agent/cortex-axon-agent +COPY --from=builder /agent/cortex-axon-agent /agent/cortex-axon-agent -COPY agent/server/snykbroker/accept_files /agent/accept_files +COPY agent/server/acceptfile/accept_files /agent/accept_files ENV ACCEPTFILE_DIR=/agent/accept_files -COPY agent/server/snykbroker/plugins /agent/plugins +COPY agent/server/acceptfile/plugins /agent/plugins # Joins the shipped scripts; nothing distinguishes them at runtime. COPY --from=builder /plugins/google-adc /agent/plugins/google-adc ENV BUILTIN_PLUGIN_DIR=/agent/plugins diff --git a/docs/design/grpc-tunnel-v2.md b/docs/design/grpc-tunnel-v2.md index 4cc19b40..cdd7b085 100644 --- a/docs/design/grpc-tunnel-v2.md +++ b/docs/design/grpc-tunnel-v2.md @@ -6,6 +6,13 @@ Supersedes: PR #85 (`grpc-tunnel`) wire protocol only; keeps its structural choi Scope: relay-agent transport used by the reflector-style HTTP-forwarding flows Non-scope: handler dispatch (`AxonAgent.Dispatch`), Cortex-API proxy, webhook handlers +> **Update:** snyk-broker mode is removed. The gRPC tunnel is now the only +> transport. This document describes the side-by-side phase, so it still +> refers to `agent/server/snykbroker/`, the reflector and +> `AXON_RELAY_TRANSPORT`. None of these exist now. Registration moved to +> `agent/server/grpctunnel/registration.go`, and the accept-file package +> moved to `agent/server/acceptfile/`. + --- ## 1. Goals diff --git a/examples/relay/helm-chart/README.md b/examples/relay/helm-chart/README.md index 91ad3dbd..8c754832 100644 --- a/examples/relay/helm-chart/README.md +++ b/examples/relay/helm-chart/README.md @@ -63,7 +63,7 @@ The secret should be created like this: kubectl create secret generic axon-ca-cert --from-file=/path/to/my-cert.pem ``` -This will then be mounted into the container and picked up by the agent and the Snyk Broker. +This will then be mounted into the container and picked up by the agent. ## Uninstallation From 896e0b630efd91336cad264bc961cff520ec1feb Mon Sep 17 00:00:00 2001 From: Shawn Burke Date: Thu, 3 Dec 2026 02:27:39 +0000 Subject: [PATCH 2/2] Keep RegistrationInfoResponse.TunnelMode, always grpc-tunnel Code that reads TunnelMode keeps getting a value. Register sets it to grpc-tunnel and ignores the value from Cortex. Co-Authored-By: Claude Opus 5.5 --- agent/server/grpctunnel/registration.go | 7 +++++++ agent/server/grpctunnel/registration_test.go | 22 ++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/agent/server/grpctunnel/registration.go b/agent/server/grpctunnel/registration.go index f14eaa5b..48a3d292 100644 --- a/agent/server/grpctunnel/registration.go +++ b/agent/server/grpctunnel/registration.go @@ -123,6 +123,7 @@ func (r *registration) Register(ctx context.Context, integration common.Integrat if err != nil { return nil, fmt.Errorf("error decoding response body: %v", err) } + rr.TunnelMode = TunnelModeGrpcTunnel return rr, nil case http.StatusUnauthorized: return nil, ErrUnauthorized @@ -136,9 +137,15 @@ func (r *registration) Register(ctx context.Context, integration common.Integrat return nil, &RegistrationError{error: fmt.Errorf("unexpected status code: %d", resp.StatusCode), Message: string(respBody), StatusCode: resp.StatusCode} } +// TunnelModeGrpcTunnel is the only relay mode the agent runs. +const TunnelModeGrpcTunnel = "grpc-tunnel" + type RegistrationInfoResponse struct { ServerUri string `json:"serverUri"` Token string `json:"token"` + // TunnelMode is always "grpc-tunnel", the only mode the agent runs. + // Register sets it and ignores the value from Cortex. + TunnelMode string `json:"tunnelMode,omitempty"` } type registerRequest struct { diff --git a/agent/server/grpctunnel/registration_test.go b/agent/server/grpctunnel/registration_test.go index 85e1b85c..04408026 100644 --- a/agent/server/grpctunnel/registration_test.go +++ b/agent/server/grpctunnel/registration_test.go @@ -41,6 +41,28 @@ func TestRegister_Success(t *testing.T) { require.Equal(t, "http://example.com", resp.ServerUri) } +// TunnelMode is always grpc-tunnel, whatever Cortex sends. +func TestRegister_TunnelModeIsAlwaysGrpcTunnel(t *testing.T) { + for _, tc := range []struct{ name, body string }{ + {"grpc-tunnel", `{"serverUri":"http://example.com","token":"t","tunnelMode":"grpc-tunnel"}`}, + {"snyk-broker", `{"serverUri":"http://example.com","token":"t","tunnelMode":"snyk-broker"}`}, + {"absent", `{"serverUri":"http://example.com","token":"t"}`}, + } { + t.Run(tc.name, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(tc.body)) + })) + defer server.Close() + + reg := NewRegistration(config.AgentConfig{CortexApiBaseUrl: server.URL, CortexApiToken: "test_token"}, nil) + resp, err := reg.Register(context.Background(), common.IntegrationGithub, "alias") + require.NoError(t, err) + require.Equal(t, "grpc-tunnel", resp.TunnelMode) + }) + } +} + func TestRegister_Unauthorized(t *testing.T) { cfg := &config.AgentConfig{