From d26174612f81c08f6363d5157acdc72551c68d0d Mon Sep 17 00:00:00 2001 From: MudassarTariq Date: Thu, 29 Oct 2026 16:21:27 +0500 Subject: [PATCH] fix: patch Steampipe dependencies and verify release binaries --- .github/workflows/checks.yml | 64 +++++++ .github/workflows/release.yml | 19 +- .goreleaser.yml | 6 + CHANGELOG.md | 1 + Makefile | 6 +- README.md | 2 +- go.mod | 22 +-- go.sum | 28 +-- ipgeolocation/client.go | 5 + ipgeolocation/client_test.go | 164 ++++++++++++++++++ ipgeolocation/http_integration_test.go | 126 ++++++++++++++ ipgeolocation/plugin_test.go | 77 ++++++++ postman/mocks/ipgeolocation/config.yaml | 7 + postman/mocks/ipgeolocation/default.js | 24 +++ .../steampipe/simulation.context.yaml | 37 ++++ postman/simulations/steampipe/simulation.yaml | 10 ++ scripts/test-http.cjs | 66 +++++++ 17 files changed, 632 insertions(+), 32 deletions(-) create mode 100644 .github/workflows/checks.yml create mode 100644 ipgeolocation/client_test.go create mode 100644 ipgeolocation/http_integration_test.go create mode 100644 ipgeolocation/plugin_test.go create mode 100644 postman/mocks/ipgeolocation/config.yaml create mode 100644 postman/mocks/ipgeolocation/default.js create mode 100644 postman/simulations/steampipe/simulation.context.yaml create mode 100644 postman/simulations/steampipe/simulation.yaml create mode 100644 scripts/test-http.cjs diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml new file mode 100644 index 0000000..f2cd79c --- /dev/null +++ b/.github/workflows/checks.yml @@ -0,0 +1,64 @@ +name: Checks + +on: + pull_request: + push: + branches: [master] + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-24.04 + timeout-minutes: 15 + strategy: + matrix: + go: ["1.26.10", "1.27.3"] + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6 + with: + go-version: ${{ matrix.go }} + - run: go mod verify + - run: go test -race -v ./... + - run: go vet ./... + - name: Scan source dependencies + run: | + go install golang.org/x/vuln/cmd/govulncheck@v1.9.0 + govulncheck ./... + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 + with: + node-version: "24.22.1" + - run: npm install --global postman-cli@1.73.0 + - run: make test-http + timeout-minutes: 3 + - name: Verify module files + run: | + go mod tidy + git diff --exit-code -- go.mod go.sum + + build: + runs-on: ubuntu-24.04 + timeout-minutes: 20 + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + fetch-depth: 0 + - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6 + with: + go-version: "1.26.10" + - run: go install golang.org/x/vuln/cmd/govulncheck@v1.9.0 + - uses: goreleaser/goreleaser-action@e435ccd777264be153ace6237001ef4d979d3a7a # v6 + with: + distribution: goreleaser + version: "v2.19.0" + args: build --snapshot --clean + - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6 + with: + name: plugin-binaries + path: | + dist/**/*.plugin + dist/artifacts.json + if-no-files-found: error + retention-days: 7 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ec7e898..ab9456e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -13,27 +13,34 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 with: fetch-depth: 0 - name: Set up Go - uses: actions/setup-go@v5 + uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6 with: - go-version: "1.26" + go-version: "1.26.10" + + - name: Test and scan + run: | + go test -race ./... + go vet ./... + go install golang.org/x/vuln/cmd/govulncheck@v1.9.0 + govulncheck ./... - name: Import GPG key id: import_gpg - uses: crazy-max/ghaction-import-gpg@v6 + uses: crazy-max/ghaction-import-gpg@e89d40939c28e39f97cf32126055eeae86ba74ec # v6 with: gpg_private_key: ${{ secrets.GPG_PRIVATE_KEY }} passphrase: ${{ secrets.GPG_PASSPHRASE }} - name: Run GoReleaser - uses: goreleaser/goreleaser-action@v6 + uses: goreleaser/goreleaser-action@e435ccd777264be153ace6237001ef4d979d3a7a # v6 with: distribution: goreleaser - version: "~> v2" + version: "v2.19.0" args: release --clean env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.goreleaser.yml b/.goreleaser.yml index 109510a..923f197 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -17,6 +17,12 @@ builds: - arm64 id: "steampipe" binary: "{{ .ProjectName }}.plugin" + ldflags: + - -w + hooks: + post: + - cmd: govulncheck -mode=binary "{{ .Path }}" + output: true flags: - -tags=netgo diff --git a/CHANGELOG.md b/CHANGELOG.md index 8053d77..f8d8337 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,6 @@ ## v0.1.5 [2026-10-29] +- Updated Go networking dependencies and the release toolchain. Transport errors retain their underlying cause without including API keys in request URLs. - `ipgeolocation_ip`: `timezone_offset` and `timezone_offset_with_dst` are now `double` columns documented in hours. The API returns hours (for example `5.5`), so the previous integer columns and "seconds" descriptions dropped fractional offsets. ## v0.1.4 [2026-10-01] diff --git a/Makefile b/Makefile index c7c2899..b00ec24 100644 --- a/Makefile +++ b/Makefile @@ -6,7 +6,7 @@ PLUGIN_BIN = $(STEAMPIPE_INSTALL_DIR)/plugins/$(PLUGIN_PATH)/steampi CONFIG_DIR = $(STEAMPIPE_INSTALL_DIR)/config CONFIG_FILE = $(CONFIG_DIR)/ipgeolocation.spc -.PHONY: install install-config setup fmt lint test clean +.PHONY: install install-config setup fmt lint test test-http clean ## Build and install the plugin binary in one step install: @@ -52,6 +52,10 @@ lint: test: go test ./... +## Check HTTPS requests against the local Postman simulation +test-http: + node scripts/test-http.cjs + ## Remove built plugin binary clean: @rm -f $(PLUGIN_BIN) diff --git a/README.md b/README.md index 34a1b02..ea9968d 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ steampipe query "select ip, country_name, city from ipgeolocation_ip where ip = Prerequisites: - [Steampipe](https://steampipe.io/downloads) ≥ 0.20 -- [Go](https://golang.org/dl/) 1.24+ +- [Go](https://golang.org/dl/) 1.26.10+ Clone the repo, build, and install: diff --git a/go.mod b/go.mod index f7b0980..952c3b9 100644 --- a/go.mod +++ b/go.mod @@ -1,8 +1,11 @@ module github.com/IPGeolocation/steampipe-plugin-ipgeolocation -go 1.26.0 +go 1.26.10 -require github.com/turbot/steampipe-plugin-sdk/v5 v5.10.4 +require ( + github.com/hashicorp/go-hclog v1.6.3 + github.com/turbot/steampipe-plugin-sdk/v5 v5.10.4 +) require ( cel.dev/expr v0.25.2 // indirect @@ -74,7 +77,6 @@ require ( github.com/hashicorp/aws-sdk-go-base/v2 v2.0.0-beta.72 // indirect github.com/hashicorp/go-cleanhttp v0.5.2 // indirect github.com/hashicorp/go-getter v1.8.6 // indirect - github.com/hashicorp/go-hclog v1.6.3 // indirect github.com/hashicorp/go-plugin v1.6.0 // indirect github.com/hashicorp/go-version v1.8.0 // indirect github.com/hashicorp/hcl/v2 v2.20.1 // indirect @@ -117,16 +119,16 @@ require ( go.opentelemetry.io/otel/sdk/metric v1.45.0 // indirect go.opentelemetry.io/otel/trace v1.45.0 // indirect go.opentelemetry.io/proto/otlp v1.11.0 // indirect - golang.org/x/crypto v0.56.0 // indirect + golang.org/x/crypto v0.58.0 // indirect golang.org/x/exp v0.0.0-20230522175609-2e198f4a06a1 // indirect - golang.org/x/mod v0.40.0 // indirect - golang.org/x/net v0.58.0 // indirect + golang.org/x/mod v0.41.0 // indirect + golang.org/x/net v0.62.0 // indirect golang.org/x/oauth2 v0.36.0 // indirect - golang.org/x/sync v0.22.0 // indirect - golang.org/x/sys v0.47.0 // indirect - golang.org/x/text v0.41.0 // indirect + golang.org/x/sync v0.24.0 // indirect + golang.org/x/sys v0.49.0 // indirect + golang.org/x/text v0.43.0 // indirect golang.org/x/time v0.15.0 // indirect - golang.org/x/tools v0.49.0 // indirect + golang.org/x/tools v0.51.0 // indirect google.golang.org/api v0.271.0 // indirect google.golang.org/genproto v0.0.0-20260128011058-8636f8732409 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d // indirect diff --git a/go.sum b/go.sum index 19b0295..f82c692 100644 --- a/go.sum +++ b/go.sum @@ -465,8 +465,8 @@ golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.56.0 h1:GUh5Ii4J5jtcseSMiRqr1jXCNHoxjeV9Fmekc2oLy6Y= -golang.org/x/crypto v0.56.0/go.mod h1:OMW5y6CY9l38uPLmxU6l6pwcXp1obtLo3e6gT7gQR2I= +golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= +golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -500,8 +500,8 @@ golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzB golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.40.0 h1:hUv+3cXcdRHz08UmSiOob7sadHig73uo5bkXxQ/tvUs= -golang.org/x/mod v0.40.0/go.mod h1:0/weTWkPWGBikyTWAX3dkjVztMmBA5hM0DH6BElSupE= +golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c= +golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -534,8 +534,8 @@ golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96b golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= -golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To= -golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU= +golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= +golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -555,8 +555,8 @@ golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= -golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= +golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -603,8 +603,8 @@ golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20221010170243-090e33056c14/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= -golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -614,8 +614,8 @@ golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8= -golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M= +golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= +golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -662,8 +662,8 @@ golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= -golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI= -golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo= +golang.org/x/tools v0.51.0 h1:k4Xc/1Om9jwkBJBo4NVLMSARBoWtK10mx+W5BnXCeAI= +golang.org/x/tools v0.51.0/go.mod h1:9eEncMayCV6zRMGhR5eZEC2iBx98qWcF1HZ9Z7wJOoA= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/ipgeolocation/client.go b/ipgeolocation/client.go index 98083f8..cdbec2e 100644 --- a/ipgeolocation/client.go +++ b/ipgeolocation/client.go @@ -3,6 +3,7 @@ package ipgeolocation import ( "context" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -102,6 +103,10 @@ func (c *Client) doGet(ctx context.Context, endpoint string) (map[string]interfa } resp, err := c.httpClient.Do(req) if err != nil { + var requestError *url.Error + if errors.As(err, &requestError) { + err = requestError.Err // The outer error includes the API key in its request URL. + } return nil, fmt.Errorf("executing request: %w", err) } defer resp.Body.Close() diff --git a/ipgeolocation/client_test.go b/ipgeolocation/client_test.go new file mode 100644 index 0000000..7df5a37 --- /dev/null +++ b/ipgeolocation/client_test.go @@ -0,0 +1,164 @@ +package ipgeolocation + +import ( + "context" + "crypto/tls" + "errors" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + "time" + + "github.com/hashicorp/go-hclog" + "github.com/turbot/steampipe-plugin-sdk/v5/plugin" + "github.com/turbot/steampipe-plugin-sdk/v5/plugin/context_key" +) + +func testContext() context.Context { + return context.WithValue(context.Background(), context_key.Logger, hclog.NewNullLogger()) +} + +type roundTripFunc func(*http.Request) (*http.Response, error) + +func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } + +func TestClientRequests(t *testing.T) { + for _, tc := range []struct { + name, path string + params url.Values + call func(*Client) (map[string]interface{}, error) + }{ + {"geolocation", "/v3/ipgeo", url.Values{"apiKey": {"test & key"}, "ip": {"2001:4860:4860::8888"}, "include": {"*"}}, func(c *Client) (map[string]interface{}, error) { + return c.GetIPGeo(context.Background(), "2001:4860:4860::8888") + }}, + {"caller IP", "/v3/ipgeo", url.Values{"include": {"*"}}, func(c *Client) (map[string]interface{}, error) { + c.apiKey = "" + return c.GetIPGeo(context.Background(), "") + }}, + {"security", "/v3/security", url.Values{"apiKey": {"test & key"}, "ip": {"8.8.8.8"}}, func(c *Client) (map[string]interface{}, error) { return c.GetSecurity(context.Background(), "8.8.8.8") }}, + {"abuse", "/v3/abuse", url.Values{"apiKey": {"test & key"}, "ip": {"8.8.8.8"}}, func(c *Client) (map[string]interface{}, error) { return c.GetAbuse(context.Background(), "8.8.8.8") }}, + {"ASN by IP", "/v3/asn", url.Values{"apiKey": {"test & key"}, "ip": {"8.8.8.8"}, "include": {"peers,upstreams,downstreams,routes,whois_response"}}, func(c *Client) (map[string]interface{}, error) { return c.GetASN(context.Background(), "8.8.8.8", "") }}, + {"ASN number", "/v3/asn", url.Values{"apiKey": {"test & key"}, "asn": {"15169"}, "include": {"peers,upstreams,downstreams,routes,whois_response"}}, func(c *Client) (map[string]interface{}, error) { return c.GetASN(context.Background(), "", "15169") }}, + } { + t.Run(tc.name, func(t *testing.T) { + calls := 0 + c := &Client{apiKey: "test & key", httpClient: &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) { + calls++ + if r.Method != "GET" || r.URL.Scheme != "https" || r.URL.Host != "api.ipgeolocation.io" || r.URL.Path != tc.path || r.URL.Query().Encode() != tc.params.Encode() { + t.Fatalf("unexpected request: %s %s", r.Method, r.URL) + } + return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"ip":"8.8.8.8","security":{"is_proxy":false}}`)), Header: make(http.Header)}, nil + })}} + got, err := tc.call(c) + if err != nil || got["ip"] != "8.8.8.8" || calls != 1 { + t.Fatalf("result=%v calls=%d error=%v", got, calls, err) + } + }) + } +} + +func TestClientResponseHandling(t *testing.T) { + for _, tc := range []struct { + name string + status int + body, wantError string + }{ + {"success", 200, `{"ip":"8.8.8.8"}`, ""}, + {"authentication", 401, `{"message":"Invalid API key"}`, "API error 401"}, + {"forbidden", 403, `{"message":"Access denied"}`, "API error 403"}, + {"rate limit", 429, `{"message":"Too many requests"}`, "API error 429"}, + {"server error", 503, `{"message":"Unavailable"}`, "API error 503"}, + {"invalid JSON", 200, `{`, "decoding response"}, + } { + t.Run(tc.name, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(tc.status) + _, _ = io.WriteString(w, tc.body) + })) + defer server.Close() + c := &Client{httpClient: server.Client()} + got, err := c.doGet(context.Background(), server.URL) + if tc.wantError == "" { + if err != nil || got["ip"] != "8.8.8.8" { + t.Fatalf("result=%v error=%v", got, err) + } + } else if err == nil || !strings.Contains(err.Error(), tc.wantError) || got != nil { + t.Fatalf("result=%v error=%v", got, err) + } + }) + } + t.Run("truncated response", func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Length", "100") + _, _ = io.WriteString(w, `{}`) + })) + defer server.Close() + _, err := (&Client{httpClient: server.Client()}).doGet(context.Background(), server.URL) + if !errors.Is(err, io.ErrUnexpectedEOF) { + t.Fatalf("expected truncated-body error, got %v", err) + } + }) +} + +func TestClientTransportErrorRedactsKey(t *testing.T) { + cause := errors.New("connection failed") + c := &Client{apiKey: "test-only-secret", httpClient: &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) { return nil, cause })}} + _, err := c.GetIPGeo(context.Background(), "8.8.8.8") + if !errors.Is(err, cause) || strings.Contains(err.Error(), c.apiKey) { + t.Fatalf("transport error must retain its cause without the API key: %v", err) + } +} + +func TestClientCancellation(t *testing.T) { + c := &Client{apiKey: "test-only-secret", httpClient: &http.Client{}} + ctx, cancel := context.WithCancel(context.Background()) + cancel() + _, err := c.GetIPGeo(ctx, "8.8.8.8") + if !errors.Is(err, context.Canceled) { + t.Fatalf("expected cancellation, got %v", err) + } +} + +func TestAPIKeyConfiguration(t *testing.T) { + t.Setenv("IPGEOLOCATION_API_KEY", "environment-key") + configured := "configured-key" + empty := "" + for _, tc := range []struct { + name string + config interface{} + want string + }{ + {"configured key wins", IPGeolocationConfig{APIKey: &configured}, configured}, + {"empty key uses environment", IPGeolocationConfig{APIKey: &empty}, "environment-key"}, + {"missing config uses environment", nil, "environment-key"}, + } { + t.Run(tc.name, func(t *testing.T) { + c, err := newClient(testContext(), &plugin.QueryData{Connection: &plugin.Connection{Config: tc.config}}) + if err != nil || c.apiKey != tc.want || c.httpClient.Timeout != 30*time.Second { + t.Fatalf("client=%+v error=%v", c, err) + } + }) + } + t.Setenv("IPGEOLOCATION_API_KEY", "") + c, err := newClient(context.Background(), &plugin.QueryData{}) + if err != nil || c.apiKey != "" { + t.Fatalf("caller-IP client=%+v error=%v", c, err) + } +} + +func TestTLSVerification(t *testing.T) { + server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = io.WriteString(w, `{"ip":"198.51.100.42"}`) })) + defer server.Close() + _, err := (&Client{httpClient: &http.Client{}}).doGet(context.Background(), server.URL) + var certificateError *tls.CertificateVerificationError + if !errors.As(err, &certificateError) { + t.Fatalf("must reject an untrusted certificate: %v", err) + } + result, err := (&Client{httpClient: server.Client()}).doGet(context.Background(), server.URL) + if err != nil || result["ip"] != "198.51.100.42" { + t.Fatalf("trusted TLS response=%v error=%v", result, err) + } +} diff --git a/ipgeolocation/http_integration_test.go b/ipgeolocation/http_integration_test.go new file mode 100644 index 0000000..780ccf2 --- /dev/null +++ b/ipgeolocation/http_integration_test.go @@ -0,0 +1,126 @@ +package ipgeolocation + +import ( + "context" + "crypto/tls" + "crypto/x509" + "errors" + "net/http" + "os" + "reflect" + "strings" + "testing" + "time" + + "github.com/turbot/steampipe-plugin-sdk/v5/grpc/proto" + "github.com/turbot/steampipe-plugin-sdk/v5/plugin" + "github.com/turbot/steampipe-plugin-sdk/v5/plugin/transform" +) + +func TestHTTPSIntegration(t *testing.T) { + if os.Getenv("STEAMPIPE_HTTP_TEST") != "1" { + t.Skip("run make test-http with Postman CLI installed") + } + if os.Getenv("HTTPS_PROXY") == "" { + t.Fatal("the local proxy is required") + } + certificate, err := os.ReadFile(os.Getenv("SSL_CERT_FILE")) + if err != nil { + t.Fatal(err) + } + roots, err := x509.SystemCertPool() + if err != nil { + t.Fatal(err) + } + if !roots.AppendCertsFromPEM(certificate) { + t.Fatal("invalid local proxy certificate") + } + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.TLSClientConfig = &tls.Config{RootCAs: roots, MinVersion: tls.VersionTLS12} + original := http.DefaultTransport + http.DefaultTransport = transport + defer func() { transport.CloseIdleConnections(); http.DefaultTransport = original }() + + ctx := testContext() + for _, tc := range []struct { + name, table, ip, asn string + want map[string]interface{} + }{ + {"IPv4 geolocation", "ipgeolocation_ip", "198.51.100.42", "", map[string]interface{}{"ip": "198.51.100.42", "city": "New Delhi", "timezone_offset": 5.5, "timezone_offset_with_dst": 5.5}}, + {"IPv6 geolocation", "ipgeolocation_ip", "2001:db8::1", "", map[string]interface{}{"ip": "2001:db8::1", "timezone_offset": 5.5}}, + {"security", "ipgeolocation_security", "198.51.100.42", "", map[string]interface{}{"ip": "198.51.100.42", "is_proxy": false}}, + {"abuse contacts", "ipgeolocation_abuse", "198.51.100.42", "", map[string]interface{}{"ip": "198.51.100.42", "emails": []interface{}{"abuse@example.test"}}}, + {"ASN by IP", "ipgeolocation_asn", "198.51.100.42", "", map[string]interface{}{"as_number": "AS15169"}}, + {"ASN prefix", "ipgeolocation_asn", "", " as15169 ", map[string]interface{}{"as_number": "AS15169"}}, + } { + t.Run(tc.name, func(t *testing.T) { + key := "TEST_KEY" + rows := []interface{}{} + d := &plugin.QueryData{ + Connection: &plugin.Connection{Config: IPGeolocationConfig{APIKey: &key}}, + EqualsQuals: plugin.KeyColumnEqualsQualMap{}, + StreamListItem: func(_ context.Context, values ...interface{}) { rows = append(rows, values...) }, + } + for name, value := range map[string]string{"ip": tc.ip, "asn": tc.asn} { + if value != "" { + d.EqualsQuals[name] = &proto.QualValue{Value: &proto.QualValue_StringValue{StringValue: value}} + } + } + table := Plugin(ctx).TableMap[tc.table] + if _, err := table.List.Hydrate(ctx, d, nil); err != nil { + t.Fatal(err) + } + if len(rows) != 1 { + t.Fatalf("expected one result row, got %d", len(rows)) + } + for name, want := range tc.want { + found := false + for _, column := range table.Columns { + if column.Name != name { + continue + } + found = true + got, err := column.Transform.Execute(ctx, &transform.TransformData{HydrateItem: rows[0]}) + if err != nil || !reflect.DeepEqual(got, want) { + t.Fatalf("%s=%v, want %v, error=%v", name, got, want, err) + } + } + if !found { + t.Fatalf("missing column %s", name) + } + } + }) + } + t.Run("keyless caller IP", func(t *testing.T) { + c := &Client{httpClient: &http.Client{Timeout: time.Second}} + got, err := c.GetIPGeo(ctx, "") + if err != nil || got["ip"] != "198.51.100.42" { + t.Fatalf("response=%v error=%v", got, err) + } + }) + for _, tc := range []struct{ key, message string }{ + {"BAD_KEY", "API error 401"}, {"FORBIDDEN", "API error 403"}, + {"RATE_LIMIT", "API error 429"}, {"SERVER_ERROR", "API error 503"}, + {"BAD_JSON", "decoding response"}, + } { + t.Run(tc.key, func(t *testing.T) { + key, rows := tc.key, 0 + d := &plugin.QueryData{ + Connection: &plugin.Connection{Config: IPGeolocationConfig{APIKey: &key}}, + EqualsQuals: plugin.KeyColumnEqualsQualMap{"ip": &proto.QualValue{Value: &proto.QualValue_StringValue{StringValue: "198.51.100.42"}}}, + StreamListItem: func(_ context.Context, values ...interface{}) { rows += len(values) }, + } + _, err := listIPSecurity(ctx, d, nil) + if rows != 0 || err == nil || !strings.Contains(err.Error(), tc.message) { + t.Fatalf("rows=%d error=%v", rows, err) + } + }) + } + t.Run("timeout", func(t *testing.T) { + c := &Client{apiKey: "SLOW", httpClient: &http.Client{Timeout: 25 * time.Millisecond}} + _, err := c.GetIPGeo(ctx, "198.51.100.42") + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("expected timeout, got %v", err) + } + }) +} diff --git a/ipgeolocation/plugin_test.go b/ipgeolocation/plugin_test.go new file mode 100644 index 0000000..5bec340 --- /dev/null +++ b/ipgeolocation/plugin_test.go @@ -0,0 +1,77 @@ +package ipgeolocation + +import ( + "context" + "reflect" + "sort" + "testing" + + "github.com/turbot/steampipe-plugin-sdk/v5/grpc/proto" + "github.com/turbot/steampipe-plugin-sdk/v5/plugin" + "github.com/turbot/steampipe-plugin-sdk/v5/plugin/transform" +) + +func TestPluginTables(t *testing.T) { + p := Plugin(context.Background()) + var names []string + for name, table := range p.TableMap { + names = append(names, name) + if table.List == nil || table.List.Hydrate == nil { + t.Fatalf("%s has no query handler", name) + } + seen := map[string]bool{} + for _, column := range table.Columns { + if seen[column.Name] { + t.Fatalf("duplicate %s column in %s", column.Name, name) + } + seen[column.Name] = true + } + if name != "ipgeolocation_asn" && (len(table.List.KeyColumns) != 1 || table.List.KeyColumns[0].Name != "ip" || table.List.KeyColumns[0].Require != plugin.Required) { + t.Fatalf("%s must require an IP", name) + } + } + sort.Strings(names) + want := []string{"ipgeolocation_abuse", "ipgeolocation_asn", "ipgeolocation_ip", "ipgeolocation_security"} + if p.Name != "ipgeolocation" || !reflect.DeepEqual(names, want) || p.ConnectionConfigSchema.NewInstance() == nil { + t.Fatalf("unexpected plugin definition: %v", names) + } +} + +func TestFractionalTimezoneOffsets(t *testing.T) { + for _, offset := range []float64{5.5, 5.75, -3.5, 0} { + row := map[string]interface{}{"time_zone": map[string]interface{}{"offset": offset, "offset_with_dst": offset + 1}} + found := 0 + for _, c := range ipGeolocationColumns() { + if c.Name != "timezone_offset" && c.Name != "timezone_offset_with_dst" { + continue + } + found++ + if c.Type != proto.ColumnType_DOUBLE { + t.Fatalf("%s must preserve fractional hours", c.Name) + } + got, err := c.Transform.Execute(context.Background(), &transform.TransformData{HydrateItem: row}) + want := offset + if c.Name == "timezone_offset_with_dst" { + want++ + } + if err != nil || got != want { + t.Fatalf("%s=%v, want %v, error=%v", c.Name, got, want, err) + } + } + if found != 2 { + t.Fatal("both timezone offset columns must exist") + } + } +} + +func TestNormaliseASN(t *testing.T) { + for input, want := range map[string]string{"15169": "15169", "AS15169": "15169", " as15169 ": "15169", "": ""} { + if got := normaliseASN(input); got != want { + t.Fatalf("%q => %q, want %q", input, got, want) + } + } + _, err := listASN(testContext(), &plugin.QueryData{}, nil) + if err == nil { + t.Fatal("an ASN query without an IP or ASN must fail") + } +} diff --git a/postman/mocks/ipgeolocation/config.yaml b/postman/mocks/ipgeolocation/config.yaml new file mode 100644 index 0000000..2965be1 --- /dev/null +++ b/postman/mocks/ipgeolocation/config.yaml @@ -0,0 +1,7 @@ +version: 1 +name: ipgeolocation +origin: https://api.ipgeolocation.io +interceptRequests: true +scenarios: + - name: default + path: default.js diff --git a/postman/mocks/ipgeolocation/default.js b/postman/mocks/ipgeolocation/default.js new file mode 100644 index 0000000..e7049e2 --- /dev/null +++ b/postman/mocks/ipgeolocation/default.js @@ -0,0 +1,24 @@ +const http = require('node:http'); + +http.createServer((req, res) => { + const url = new URL(req.url, 'http://localhost'); + const reply = (status, body) => { res.writeHead(status, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(body)); }; + if (!['/v3/ipgeo', '/v3/security', '/v3/abuse', '/v3/asn'].includes(url.pathname)) return reply(501, { message: 'Endpoint not modeled' }); + if (req.method !== 'GET') return reply(400, { message: 'Expected GET' }); + const key = url.searchParams.get('apiKey'); + const statuses = { BAD_KEY: 401, FORBIDDEN: 403, RATE_LIMIT: 429, SERVER_ERROR: 503 }; + if (statuses[key]) return reply(statuses[key], { message: 'Test failure response' }); + if (key === 'BAD_JSON') { res.writeHead(200); return res.end('{'); } + if (key === 'SLOW') return setTimeout(() => { if (!res.destroyed) reply(200, {}); }, 250); + if (key !== 'TEST_KEY' && !(key === null && url.pathname === '/v3/ipgeo')) return reply(401, { message: 'Invalid test key' }); + const ip = url.searchParams.get('ip') || '198.51.100.42'; + if (url.pathname === '/v3/ipgeo') { + if (url.searchParams.get('include') !== '*') return reply(400, { message: 'Expected include=*' }); + return reply(200, { ip, location: { city: 'New Delhi' }, time_zone: { offset: 5.5, offset_with_dst: 5.5 } }); + } + if (url.pathname === '/v3/security') return reply(200, { ip, security: { is_proxy: false } }); + if (url.pathname === '/v3/abuse') return reply(200, { ip, abuse: { emails: ['abuse@example.test'] } }); + if (url.searchParams.get('include') !== 'peers,upstreams,downstreams,routes,whois_response') return reply(400, { message: 'Missing ASN relationship fields' }); + if (url.searchParams.get('asn') !== '15169' && !url.searchParams.get('ip')) return reply(400, { message: 'Expected an IP or normalized ASN' }); + reply(200, { ip, asn: { as_number: 'AS15169' } }); +}).listen(process.env.PORT || 4500); diff --git a/postman/simulations/steampipe/simulation.context.yaml b/postman/simulations/steampipe/simulation.context.yaml new file mode 100644 index 0000000..43ec291 --- /dev/null +++ b/postman/simulations/steampipe/simulation.context.yaml @@ -0,0 +1,37 @@ +purpose: + stands_in_for: IPGeolocation v3 IP, security, abuse and ASN GET responses. + unblocks: HTTP and table-hydration regression checks for the plugin dependency update. +assumptions: + - id: request-and-row-compatibility + status: supported + claim: The plugin preserves its request parameters, nested result fields, IPv6 values and fractional timezone offsets in the modeled cases. + reason: These are the existing client and table contracts under test. + verification: On 2026-10-29, all 13 HTTPS cases passed. Proxy traffic confirms the real client reached the stand-in for all four endpoints; the timeout check observed the expected caller error. No live service behavior is established. + source: ipgeolocation/http_integration_test.go; postman/mocks/ipgeolocation/default.js + updated_at: '2026-10-29' + - id: error-compatibility + status: supported + claim: HTTP 401, 403, 429 and 503 responses, malformed JSON and timeouts still return errors without result rows. + reason: The dependency update must preserve these caller outcomes. + verification: On 2026-10-29, all 13 HTTPS cases passed. Proxy traffic confirms the real client reached the stand-in for all four endpoints; the timeout check observed the expected caller error. No live service behavior is established. + source: ipgeolocation/http_integration_test.go + updated_at: '2026-10-29' + - id: live-provider-contract + status: unknown + claim: These fixture checks establish live provider behavior or account permissions. + reason: Fixtures model the existing plugin and documented table fields. No provider mock was listed in the official IPGeolocation.io API Hub workspace; Orbit discovery returned HTTP 403. + verification: No live provider requests or credentials are used. The simulation checks the real client against controlled responses. + source: ipgeolocation/client.go; docs/tables; postman/mocks/ipgeolocation/default.js + updated_at: '2026-10-29' + - id: proxy-certificate-serials + status: supported + claim: Postman CLI 1.73.0 can issue a negative-serial test certificate that strict Go rejects before an API request reaches the mock. + reason: Go 1.26.10 rejected the local proxy certificate with x509 negative serial number errors. The HTTPS-only test subprocess enables the Go compatibility flag for these fixture certificates; the production plugin and normal TLS tests keep their defaults. + verification: The initial Go 1.26.10 proxy run failed at the TLS handshake. The Go 1.26.10 rerun passed all 13 HTTPS cases with the fixture-only compatibility flag; normal tests separately passed trusted and untrusted TLS checks without that flag. + source: scripts/test-http.cjs; ipgeolocation/client_test.go; ipgeolocation/http_integration_test.go + updated_at: '2026-10-29' +fingerprints: + - id: security-update-v0.1.5 + date: '2026-10-29' + commit: 4ab6ad1c plus dependency, error-redaction and regression-test changes in the working tree. + cli: Postman CLI 1.73.0; Go 1.26.10 and 1.27.3. diff --git a/postman/simulations/steampipe/simulation.yaml b/postman/simulations/steampipe/simulation.yaml new file mode 100644 index 0000000..8eccbc0 --- /dev/null +++ b/postman/simulations/steampipe/simulation.yaml @@ -0,0 +1,10 @@ +id: 5363c5ee-33a1-46ef-a8c1-cd5dc633171e +simulation: steampipe +routing: path +mocks: + - name: ipgeolocation + id: 4cfe8d84-e688-4f4e-955f-de1856c44d25 + routeKey: ipgeolocation + origin: + - api.ipgeolocation.io + path: ../../mocks/ipgeolocation/config.yaml diff --git a/scripts/test-http.cjs b/scripts/test-http.cjs new file mode 100644 index 0000000..293915d --- /dev/null +++ b/scripts/test-http.cjs @@ -0,0 +1,66 @@ +'use strict'; + +const { spawn } = require('node:child_process'); +const { once } = require('node:events'); +const path = require('node:path'); + +async function main() { + const proxy = spawn('postman', [ + 'simulation', 'run', 'postman/simulations/steampipe/simulation.yaml', + '--proxy', '--proxy-port', '7012', '--no-history', '--log-format', 'json', + ], { + cwd: path.resolve(__dirname, '..'), stdio: ['ignore', 'pipe', 'pipe'], + detached: process.platform !== 'win32', + }); + const closed = new Promise((resolve) => proxy.once('close', resolve)); + let output = ''; + let errors = ''; + let timer; + try { + const certificate = await new Promise((resolve, reject) => { + timer = setTimeout(() => reject(new Error(`Postman proxy did not start: ${errors}`)), 20000); + proxy.once('error', reject); + proxy.once('exit', (code) => reject(new Error(`Postman proxy exited (${code}): ${errors}`))); + proxy.stderr.on('data', (chunk) => { errors += chunk; }); + proxy.stdout.on('data', (chunk) => { + output += chunk; + const match = output.match(/NODE_EXTRA_CA_CERTS=([^\r\n]+)/); + if (match) resolve(match[1].trim()); + }); + }); + clearTimeout(timer); + const checks = spawn('go', ['test', './ipgeolocation', '-run', '^TestHTTPSIntegration$', '-count=1', '-v'], { + cwd: path.resolve(__dirname, '..'), stdio: 'inherit', + env: { + ...process.env, + HTTPS_PROXY: 'http://127.0.0.1:7012', HTTP_PROXY: 'http://127.0.0.1:7012', + NO_PROXY: '', SSL_CERT_FILE: certificate, STEAMPIPE_HTTP_TEST: '1', + // shortcut: allow Postman 1.73's negative test-certificate serials until the CLI fixes them. + GODEBUG: [process.env.GODEBUG, 'x509negativeserial=1'].filter(Boolean).join(','), + }, + }); + const [code] = await once(checks, 'exit'); + process.exitCode = code === 0 ? 0 : 1; + console.log(output); + if (process.exitCode) console.error(errors); + } finally { + clearTimeout(timer); + if (proxy.pid) { + // The npm-installed CLI launches a child; stop the entire proxy process group. + const stop = (signal) => { + try { + if (process.platform === 'win32') proxy.kill(signal); + else process.kill(-proxy.pid, signal); + } catch (err) { + if (err.code !== 'ESRCH') throw err; + } + }; + const force = setTimeout(() => stop('SIGKILL'), 2000); + stop('SIGINT'); + await closed; + clearTimeout(force); + } + } +} + +main().catch((err) => { console.error(err.message); process.exitCode = 1; });