From 1db50cc7d008db34078712ea1bd97790800912ff Mon Sep 17 00:00:00 2001 From: Nikolai Baudis Date: Thu, 26 Nov 2026 22:15:07 +0100 Subject: [PATCH] Add sample network-isolation/inbound-webhooks --- network-isolation/inbound-webhooks/.gitignore | 1 + network-isolation/inbound-webhooks/README.md | 61 + network-isolation/inbound-webhooks/build | 29 + network-isolation/inbound-webhooks/run | 132 ++ .../inbound-webhooks/src/consumer/Dockerfile | 15 + .../inbound-webhooks/src/consumer/cos.go | 120 ++ .../inbound-webhooks/src/consumer/cos_test.go | 44 + .../inbound-webhooks/src/consumer/env.go | 23 + .../inbound-webhooks/src/consumer/envelope.go | 26 + .../inbound-webhooks/src/consumer/go.mod | 30 + .../inbound-webhooks/src/consumer/go.sum | 91 ++ .../inbound-webhooks/src/consumer/main.go | 140 ++ .../src/consumer/main_test.go | 125 ++ .../inbound-webhooks/src/consumer/server.go | 42 + .../inbound-webhooks/src/receiver/.ceignore | 1 + .../inbound-webhooks/src/receiver/main.js | 248 ++++ .../src/receiver/main.test.js | 283 ++++ .../src/receiver/package-lock.json | 1253 +++++++++++++++++ .../src/receiver/package.json | 17 + .../inbound-webhooks/test-receiver | 120 ++ 20 files changed, 2801 insertions(+) create mode 100644 network-isolation/inbound-webhooks/.gitignore create mode 100644 network-isolation/inbound-webhooks/README.md create mode 100755 network-isolation/inbound-webhooks/build create mode 100755 network-isolation/inbound-webhooks/run create mode 100644 network-isolation/inbound-webhooks/src/consumer/Dockerfile create mode 100644 network-isolation/inbound-webhooks/src/consumer/cos.go create mode 100644 network-isolation/inbound-webhooks/src/consumer/cos_test.go create mode 100644 network-isolation/inbound-webhooks/src/consumer/env.go create mode 100644 network-isolation/inbound-webhooks/src/consumer/envelope.go create mode 100644 network-isolation/inbound-webhooks/src/consumer/go.mod create mode 100644 network-isolation/inbound-webhooks/src/consumer/go.sum create mode 100644 network-isolation/inbound-webhooks/src/consumer/main.go create mode 100644 network-isolation/inbound-webhooks/src/consumer/main_test.go create mode 100644 network-isolation/inbound-webhooks/src/consumer/server.go create mode 100644 network-isolation/inbound-webhooks/src/receiver/.ceignore create mode 100644 network-isolation/inbound-webhooks/src/receiver/main.js create mode 100644 network-isolation/inbound-webhooks/src/receiver/main.test.js create mode 100644 network-isolation/inbound-webhooks/src/receiver/package-lock.json create mode 100644 network-isolation/inbound-webhooks/src/receiver/package.json create mode 100755 network-isolation/inbound-webhooks/test-receiver diff --git a/network-isolation/inbound-webhooks/.gitignore b/network-isolation/inbound-webhooks/.gitignore new file mode 100644 index 000000000..7cd53fdbc --- /dev/null +++ b/network-isolation/inbound-webhooks/.gitignore @@ -0,0 +1 @@ +**/node_modules/ diff --git a/network-isolation/inbound-webhooks/README.md b/network-isolation/inbound-webhooks/README.md new file mode 100644 index 000000000..99070ca80 --- /dev/null +++ b/network-isolation/inbound-webhooks/README.md @@ -0,0 +1,61 @@ +# Webhooks for a private Code Engine project + +This sample shows how a network-isolated (private, CBR-restricted) Code Engine project can receive webhooks from the public internet. A sender such as GitHub cannot call a private project directly. Instead, a small public project verifies and stores each delivery, and the private project picks it up from there. GitHub is used as the example sender, but the pattern works for any webhook. + +``` +sender ──HTTPS──▶ receiver (public project) ──write──▶ COS bucket ──event──▶ consumer (private project, CBR) +``` + +* **receiver** (public project): a Code Engine function that verifies the HMAC signature and writes the delivery as an object to a Cloud Object Storage (COS) bucket. It only has write access to that bucket, and its project allows no outbound traffic except to IBM Cloud services over their private endpoints. +* **consumer** (private project): triggered by a COS event subscription for every new object, reads it and processes it (the sample logs a summary). It only has read access to that bucket and accepts no inbound traffic at all, because a context-based restriction (CBR) rule denies the public and the private endpoint. + +Receiver and consumer authenticate to COS with IAM trusted profiles, so there are no API keys. The sender-specific code (header names, signature scheme) is marked in [`src/receiver/main.js`](src/receiver/main.js). Adapt it to use another sender. + +**Payload size limit:** Code Engine functions accept request bodies of up to 5 MB, while GitHub sends up to 25 MB. A delivery above the limit is rejected by Code Engine before the function runs, so it is dropped: nothing is written to the bucket, the consumer never sees it, and the receiver does not log it. The sender is told that the delivery failed (GitHub shows it as failed under *Settings > Webhooks > Recent Deliveries*), and redelivering it fails again. Typical events such as pushes, issues and pull request activity are far smaller, but a push with many commits or a large pull request payload can exceed the limit. If you must receive such payloads, run the receiver as an application instead of a function. + + +## Prerequisites + +[IBM Cloud CLI](https://cloud.ibm.com/docs/cli) with the `code-engine`, `cloud-object-storage` and `cbr` plugins, plus `jq`, `curl`, `openssl` and `uuidgen`. + +``` +ibmcloud plugin install -f code-engine cloud-object-storage cbr +ibmcloud login +``` + +## Installing the sample + +1. Set the secret that your sender signs its webhooks with (it is not stored in any file), then deploy. The names and the region are documented with their defaults at the top of [`run`](run). Override any of them with an environment variable, for example `REGION=us-south ./run`. The receiver code bundle and the consumer image are pulled from `icr.io/codeengine/webhook-sample` unless you set `REGISTRY`. + ``` + read -rs WEBHOOK_SECRET && export WEBHOOK_SECRET + ./run + ``` + +2. Configure the webhook of your sender with the URL that `./run` prints, content type `application/json` and the same secret. For GitHub, add it under *Settings > Webhooks* of your repository. + +3. Check that it works. The first command sends a signed and several invalid requests to the receiver, the second shows the deliveries that the consumer processed. The logs of the receiver function are available in IBM Cloud Logs. + ``` + ./test-receiver + ibmcloud ce project select --name webhook-isolated && ibmcloud ce app logs --name webhook-consumer + ``` + +When you do not need the sample anymore, delete everything: + +``` +./run clean +``` + +`./run clean` deletes everything that `./run` created, except the resource group, without asking. + +## Using your own images + +[`build`](build) builds both components with Code Engine build runs, so you do not need a local Docker setup. The builds run in a third Code Engine project, `webhook-build`, so that the two projects of the sample are not used for building. The consumer ([`src/consumer`](src/consumer)) is a regular container image built with its [`Dockerfile`](src/consumer/Dockerfile). The receiver ([`src/receiver`](src/receiver)) is a function, so its image is a code bundle built with the `codebundle-nodejs-24` strategy, which installs the dependencies and packages them with `main.js` for the managed Node.js runtime of Code Engine. Build both images into your own registry and namespace, then deploy with the same registry and namespace. The receiver code bundle is named `/receiver` and the consumer image `/consumer`. + +``` +REGISTRY=/ ./build +REGISTRY=/ ./run +``` + +With IBM Cloud Container Registry, use the private endpoint of your region, for example `REGISTRY=private.au.icr.io/`. If the registry is private, create a registry secret for it in both projects. Add it to the consumer with `ibmcloud ce app update --registry-secret ` and to the receiver with `ibmcloud ce function update --code-bundle-secret `. + +The unit tests of the receiver run with `npm ci && npm test` in [`src/receiver`](src/receiver). diff --git a/network-isolation/inbound-webhooks/build b/network-isolation/inbound-webhooks/build new file mode 100755 index 000000000..8b9564e24 --- /dev/null +++ b/network-isolation/inbound-webhooks/build @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# +# Optional: builds your own receiver code bundle and consumer image with Code Engine build runs and pushes them to your registry. +# Then deploy them with: REGISTRY=/ WEBHOOK_SECRET=... ./run +# +# The builds run in a separate Code Engine project, so that the network-isolated consumer and receiver projects are not used for +# building. Nothing in this script needs Docker. +# +# Env Vars: +# REGISTRY: image registry and namespace to push the receiver code bundle and the consumer image to (required, defaults to +# icr.io/codeengine/webhook-sample where you don't have write permission). +# With IBM Cloud Container Registry, use the private endpoint of your region, for example +# private.au.icr.io/. Use the same value for ./run. +# BUILD_PROJECT: name of the Code Engine project that runs the builds, created if it does not exist (default: webhook-build) + +set -euo pipefail +cd "$(dirname "$0")" + +BUILD_PROJECT=${BUILD_PROJECT:-webhook-build} +REGISTRY=${REGISTRY:-icr.io/codeengine/webhook-sample} + +ibmcloud ce project get --name "$BUILD_PROJECT" > /dev/null 2>&1 || ibmcloud ce project create --name "$BUILD_PROJECT" +ibmcloud ce project select --name "$BUILD_PROJECT" + +suffix=$(date +%y%m%d-%H%M%S) +ibmcloud ce buildrun submit --name "webhook-consumer-$suffix" --source src/consumer --strategy dockerfile \ + --image "$REGISTRY/consumer" --wait +ibmcloud ce buildrun submit --name "webhook-receiver-$suffix" --source src/receiver --strategy codebundle-nodejs-24 \ + --dockerfile "" --image "$REGISTRY/receiver" --wait diff --git a/network-isolation/inbound-webhooks/run b/network-isolation/inbound-webhooks/run new file mode 100755 index 000000000..81ceb732b --- /dev/null +++ b/network-isolation/inbound-webhooks/run @@ -0,0 +1,132 @@ +#!/usr/bin/env bash + +# Deploys the webhook sample: a public receiver, a COS bucket and a network-isolated consumer (see README.md). +# WEBHOOK_SECRET=... ./run deploy +# ./run clean delete everything again (except the resource group) +# +# Env Vars (use the same values for ./run clean): +# WEBHOOK_SECRET: secret that your webhook sender signs its deliveries with (required, no default) +# REGION: region of all resources (default: the region that your IBM Cloud CLI targets, see 'ibmcloud target') +# RESOURCE_GROUP: resource group that holds the COS instance (default: webhook-sample) +# COS_INSTANCE: name of the Cloud Object Storage instance (default: webhook-cos) +# PUBLIC_PROJECT: name of the public Code Engine project with the receiver (default: webhook-public) +# ISOLATED_PROJECT: name of the network-isolated Code Engine project with the consumer (default: webhook-isolated) +# RECEIVER_FUNCTION: name of the receiver function (default: webhook-receiver) +# CONSUMER_APP: name of the consumer app (default: webhook-consumer) +# REGISTRY: image registry and namespace of the receiver code bundle and the consumer image (default: icr.io/codeengine/webhook-sample, see ./build) + +set -euo pipefail + +RESOURCE_GROUP=${RESOURCE_GROUP:-webhook-sample} +COS_INSTANCE=${COS_INSTANCE:-webhook-cos} +PUBLIC_PROJECT=${PUBLIC_PROJECT:-webhook-public} +ISOLATED_PROJECT=${ISOLATED_PROJECT:-webhook-isolated} +BUILD_PROJECT=${BUILD_PROJECT:-webhook-build} +RECEIVER_FUNCTION=${RECEIVER_FUNCTION:-webhook-receiver} +CONSUMER_APP=${CONSUMER_APP:-webhook-consumer} + +REGISTRY=${REGISTRY:-icr.io/codeengine/webhook-sample} +REGION=${REGION:-$(ibmcloud target --output json | jq -r '.region.name // empty')} +: "${REGION:?Set REGION or target a region with: ibmcloud target -r }" + +COS_ENDPOINT=https://s3.direct.$REGION.cloud-object-storage.appdomain.cloud +IBM_AUTH_ENDPOINT=https://private.iam.cloud.ibm.com +PROFILE_PUBLIC=webhook-public-cos-writer +PROFILE_ISOLATED=webhook-isolated-cos-reader + +clean() { + set +e + set -x + + ibmcloud target -r "$REGION" -g "$RESOURCE_GROUP" + guid=$(ibmcloud ce project get --name "$ISOLATED_PROJECT" --output json | jq -r '.guid') + for id in $(ibmcloud cbr rules --service-name codeengine --service-instance "$guid" --output json | jq -r '.rules[]?.id'); do + ibmcloud cbr rule-delete "$id" + done + for id in $(ibmcloud iam authorization-policies --output json \ + | jq -r --arg s "$guid" '(if type == "array" then . else .policies end)[] | select(any(.subjects[]?.attributes[]?; .value == $s)) | .id'); do + ibmcloud iam authorization-policy-delete "$id" --force + done + ibmcloud ce project delete --name "$PUBLIC_PROJECT" --force --hard + ibmcloud ce project delete --name "$ISOLATED_PROJECT" --force --hard + ibmcloud ce project delete --name "$BUILD_PROJECT" --force --hard + ibmcloud iam trusted-profile-delete "$PROFILE_PUBLIC" --force + ibmcloud iam trusted-profile-delete "$PROFILE_ISOLATED" --force + for crn in $(ibmcloud resource service-instances --service-name cloud-object-storage --output json \ + | jq -r --arg n "$COS_INSTANCE" '.[] | select(.name == $n) | .crn'); do + ibmcloud resource service-instance-delete "$crn" --force --recursive + done +} + +if [ "${1:-}" = clean ]; then + clean + exit +fi +: "${WEBHOOK_SECRET:?Set WEBHOOK_SECRET to the secret that your webhook sender signs with}" + +# Resource group, COS instance and bucket (bucket names are globally unique, so the name contains part of the instance GUID) +ibmcloud target -r "$REGION" +ibmcloud resource group "$RESOURCE_GROUP" > /dev/null 2>&1 || ibmcloud resource group-create "$RESOURCE_GROUP" # not deleted by ./run clean +ibmcloud target -g "$RESOURCE_GROUP" +COS_CRN=$(ibmcloud resource service-instance-create "$COS_INSTANCE" cloud-object-storage standard global -d premium-global-deployment-iam \ + -g "$RESOURCE_GROUP" | awk '/^ID:/ {print $2}') +COS_GUID=$(echo "$COS_CRN" | cut -d: -f8) +BUCKET=webhook-${COS_GUID:0:8} +ibmcloud cos config crn --crn "$COS_CRN" --force +ibmcloud cos config region --region "$REGION" +ibmcloud cos config endpoint-url --url "https://s3.$REGION.cloud-object-storage.appdomain.cloud" +ibmcloud cos config auth --method iam +ibmcloud cos bucket-create --bucket "$BUCKET" --region "$REGION" + +# Code Engine projects. The public project may not call any external address. Calls to IBM Cloud services over their private +# endpoints (COS, IAM) are always allowed, so removing the default "allow-all" rule is enough. +ibmcloud ce project create --name "$PUBLIC_PROJECT" +ibmcloud ce connectivity outbound delete --name allow-all --force + +# The isolated project accepts no inbound traffic at all: a rule without any context denies the public and the private endpoint. +# The COS event subscription is not affected, because the Code Engine platform delivers the events. +ibmcloud ce project create --name "$ISOLATED_PROJECT" +ISOLATED_GUID=$(ibmcloud ce project get --name "$ISOLATED_PROJECT" --output json | jq -r '.guid') +ibmcloud cbr rule-create --description "Block all inbound traffic to $ISOLATED_PROJECT" \ + --service-name codeengine --service-instance "$ISOLATED_GUID" \ + --api-types crn:v1:bluemix:public:context-based-restrictions::::api-type:data-plane \ + --empty-context-list + +# Trusted profiles: the receiver may only write to the bucket, the consumer may only read from it +PUBLIC_TRUSTED_PROFILE_ID=$(ibmcloud iam trusted-profile-create "$PROFILE_PUBLIC" --output json | jq -r '.id') +ISOLATED_TRUSTED_PROFILE_ID=$(ibmcloud iam trusted-profile-create "$PROFILE_ISOLATED" --output json | jq -r '.id') +ibmcloud iam trusted-profile-policy-create "$PROFILE_PUBLIC" --roles "Object Writer" --service-name cloud-object-storage \ + --service-instance "$COS_GUID" --resource-type bucket --resource "$BUCKET" +ibmcloud iam trusted-profile-policy-create "$PROFILE_ISOLATED" --roles "Object Reader" --service-name cloud-object-storage \ + --service-instance "$COS_GUID" --resource-type bucket --resource "$BUCKET" + +# Receiver (public project), a function that runs the code bundle image built from src/receiver (see ./build). +# The secret goes through a private temporary file, so it does not show up in the process list. Function runtimes start fast, +# so no always-running instance is needed for senders such as GitHub that time out quickly. +secret_file=$(mktemp) +trap 'rm -f "$secret_file"' EXIT +printf '%s' "$WEBHOOK_SECRET" > "$secret_file" +ibmcloud ce project select --name "$PUBLIC_PROJECT" +ibmcloud ce secret create --name webhook-secret --from-file "WEBHOOK_SECRET=$secret_file" +ibmcloud ce function create --name "$RECEIVER_FUNCTION" --runtime nodejs-24 --code-bundle "$REGISTRY/receiver" \ + --trusted-profiles-enabled=true --env-from-secret webhook-secret \ + --env "COS_BUCKET=$BUCKET" --env "COS_ENDPOINT=$COS_ENDPOINT" --env "IBM_AUTH_ENDPOINT=$IBM_AUTH_ENDPOINT" --env "TRUSTED_PROFILE_ID=$PUBLIC_TRUSTED_PROFILE_ID" +PUBLIC_CRN=$(ibmcloud resource service-instance "$PUBLIC_PROJECT" --location "$REGION" --crn | grep ':codeengine:') +ibmcloud iam trusted-profile-link-create "$PROFILE_PUBLIC" --name receiver --cr-type CE --link-crn "$PUBLIC_CRN" \ + --link-component-type function --link-component-name "$RECEIVER_FUNCTION" + +# Consumer (isolated project), triggered for every object that is written to the bucket +ibmcloud ce project select --name "$ISOLATED_PROJECT" +ibmcloud ce app create --name "$CONSUMER_APP" --image "$REGISTRY/consumer" \ + --trusted-profiles-enabled=true \ + --env "COS_BUCKET=$BUCKET" --env "COS_ENDPOINT=$COS_ENDPOINT" --env "IBM_AUTH_ENDPOINT=$IBM_AUTH_ENDPOINT" --env "COS_REGION=$REGION" --env "TRUSTED_PROFILE_ID=$ISOLATED_TRUSTED_PROFILE_ID" +ISOLATED_CRN=$(ibmcloud resource service-instance "$ISOLATED_PROJECT" --location "$REGION" --crn | grep ':codeengine:') +ibmcloud iam trusted-profile-link-create "$PROFILE_ISOLATED" --name consumer --cr-type CE --link-crn "$ISOLATED_CRN" \ + --link-component-type application --link-component-name "$CONSUMER_APP" +# Code Engine needs the permission to manage the notifications of the bucket +ibmcloud iam authorization-policy-create codeengine cloud-object-storage "Notifications Manager" \ + --source-service-instance-id "$ISOLATED_GUID" --target-service-instance-id "$COS_GUID" +ibmcloud ce sub cos create --name webhook-sub --destination "$CONSUMER_APP" --bucket "$BUCKET" --event-type write + +ibmcloud ce project select --name "$PUBLIC_PROJECT" +echo "Webhook URL: $(ibmcloud ce function get --name "$RECEIVER_FUNCTION" --output jsonpath="{.endpoint}")" diff --git a/network-isolation/inbound-webhooks/src/consumer/Dockerfile b/network-isolation/inbound-webhooks/src/consumer/Dockerfile new file mode 100644 index 000000000..a9d2d31e4 --- /dev/null +++ b/network-isolation/inbound-webhooks/src/consumer/Dockerfile @@ -0,0 +1,15 @@ +# Build context: this directory (see ../../build) +FROM golang:1.27.4-alpine AS build +WORKDIR /src +COPY go.mod go.sum ./ +RUN go mod download +COPY . ./ +RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/webhook-consumer . + +FROM scratch +# CA certificates for the TLS connections to IAM and COS +COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt +COPY --from=build /out/webhook-consumer /webhook-consumer +USER 65534:65534 +EXPOSE 8080 +ENTRYPOINT ["/webhook-consumer"] diff --git a/network-isolation/inbound-webhooks/src/consumer/cos.go b/network-isolation/inbound-webhooks/src/consumer/cos.go new file mode 100644 index 000000000..21a12011e --- /dev/null +++ b/network-isolation/inbound-webhooks/src/consumer/cos.go @@ -0,0 +1,120 @@ +package main + +import ( + "context" + "encoding/base64" + "encoding/json" + "fmt" + "io" + "log" + "strings" + "time" + + "github.com/IBM/go-sdk-core/v5/core" + "github.com/IBM/ibm-cos-sdk-go/aws" + "github.com/IBM/ibm-cos-sdk-go/aws/credentials/ibmiam" + "github.com/IBM/ibm-cos-sdk-go/aws/credentials/ibmiam/token" + "github.com/IBM/ibm-cos-sdk-go/aws/session" + "github.com/IBM/ibm-cos-sdk-go/service/s3" +) + +const maxObjectBytes = 26 << 20 // GitHub payloads are up to 25 MB, plus envelope + +type objectGetter interface { + Get(ctx context.Context, bucket, key string) ([]byte, error) +} + +type cosGetter struct { + client *s3.S3 +} + +func (c *cosGetter) Get(ctx context.Context, bucket, key string) ([]byte, error) { + out, err := c.client.GetObjectWithContext(ctx, &s3.GetObjectInput{ + Bucket: aws.String(bucket), + Key: aws.String(key), + }) + if err != nil { + return nil, err + } + defer out.Body.Close() + + data, err := io.ReadAll(io.LimitReader(out.Body, maxObjectBytes+1)) + if err != nil { + return nil, err + } + if len(data) > maxObjectBytes { + return nil, fmt.Errorf("object larger than %d bytes", maxObjectBytes) + } + return data, nil +} + +// jwtExpiry returns the expiry time ("exp" claim) of an IAM access token, which is a JWT. +// The signature is not verified: the token comes straight from IAM and is only inspected here. +func jwtExpiry(accessToken string) (time.Time, error) { + parts := strings.Split(accessToken, ".") + if len(parts) != 3 { + return time.Time{}, fmt.Errorf("access token is not a JWT") + } + claims, err := base64.RawURLEncoding.DecodeString(parts[1]) + if err != nil { + return time.Time{}, fmt.Errorf("cannot decode the claims of the access token: %w", err) + } + var c struct { + Exp int64 `json:"exp"` + } + if err := json.Unmarshal(claims, &c); err != nil { + return time.Time{}, fmt.Errorf("cannot parse the claims of the access token: %w", err) + } + if c.Exp == 0 { + return time.Time{}, fmt.Errorf("access token has no exp claim") + } + return time.Unix(c.Exp, 0), nil +} + +// newCOSClient creates a COS client from COS_ENDPOINT, COS_REGION and TRUSTED_PROFILE_ID. +// Credentials come from the Code Engine trusted profile (compute resource token), no API key involved. +// The IBM SDK core ContainerAuthenticator exchanges the compute resource token for IAM access tokens +// and caches and refreshes them. The COS client is told the real expiry of the access token (from its +// JWT), and asks the authenticator for a new one shortly before that. +func newCOSClient() *s3.S3 { + endpoint := mustEnv("COS_ENDPOINT") + region := mustEnv("COS_REGION") + profileID := mustEnv("TRUSTED_PROFILE_ID") + iamEndpoint := getEnv("IBM_AUTH_ENDPOINT", "https://private.iam.cloud.ibm.com") + tokenFile := getEnv("CR_TOKEN_FILE_PATH", "/var/run/secrets/codeengine.cloud.ibm.com/compute-resource-token/token") + + authenticator, err := core.NewContainerAuthenticatorBuilder(). + SetIAMProfileID(profileID). + SetCRTokenFilename(tokenFile). + SetURL(iamEndpoint). + Build() + if err != nil { + log.Fatalf("cannot create authenticator: %v", err) + } + + cfg := aws.NewConfig(). + WithEndpoint(endpoint). + WithRegion(region). + WithS3ForcePathStyle(true). + WithCredentials(ibmiam.NewCustomInitFuncCredentials(aws.NewConfig(), func() (*token.Token, error) { + accessToken, err := authenticator.GetToken() + if err != nil { + return nil, err + } + expiry, err := jwtExpiry(accessToken) + if err != nil { + return nil, err + } + return &token.Token{ + AccessToken: accessToken, + TokenType: "Bearer", + ExpiresIn: int64(time.Until(expiry).Seconds()), + Expiration: expiry.Unix(), + }, nil + }, iamEndpoint, "")) + sess, err := session.NewSession(cfg) + if err != nil { + log.Fatalf("cannot create COS session: %v", err) + } + return s3.New(sess) +} diff --git a/network-isolation/inbound-webhooks/src/consumer/cos_test.go b/network-isolation/inbound-webhooks/src/consumer/cos_test.go new file mode 100644 index 000000000..7b8ee7da6 --- /dev/null +++ b/network-isolation/inbound-webhooks/src/consumer/cos_test.go @@ -0,0 +1,44 @@ +package main + +import ( + "encoding/base64" + "strings" + "testing" + "time" +) + +func fakeJWT(claims string) string { + enc := base64.RawURLEncoding + return enc.EncodeToString([]byte(`{"alg":"none"}`)) + "." + enc.EncodeToString([]byte(claims)) + ".sig" +} + +func TestJWTExpiry(t *testing.T) { + got, err := jwtExpiry(fakeJWT(`{"sub":"x","exp":1795000000}`)) + if err != nil { + t.Fatalf("jwtExpiry() error = %v", err) + } + if want := time.Unix(1795000000, 0); !got.Equal(want) { + t.Fatalf("jwtExpiry() = %v, want %v", got, want) + } +} + +func TestJWTExpiryErrors(t *testing.T) { + tests := []struct { + name string + token string + want string + }{ + {"not a JWT", "opaque-token", "not a JWT"}, + {"invalid base64", "a.!!!.c", "cannot decode"}, + {"invalid JSON", fakeJWT("not json"), "cannot parse"}, + {"no exp claim", fakeJWT(`{"sub":"x"}`), "no exp claim"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := jwtExpiry(tt.token) + if err == nil || !strings.Contains(err.Error(), tt.want) { + t.Fatalf("jwtExpiry() error = %v, want it to contain %q", err, tt.want) + } + }) + } +} diff --git a/network-isolation/inbound-webhooks/src/consumer/env.go b/network-isolation/inbound-webhooks/src/consumer/env.go new file mode 100644 index 000000000..826802029 --- /dev/null +++ b/network-isolation/inbound-webhooks/src/consumer/env.go @@ -0,0 +1,23 @@ +package main + +import ( + "log" + "os" +) + +// mustEnv returns the value of an environment variable and exits if it is not set. +func mustEnv(name string) string { + v := os.Getenv(name) + if v == "" { + log.Fatalf("environment variable %s is required", name) + } + return v +} + +// getEnv returns the value of an environment variable, or the fallback if it is not set. +func getEnv(name, fallback string) string { + if v := os.Getenv(name); v != "" { + return v + } + return fallback +} diff --git a/network-isolation/inbound-webhooks/src/consumer/envelope.go b/network-isolation/inbound-webhooks/src/consumer/envelope.go new file mode 100644 index 000000000..0e87146d8 --- /dev/null +++ b/network-isolation/inbound-webhooks/src/consumer/envelope.go @@ -0,0 +1,26 @@ +package main + +import ( + "encoding/json" + "fmt" +) + +// envelope is the object webhook-receiver (src/receiver/main.js) writes to COS and webhook-consumer reads. +type envelope struct { + ReceivedAt string `json:"received_at"` + DeliveryID string `json:"delivery_id"` + Event string `json:"event"` + Headers map[string][]string `json:"headers"` + Payload json.RawMessage `json:"payload"` +} + +func parseEnvelope(data []byte) (envelope, error) { + var env envelope + if err := json.Unmarshal(data, &env); err != nil { + return env, fmt.Errorf("object is not a valid envelope: %w", err) + } + if env.DeliveryID == "" || env.Event == "" || len(env.Payload) == 0 { + return env, fmt.Errorf("envelope is incomplete (delivery_id, event and payload are required)") + } + return env, nil +} diff --git a/network-isolation/inbound-webhooks/src/consumer/go.mod b/network-isolation/inbound-webhooks/src/consumer/go.mod new file mode 100644 index 000000000..b04f04fd8 --- /dev/null +++ b/network-isolation/inbound-webhooks/src/consumer/go.mod @@ -0,0 +1,30 @@ +module github.com/IBM/CodeEngine/network-isolation/inbound-webhooks/src/consumer + +go 1.27.3 + +require ( + github.com/IBM/go-sdk-core/v5 v5.25.3 + github.com/IBM/ibm-cos-sdk-go v1.15.2 +) + +require ( + github.com/gabriel-vasile/mimetype v1.4.16 // indirect + github.com/go-openapi/errors v0.22.9 // indirect + github.com/go-openapi/strfmt v0.27.4 // indirect + github.com/go-playground/locales v0.14.2 // indirect + github.com/go-playground/universal-translator v0.18.2 // indirect + github.com/go-playground/validator/v10 v10.30.5 // indirect + github.com/go-viper/mapstructure/v2 v2.5.0 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/hashicorp/go-cleanhttp v0.5.2 // indirect + github.com/hashicorp/go-retryablehttp v0.7.8 // indirect + github.com/jmespath/go-jmespath v0.4.0 // indirect + github.com/leodido/go-urn v1.5.0 // indirect + github.com/oklog/ulid/v2 v2.1.2 // indirect + go.yaml.in/yaml/v2 v2.4.4 // indirect + golang.org/x/crypto v0.58.0 // indirect + golang.org/x/net v0.62.0 // indirect + golang.org/x/sys v0.49.0 // indirect + golang.org/x/text v0.43.0 // indirect + sigs.k8s.io/yaml v1.6.0 // indirect +) diff --git a/network-isolation/inbound-webhooks/src/consumer/go.sum b/network-isolation/inbound-webhooks/src/consumer/go.sum new file mode 100644 index 000000000..13b57fe61 --- /dev/null +++ b/network-isolation/inbound-webhooks/src/consumer/go.sum @@ -0,0 +1,91 @@ +github.com/IBM/go-sdk-core/v5 v5.25.3 h1:dL7r1nLoi3xPtX0MdMl0FA0WAM6E6oz40KIu4LwEloI= +github.com/IBM/go-sdk-core/v5 v5.25.3/go.mod h1:83BKM+mYr4eUlkiCJWf36wjF7PSdOOAxeIjTfoSCnTg= +github.com/IBM/ibm-cos-sdk-go v1.15.2 h1:5SXCSNgFKAiPINaRtZ+t/eRAD5RLjuDi/apTCl79Z40= +github.com/IBM/ibm-cos-sdk-go v1.15.2/go.mod h1:+06KEpXznSyE8u3G4Ufgtor1Mnop0odPDvQaZpd9NjY= +github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0= +github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/fatih/color v1.16.0 h1:zmkK9Ngbjj+K0yRhTVONQh1p/HknKYSlNT+vZCzyokM= +github.com/fatih/color v1.16.0/go.mod h1:fL2Sau1YI5c0pdGEVCbKQbLXB6edEj1ZgiY4NijnWvE= +github.com/gabriel-vasile/mimetype v1.4.16 h1:5izNFuvA37st1dDRAcA7TtmngBmRgiIPDmTtiEvjx1E= +github.com/gabriel-vasile/mimetype v1.4.16/go.mod h1:3oFFwxX8kTklZwzIl2aQEDZT0lKY8xH92ST88bAwba4= +github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= +github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-openapi/errors v0.22.9 h1:HI9+SyVYiRzyeBQGv0CbWbQa+u2S0nny7G7AhY+UMiM= +github.com/go-openapi/errors v0.22.9/go.mod h1:R73q66sXP2smzAGgFOI4nqtusRK2xN5pYCjsij+KX58= +github.com/go-openapi/strfmt v0.27.4 h1:E1xsvHb8R9vsuYru4TP2PVVTv9AIgSFAUACUZrFQfCI= +github.com/go-openapi/strfmt v0.27.4/go.mod h1:SCOff81PPhU26acBiW96jHaFycEbT2nkQRvojM+V2z0= +github.com/go-openapi/testify/v2 v2.8.0 h1:19QDx5b57p8KjO2E4sgs/woL4Akp+FGLRlVm2xn0Rho= +github.com/go-openapi/testify/v2 v2.8.0/go.mod h1:4gUN8jC+RqOE2qjW/vDmfyTvl5BCht4qL7oca0odrak= +github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= +github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.14.2 h1:d8UmcrM6Nip0hfGZKLGpAvZH37XB4TS0xzK9B56YNCY= +github.com/go-playground/locales v0.14.2/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.2 h1:LCsMLC9RzmbUMNUPVYD15dmcjwYAJhmX8mPZRW4rAVU= +github.com/go-playground/universal-translator v0.18.2/go.mod h1:67VZIMp5lQpDWlnStOct22q1bkdJGJqHghbOtmkawxk= +github.com/go-playground/validator/v10 v10.30.5 h1:YyCXvVShZbs2Sm3Mb53eNOlhRXctSOzW5QJAouCTZL4= +github.com/go-playground/validator/v10 v10.30.5/go.mod h1:wEqiaov48pXX1kjhc3Da8y0M0Dtg/BK7gurFBLgwFrQ= +github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= +github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= +github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro= +github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/pprof v0.0.0-20260402051712-545e8a4df936 h1:EwtI+Al+DeppwYX2oXJCETMO23COyaKGP6fHVpkpWpg= +github.com/google/pprof v0.0.0-20260402051712-545e8a4df936/go.mod h1:MxpfABSjhmINe3F1It9d+8exIHFvUqtLIRCdOGNXqiI= +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/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ= +github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48= +github.com/hashicorp/go-hclog v1.6.3 h1:Qr2kF+eVWjTiYmU7Y31tYlP1h0q/X3Nl3tPGdaB11/k= +github.com/hashicorp/go-hclog v1.6.3/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M= +github.com/hashicorp/go-retryablehttp v0.7.8 h1:ylXZWnqa7Lhqpk0L1P1LzDtGcCR0rPVUrx/c8Unxc48= +github.com/hashicorp/go-retryablehttp v0.7.8/go.mod h1:rjiScheydd+CxvumBsIrFKlx3iS0jrZ7LvzFGFmuKbw= +github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= +github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= +github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8= +github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= +github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0= +github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/oklog/ulid/v2 v2.1.2 h1:IEclFb9JNvzYA6MW2SCxbLzcHTVsfqm3PrqGQJH5zec= +github.com/oklog/ulid/v2 v2.1.2/go.mod h1:rcEKHmBBKfef9DhnvX7y1HZBYxjXb0cP5ExxNsTT1QQ= +github.com/onsi/ginkgo/v2 v2.33.1 h1:62XfWJbEIjPSCSDYrsCPP/SHcmH7O0M8ne8zfqQ2iz4= +github.com/onsi/ginkgo/v2 v2.33.1/go.mod h1:+aXOY+vzZ5mu2iI2HpTZUPmM//oQfsNFX6gU9kNcA44= +github.com/onsi/gomega v1.44.0 h1:eAiGl3Pw5jz5GQdDff0BcxYpAX1JxW8xD7mFUuwNfZQ= +github.com/onsi/gomega v1.44.0/go.mod h1:e/C2HwaZ1DhvjzXXuFhcR7hY7Sh9pl7MmoWKEjzwcdA= +github.com/pborman/getopt v0.0.0-20170112200414-7148bc3a4c30/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ= +go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= +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/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c= +golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o= +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/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= +golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= +golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= +golang.org/x/tools v0.51.0 h1:k4Xc/1Om9jwkBJBo4NVLMSARBoWtK10mx+W5BnXCeAI= +golang.org/x/tools v0.51.0/go.mod h1:9eEncMayCV6zRMGhR5eZEC2iBx98qWcF1HZ9Z7wJOoA= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +sigs.k8s.io/yaml v1.6.0 h1:G8fkbMSAFqgEFgh4b1wmtzDnioxFCUgTZhlbj5P9QYs= +sigs.k8s.io/yaml v1.6.0/go.mod h1:796bPqUfzR/0jLAl6XjHl3Ck7MiyVv8dbTdyT3/pMf4= diff --git a/network-isolation/inbound-webhooks/src/consumer/main.go b/network-isolation/inbound-webhooks/src/consumer/main.go new file mode 100644 index 000000000..0900d77d3 --- /dev/null +++ b/network-isolation/inbound-webhooks/src/consumer/main.go @@ -0,0 +1,140 @@ +// webhook-consumer receives IBM Cloud Object Storage events from a Code Engine +// subscription, reads the referenced object (a webhook envelope written by +// webhook-receiver) and logs meaningful data from it. +// +// It answers 2xx only if the object was read and parsed successfully, and +// non-2xx otherwise. It never deletes or modifies objects. +package main + +import ( + "encoding/json" + "fmt" + "log" + "net/http" + "strings" +) + +const maxEventBytes = 1 << 20 // COS event notifications are small + +// cosEvent is the HTTP body of a Code Engine Object Storage event. +type cosEvent struct { + Bucket string `json:"bucket"` + Key string `json:"key"` + Operation string `json:"operation"` + Notification struct { + EventType string `json:"event_type"` + ObjectLength string `json:"object_length"` + RequestID string `json:"request_id"` + } `json:"notification"` +} + +// --- Your business logic: adapt this block for your webhook payloads --------- + +// payloadSummary holds the few GitHub payload fields that are logged. +type payloadSummary struct { + Action string `json:"action"` + Ref string `json:"ref"` + Zen string `json:"zen"` + Repository struct { + FullName string `json:"full_name"` + } `json:"repository"` + Sender struct { + Login string `json:"login"` + } `json:"sender"` +} + +// process handles one stored delivery and returns a one-line summary for the log. +// Return an error to answer non-2xx, which Code Engine treats as a failed event delivery. +// The sample only logs; do something useful with the payload here. +func process(key string, env envelope) (string, error) { + var p payloadSummary + if err := json.Unmarshal(env.Payload, &p); err != nil { + return "", fmt.Errorf("payload is not a JSON object: %w", err) + } + + fields := []string{ + "key=" + key, + "delivery=" + env.DeliveryID, + "event=" + env.Event, + "received_at=" + env.ReceivedAt, + } + for _, f := range []struct{ name, value string }{ + {"action", p.Action}, + {"repository", p.Repository.FullName}, + {"sender", p.Sender.Login}, + {"ref", p.Ref}, + {"zen", p.Zen}, + } { + if f.value != "" { + fields = append(fields, fmt.Sprintf("%s=%q", f.name, f.value)) + } + } + fields = append(fields, fmt.Sprintf("payload_bytes=%d", len(env.Payload))) + return strings.Join(fields, " "), nil +} + +// ----------------------------------------------------------------------------- + +type consumer struct { + bucket string + store objectGetter +} + +func (c *consumer) ServeHTTP(w http.ResponseWriter, req *http.Request) { + if req.Method != http.MethodPost { + w.Header().Set("Allow", http.MethodPost) + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + + var ev cosEvent + dec := json.NewDecoder(http.MaxBytesReader(w, req.Body, maxEventBytes)) + if err := dec.Decode(&ev); err != nil { + log.Printf("cannot parse event (ce-id=%s): %v", req.Header.Get("Ce-Id"), err) + http.Error(w, "invalid event", http.StatusBadRequest) + return + } + log.Printf("event ce-id=%s ce-type=%s bucket=%s key=%s operation=%s", + req.Header.Get("Ce-Id"), req.Header.Get("Ce-Type"), ev.Bucket, ev.Key, ev.Operation) + + // only new/updated objects are of interest + if ev.Operation != "Object:Write" { + log.Printf("ignoring operation %q for key %s", ev.Operation, ev.Key) + fmt.Fprintln(w, "ignored") + return + } + if ev.Bucket != c.bucket || ev.Key == "" { + log.Printf("rejecting event for unexpected bucket %q or empty key %q", ev.Bucket, ev.Key) + http.Error(w, "unexpected bucket or key", http.StatusBadRequest) + return + } + + data, err := c.store.Get(req.Context(), ev.Bucket, ev.Key) + if err != nil { + log.Printf("ERROR key=%s: reading object failed: %v", ev.Key, err) + http.Error(w, "reading object failed", http.StatusInternalServerError) + return + } + env, err := parseEnvelope(data) + if err != nil { + log.Printf("ERROR key=%s: %v", ev.Key, err) + http.Error(w, "processing failed", http.StatusInternalServerError) + return + } + summary, err := process(ev.Key, env) + if err != nil { + log.Printf("ERROR key=%s: %v", ev.Key, err) + http.Error(w, "processing failed", http.StatusInternalServerError) + return + } + + log.Printf("processed webhook %s", summary) + fmt.Fprintln(w, "processed") +} + +func main() { + bucket := mustEnv("COS_BUCKET") + + log.Printf("reading from bucket %s", bucket) + serve("webhook-consumer", &consumer{bucket: bucket, store: &cosGetter{client: newCOSClient()}}) +} diff --git a/network-isolation/inbound-webhooks/src/consumer/main_test.go b/network-isolation/inbound-webhooks/src/consumer/main_test.go new file mode 100644 index 000000000..8e75089df --- /dev/null +++ b/network-isolation/inbound-webhooks/src/consumer/main_test.go @@ -0,0 +1,125 @@ +package main + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +const sampleEnvelope = `{ + "received_at": "2026-11-13T12:00:00Z", + "delivery_id": "72d3162e-cc78-11e3-81ab-4c9367dc0958", + "event": "push", + "headers": {"X-Github-Event": ["push"]}, + "payload": {"ref": "refs/heads/main", "repository": {"full_name": "octo/repo"}, "sender": {"login": "octocat"}} +}` + +// describe runs the same steps as the handler: parse the envelope, then process it. +func describe(key string, data []byte) (string, error) { + env, err := parseEnvelope(data) + if err != nil { + return "", err + } + return process(key, env) +} + +func TestDescribe(t *testing.T) { + got, err := describe("some-key.json", []byte(sampleEnvelope)) + if err != nil { + t.Fatalf("describe() error: %v", err) + } + for _, want := range []string{ + "key=some-key.json", + "delivery=72d3162e-cc78-11e3-81ab-4c9367dc0958", + "event=push", + `repository="octo/repo"`, + `sender="octocat"`, + `ref="refs/heads/main"`, + } { + if !strings.Contains(got, want) { + t.Errorf("summary %q does not contain %q", got, want) + } + } +} + +func TestDescribeRejectsBadObjects(t *testing.T) { + for name, data := range map[string]string{ + "not json": `hello`, + "missing fields": `{"event":"push"}`, + "payload not json": `{"delivery_id":"x","event":"push","payload":"text"}`, + } { + t.Run(name, func(t *testing.T) { + if _, err := describe("k", []byte(data)); err == nil { + t.Fatal("expected an error") + } + }) + } +} + +type fakeGetter struct { + data []byte + err error + got string +} + +func (f *fakeGetter) Get(_ context.Context, bucket, key string) ([]byte, error) { + f.got = bucket + "/" + key + return f.data, f.err +} + +func post(c *consumer, body string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(body)) + rec := httptest.NewRecorder() + c.ServeHTTP(rec, req) + return rec +} + +const writeEvent = `{"bucket":"queue","key":"k.json","operation":"Object:Write","notification":{"event_type":"Object:Write"}}` + +func TestHandlerSuccess(t *testing.T) { + store := &fakeGetter{data: []byte(sampleEnvelope)} + rec := post(&consumer{bucket: "queue", store: store}, writeEvent) + + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200", rec.Code) + } + if store.got != "queue/k.json" { + t.Fatalf("fetched %q, want queue/k.json", store.got) + } +} + +func TestHandlerFailuresAreNon2xx(t *testing.T) { + tests := []struct { + name string + store *fakeGetter + body string + want int + }{ + {"read error", &fakeGetter{err: errors.New("boom")}, writeEvent, http.StatusInternalServerError}, + {"bad object", &fakeGetter{data: []byte("nope")}, writeEvent, http.StatusInternalServerError}, + {"bad event", &fakeGetter{}, `not json`, http.StatusBadRequest}, + {"other bucket", &fakeGetter{}, `{"bucket":"other","key":"k","operation":"Object:Write"}`, http.StatusBadRequest}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if rec := post(&consumer{bucket: "queue", store: tt.store}, tt.body); rec.Code != tt.want { + t.Fatalf("status = %d, want %d", rec.Code, tt.want) + } + }) + } +} + +func TestHandlerIgnoresDelete(t *testing.T) { + store := &fakeGetter{} + rec := post(&consumer{bucket: "queue", store: store}, `{"bucket":"queue","key":"k","operation":"Object:Delete"}`) + + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200", rec.Code) + } + if store.got != "" { + t.Fatalf("object must not be fetched for delete events, fetched %q", store.got) + } +} diff --git a/network-isolation/inbound-webhooks/src/consumer/server.go b/network-isolation/inbound-webhooks/src/consumer/server.go new file mode 100644 index 000000000..c137a148a --- /dev/null +++ b/network-isolation/inbound-webhooks/src/consumer/server.go @@ -0,0 +1,42 @@ +package main + +import ( + "context" + "errors" + "log" + "net/http" + "os" + "os/signal" + "syscall" + "time" +) + +// serve runs the handler on $PORT (default 8080) until SIGTERM or interrupt, then lets +// in-flight requests finish. Code Engine sends SIGTERM when it scales down or replaces a revision. +func serve(name string, handler http.Handler) { + port := getEnv("PORT", "8080") + srv := &http.Server{ + Addr: ":" + port, + Handler: handler, + ReadHeaderTimeout: 10 * time.Second, + ReadTimeout: 60 * time.Second, + WriteTimeout: 60 * time.Second, + } + + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt) + defer stop() + go func() { + log.Printf("%s listening on :%s", name, port) + if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) { + log.Fatal(err) + } + }() + <-ctx.Done() + + log.Printf("shutting down") + shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := srv.Shutdown(shutdownCtx); err != nil { + log.Printf("shutdown: %v", err) + } +} diff --git a/network-isolation/inbound-webhooks/src/receiver/.ceignore b/network-isolation/inbound-webhooks/src/receiver/.ceignore new file mode 100644 index 000000000..3c3629e64 --- /dev/null +++ b/network-isolation/inbound-webhooks/src/receiver/.ceignore @@ -0,0 +1 @@ +node_modules diff --git a/network-isolation/inbound-webhooks/src/receiver/main.js b/network-isolation/inbound-webhooks/src/receiver/main.js new file mode 100644 index 000000000..f3f6af3b1 --- /dev/null +++ b/network-isolation/inbound-webhooks/src/receiver/main.js @@ -0,0 +1,248 @@ +// webhook-receiver is a Code Engine function that receives webhooks, validates their HMAC +// signature and stores every valid delivery as one JSON envelope object in a COS bucket. +// +// It is written for GitHub; the sender-specific part is marked below. +// +// It is deployed as a code bundle (see ../../build) and authenticates to COS with the +// Code Engine trusted profile (compute resource token), no API key involved. +'use strict'; + +const crypto = require('node:crypto'); + +const { ContainerAuthenticator } = require('ibm-cloud-sdk-core'); +const COS = require('ibm-cos-sdk'); + +// --- Sender-specific part: adapt this block for your webhook sender ---------- + +// Code Engine functions accept request bodies up to 5 MB (GitHub sends up to 25 MB). Lower it +// with MAX_BODY_BYTES if your sender sends less. +const DEFAULT_MAX_BODY_BYTES = 5 << 20; + +const SIGNATURE_HEADER = 'x-hub-signature-256'; +const DELIVERY_HEADER = 'x-github-delivery'; +const EVENT_HEADER = 'x-github-event'; + +// delivery IDs are GUIDs; only accept characters that are safe in an object key +const DELIVERY_ID_PATTERN = /^[A-Za-z0-9-]{1,64}$/; + +// verifySignature checks the X-Hub-Signature-256 header value ("sha256=") +// against the HMAC-SHA256 of the raw body, using a constant-time comparison. +function verifySignature(secret, body, header) { + if (typeof header !== 'string' || !header.startsWith('sha256=')) { + return false; + } + const hexSig = header.slice('sha256='.length); + if (!/^(?:[0-9a-fA-F]{2})+$/.test(hexSig)) { + return false; + } + const got = Buffer.from(hexSig, 'hex'); + const want = crypto.createHmac('sha256', secret).update(body).digest(); + return got.length === want.length && crypto.timingSafeEqual(got, want); +} + +// canonicalHeaderName turns "x-github-event" into "X-Github-Event". +function canonicalHeaderName(name) { + return name + .split('-') + .map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()) + .join('-'); +} + +// storedHeaders returns the request headers worth keeping. It is an allow list, +// so the signature and any credentials are never stored. +function storedHeaders(headers) { + const out = {}; + for (const [name, value] of Object.entries(headers)) { + const lower = name.toLowerCase(); + if (lower.startsWith('x-github-') || lower === 'content-type' || lower === 'user-agent') { + out[canonicalHeaderName(lower)] = [String(value)]; + } + } + return out; +} + +// ----------------------------------------------------------------------------- + +// GitHub gives up on a delivery after 10 seconds, so fail the COS write before that. +const STORE_TIMEOUT_MS = 8000; + +// requireEnv returns the value of an environment variable and throws if it is unset or empty. +function requireEnv(name) { + const value = process.env[name]; + if (!value) { + throw new Error(`environment variable ${name} is required`); + } + return value; +} + +// expiryOf returns the expiry time (ms since the epoch) of an IAM access token, which is a JWT. +function expiryOf(accessToken) { + const claims = JSON.parse(Buffer.from(accessToken.split('.')[1], 'base64url').toString('utf8')); + return claims.exp * 1000; +} + +// cosStore writes objects to a bucket. The authenticator, a ContainerAuthenticator of the IBM Cloud SDK +// core, exchanges the compute resource token that Code Engine mounts into the function for an IAM access +// token of the trusted profile, and caches and renews it. The COS SDK asks for that token through authCallback. +// put aborts the request after timeoutMs in total (including retries), so a failed put does not +// leave a write running that could still store the object after the sender was told it failed. +function cosStore({ endpoint, bucket, authenticator, timeoutMs = STORE_TIMEOUT_MS }) { + const cos = new COS.S3({ + endpoint, + s3ForcePathStyle: true, + maxRetries: 1, + httpOptions: { connectTimeout: 3000, timeout: timeoutMs }, + authCallback: async () => { + const request = { headers: {} }; + await authenticator.authenticate(request); + const accessToken = request.headers.Authorization.replace(/^Bearer /, ''); + return { accessToken, expiration: expiryOf(accessToken) }; + }, + }); + + return { + async put(key, body) { + const request = cos.putObject({ Bucket: bucket, Key: key, Body: body, ContentType: 'application/json' }); + const timer = setTimeout(() => request.abort(), timeoutMs); + try { + await request.promise(); + } finally { + clearTimeout(timer); + } + }, + }; +} + +// withTimeout fails the promise if it does not settle within ms milliseconds. +async function withTimeout(promise, ms) { + let timer; + try { + return await Promise.race([ + promise, + new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error(`timed out after ${ms} ms`)), ms); + }), + ]); + } finally { + clearTimeout(timer); + } +} + +// reply builds a plain text function response; headers are added to the Content-Type header. +function reply(statusCode, text, headers = {}) { + return { statusCode, headers: { 'Content-Type': 'text/plain', ...headers }, body: `${text}\n` }; +} + +// bodyEncoding returns how Code Engine encodes __ce_body: Base64 for JSON, plain text otherwise. +function bodyEncoding(contentType) { + return contentType.toLowerCase().startsWith('application/json') ? 'base64' : 'utf8'; +} + +// requestBody returns the raw request body. Code Engine passes it in __ce_body, encoded as bodyEncoding says. +function requestBody(args, encoding) { + const raw = args.__ce_body; + return typeof raw === 'string' ? Buffer.from(raw, encoding) : Buffer.alloc(0); +} + +// createReceiver returns the request handler. secret is the webhook signing secret, store has an +// async put(key, body) method, now returns the current Date (injectable for tests), and maxBytes +// is the largest accepted request body. +function createReceiver({ secret, store, now = () => new Date(), maxBytes = DEFAULT_MAX_BODY_BYTES }) { + return async function receive(args) { + if (args.__ce_method !== 'POST') { + return reply(405, 'method not allowed', { Allow: 'POST' }); + } + + const headers = {}; + for (const [name, value] of Object.entries(args.__ce_headers || {})) { + headers[name.toLowerCase()] = value; + } + + // reject unsigned requests before looking at the body + const sig = headers[SIGNATURE_HEADER]; + if (!sig) { + console.log(`rejected: missing ${SIGNATURE_HEADER} header`); + return reply(403, 'missing signature'); + } + + // Reject oversized bodies before decoding them: the decoded size is known without allocating the + // buffer, so a body that is not signed correctly does not cost memory proportional to its size. + const encoding = bodyEncoding(String(headers['content-type'] || '')); + if (typeof args.__ce_body === 'string' && Buffer.byteLength(args.__ce_body, encoding) > maxBytes) { + return reply(413, 'payload too large'); + } + const body = requestBody(args, encoding); + + // validate the signature over the raw body before looking at anything else + if (!verifySignature(secret, body, sig)) { + console.log('rejected: signature mismatch'); + return reply(403, 'signature mismatch'); + } + + const deliveryId = headers[DELIVERY_HEADER]; + const event = headers[EVENT_HEADER]; + if (!DELIVERY_ID_PATTERN.test(deliveryId || '') || !event) { + console.log(`rejected: missing or invalid ${DELIVERY_HEADER} / ${EVENT_HEADER}`); + return reply(400, 'missing or invalid delivery headers'); + } + const payload = body.toString('utf8'); + try { + JSON.parse(payload); + } catch { + console.log(`rejected: delivery ${deliveryId} has no valid JSON body (content type must be application/json)`); + return reply(400, 'body must be JSON'); + } + + const received = now(); + // the payload is embedded as it was received, so the signed bytes stay intact + const envelope = + '{' + + `"received_at":${JSON.stringify(received.toISOString())},` + + `"delivery_id":${JSON.stringify(deliveryId)},` + + `"event":${JSON.stringify(event)},` + + `"headers":${JSON.stringify(storedHeaders(args.__ce_headers || {}))},` + + `"payload":${payload}` + + '}'; + + const key = `${received.toISOString().replace(/[-:]/g, '')}-${deliveryId}.json`; + try { + await withTimeout(store.put(key, envelope), STORE_TIMEOUT_MS); + } catch (err) { + // 5xx so that the failed delivery is visible in the sender and can be redelivered + console.log(`delivery ${deliveryId}: storing ${key} failed: ${err.message}`); + return reply(500, 'storing delivery failed'); + } + + console.log(`stored delivery ${deliveryId} (event ${event}) as ${key}`); + return reply(202, 'accepted'); + }; +} + +let receiver; + +// main is the entry point of the Code Engine function. The receiver is created on the first request, +// so the environment is only read once per function instance. +async function main(args) { + if (!receiver) { + const maxBytes = Number(process.env.MAX_BODY_BYTES || DEFAULT_MAX_BODY_BYTES); + if (!Number.isInteger(maxBytes) || maxBytes <= 0) { + throw new Error('MAX_BODY_BYTES must be a positive integer'); + } + receiver = createReceiver({ + secret: requireEnv('WEBHOOK_SECRET'), + maxBytes, + store: cosStore({ + endpoint: requireEnv('COS_ENDPOINT'), + bucket: requireEnv('COS_BUCKET'), + authenticator: new ContainerAuthenticator({ + iamProfileId: requireEnv('TRUSTED_PROFILE_ID'), + url: process.env.IBM_AUTH_ENDPOINT || 'https://private.iam.cloud.ibm.com', + }), + }), + }); + console.log(`writing to bucket ${process.env.COS_BUCKET}`); + } + return receiver(args); +} + +module.exports = { main, createReceiver, cosStore, verifySignature, storedHeaders }; diff --git a/network-isolation/inbound-webhooks/src/receiver/main.test.js b/network-isolation/inbound-webhooks/src/receiver/main.test.js new file mode 100644 index 000000000..7bdd9fecd --- /dev/null +++ b/network-isolation/inbound-webhooks/src/receiver/main.test.js @@ -0,0 +1,283 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const crypto = require('node:crypto'); +const fs = require('node:fs'); +const http = require('node:http'); +const os = require('node:os'); +const path = require('node:path'); + +const { ContainerAuthenticator } = require('ibm-cloud-sdk-core'); + +const { createReceiver, cosStore, verifySignature, storedHeaders } = require('./main.js'); + +const VECTOR_SECRET = "It's a Secret to Everybody"; +const VECTOR_PAYLOAD = 'Hello, World!'; +const VECTOR_SIGNATURE = 'sha256=757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17'; +const DELIVERY_ID = '72d3162e-cc78-11e3-81ab-4c9367dc0958'; + +test('verifySignature', async (t) => { + const secret = VECTOR_SECRET; + const body = Buffer.from(VECTOR_PAYLOAD); + const hex = VECTOR_SIGNATURE.slice('sha256='.length); + + const cases = [ + ['documented vector', secret, body, VECTOR_SIGNATURE, true], + ['wrong secret', 'other', body, VECTOR_SIGNATURE, false], + ['modified body', secret, Buffer.from('Hello, World?'), VECTOR_SIGNATURE, false], + ['missing prefix', secret, body, hex, false], + ['sha1 prefix', secret, body, `sha1=${hex}`, false], + ['not hex', secret, body, 'sha256=zzzz', false], + ['truncated', secret, body, VECTOR_SIGNATURE.slice(0, -2), false], + ['empty', secret, body, '', false], + ]; + for (const [name, s, b, header, want] of cases) { + await t.test(name, () => assert.equal(verifySignature(s, b, header), want)); + } +}); + +test('storedHeaders only keeps the allow list', () => { + const got = storedHeaders({ + 'X-Github-Event': 'push', + 'x-github-delivery': DELIVERY_ID, + 'Content-Type': 'application/json', + 'User-Agent': 'GitHub-Hookshot/abc', + 'X-Hub-Signature-256': VECTOR_SIGNATURE, + Authorization: 'Bearer should-not-be-stored', + }); + assert.deepEqual(got, { + 'X-Github-Event': ['push'], + 'X-Github-Delivery': [DELIVERY_ID], + 'Content-Type': ['application/json'], + 'User-Agent': ['GitHub-Hookshot/abc'], + }); +}); + +function signatureFor(secret, payload) { + return `sha256=${crypto.createHmac('sha256', secret).update(payload).digest('hex')}`; +} + +// newRequest builds the arguments that Code Engine passes to the function for a signed GitHub delivery. +// JSON bodies arrive Base64-encoded in __ce_body. +function newRequest(payload) { + return { + __ce_method: 'POST', + __ce_path: '/', + __ce_body: Buffer.from(payload).toString('base64'), + __ce_headers: { + 'Content-Type': 'application/json', + 'X-GitHub-Event': 'push', + 'X-GitHub-Delivery': DELIVERY_ID, + Authorization: 'Bearer should-not-be-stored', + 'X-Hub-Signature-256': signatureFor(VECTOR_SECRET, payload), + }, + }; +} + +// setBody replaces the request body and re-signs it, so only the body itself is invalid. +function setBody(req, payload) { + req.__ce_body = Buffer.from(payload).toString('base64'); + req.__ce_headers['X-Hub-Signature-256'] = signatureFor(VECTOR_SECRET, payload); +} + +function fakeStore(err) { + return { + keys: [], + bodies: [], + async put(key, body) { + if (err) { + throw err; + } + this.keys.push(key); + this.bodies.push(body); + }, + }; +} + +test('handler stores a valid delivery', async () => { + const store = fakeStore(); + const receive = createReceiver({ + secret: VECTOR_SECRET, + store, + now: () => new Date('2026-11-13T12:00:00Z'), + }); + const payload = '{"zen":"Keep it logically awesome.","repository":{"full_name":"octo/repo"}}'; + + const res = await receive(newRequest(payload)); + + assert.equal(res.statusCode, 202); + assert.deepEqual(store.keys, [`20261113T120000.000Z-${DELIVERY_ID}.json`]); + + const env = JSON.parse(store.bodies[0]); + assert.equal(env.event, 'push'); + assert.equal(env.delivery_id, DELIVERY_ID); + assert.equal(env.received_at, '2026-11-13T12:00:00.000Z'); + assert.deepEqual(env.payload, JSON.parse(payload)); + assert.ok(store.bodies[0].endsWith(`"payload":${payload}}`), 'payload must be stored as received'); + for (const name of Object.keys(env.headers)) { + assert.ok(!/^(x-hub-signature-256|authorization)$/i.test(name), `header ${name} must not be stored`); + } +}); + +test('handler rejects bad requests and stores nothing', async (t) => { + const cases = [ + ['wrong signature', (req) => (req.__ce_headers['X-Hub-Signature-256'] = VECTOR_SIGNATURE), 403], + ['missing signature', (req) => delete req.__ce_headers['X-Hub-Signature-256'], 403], + ['missing delivery id', (req) => delete req.__ce_headers['X-GitHub-Delivery'], 400], + ['unsafe delivery id', (req) => (req.__ce_headers['X-GitHub-Delivery'] = '../evil'), 400], + ['missing event', (req) => delete req.__ce_headers['X-GitHub-Event'], 400], + ['invalid JSON body', (req) => setBody(req, 'not json'), 400], + ['payload too large', (req) => setBody(req, 'x'.repeat(100)), 413], + ['wrong method', (req) => (req.__ce_method = 'GET'), 405], + ]; + for (const [name, mutate, want] of cases) { + await t.test(name, async () => { + const store = fakeStore(); + const receive = createReceiver({ secret: VECTOR_SECRET, store, maxBytes: 64 }); + const req = newRequest('{"a":1}'); + mutate(req); + + const res = await receive(req); + + assert.equal(res.statusCode, want); + assert.deepEqual(store.keys, []); + }); + } +}); + +test('handler accepts a mixed-case JSON content type', async () => { + const store = fakeStore(); + const receive = createReceiver({ secret: VECTOR_SECRET, store }); + const req = newRequest('{"a":1}'); + delete req.__ce_headers['Content-Type']; + req.__ce_headers['content-type'] = 'Application/JSON; charset=utf-8'; + + const res = await receive(req); + + assert.equal(res.statusCode, 202); + assert.equal(store.keys.length, 1); +}); + +test('handler answers 5xx when storing fails', async () => { + const receive = createReceiver({ secret: VECTOR_SECRET, store: fakeStore(new Error('boom')) }); + + const res = await receive(newRequest('{"a":1}')); + + assert.equal(res.statusCode, 500); +}); + +// A local server that plays IAM (POST /identity/token) and COS (PUT //). +function startFakeIamAndCos() { + const server = http.createServer((req, res) => { + const chunks = []; + req.on('data', (chunk) => chunks.push(chunk)); + req.on('end', () => { + const body = Buffer.concat(chunks).toString('utf8'); + if (req.method === 'POST' && req.url === '/identity/token') { + server.tokenRequests.push(new URLSearchParams(body)); + const exp = Math.floor(Date.now() / 1000) + 3600; + const jwt = ['{"alg":"none"}', JSON.stringify({ exp })] + .map((part) => Buffer.from(part).toString('base64url')) + .join('.') + '.sig'; + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify({ access_token: jwt, token_type: 'Bearer', expires_in: 3600, expiration: exp })); + } else if (req.method === 'PUT') { + server.puts.push({ url: req.url, authorization: req.headers.authorization, body }); + res.setHeader('ETag', '"abc"'); + res.end(); + } else { + res.statusCode = 404; + res.end(); + } + }); + }); + server.tokenRequests = []; + server.puts = []; + return new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve(server))); +} + +test('cosStore writes with the access token of the trusted profile', async () => { + const server = await startFakeIamAndCos(); + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'receiver-test-')); + const tokenFile = path.join(dir, 'token'); + fs.writeFileSync(tokenFile, 'compute-resource-token'); + const base = `http://127.0.0.1:${server.address().port}`; + + try { + const store = cosStore({ + endpoint: base, + bucket: 'my-bucket', + // the test token file stands in for the one that Code Engine mounts + authenticator: new ContainerAuthenticator({ + iamProfileId: 'Profile-1234', + crTokenFilename: tokenFile, + url: base, + }), + }); + await store.put('a.json', '{"a":1}'); + await store.put('b.json', '{"b":2}'); + + // one token exchange with the compute resource token and the trusted profile, reused for both writes + assert.equal(server.tokenRequests.length, 1); + const form = server.tokenRequests[0]; + assert.equal(form.get('grant_type'), 'urn:ibm:params:oauth:grant-type:cr-token'); + assert.equal(form.get('cr_token'), 'compute-resource-token'); + assert.equal(form.get('profile_id'), 'Profile-1234'); + + assert.deepEqual( + server.puts.map((p) => [p.url, p.body]), + [ + ['/my-bucket/a.json', '{"a":1}'], + ['/my-bucket/b.json', '{"b":2}'], + ], + ); + for (const put of server.puts) { + assert.match(put.authorization, /^Bearer .+\..+\..+$/); + } + } finally { + server.close(); + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +test('cosStore aborts a write that does not finish in time', async () => { + const server = await startFakeIamAndCos(); + // the COS endpoint accepts the PUT but never answers; the promise settles when the client hangs up + let putClosed; + const closedByClient = new Promise((resolve) => { + putClosed = resolve; + }); + const answerIam = server.listeners('request')[0]; + server.removeAllListeners('request'); + server.on('request', (req, res) => { + if (req.method === 'PUT') { + res.on('close', putClosed); + return; + } + answerIam(req, res); + }); + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'receiver-test-')); + const tokenFile = path.join(dir, 'token'); + fs.writeFileSync(tokenFile, 'compute-resource-token'); + const base = `http://127.0.0.1:${server.address().port}`; + + try { + const store = cosStore({ + endpoint: base, + bucket: 'my-bucket', + timeoutMs: 300, + authenticator: new ContainerAuthenticator({ iamProfileId: 'Profile-1234', crTokenFilename: tokenFile, url: base }), + }); + const started = Date.now(); + + await assert.rejects(store.put('a.json', '{"a":1}')); + + assert.ok(Date.now() - started < 2000, 'put must fail at the deadline'); + await closedByClient; // the request was cancelled, not left running + } finally { + server.closeAllConnections(); + server.close(); + fs.rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/network-isolation/inbound-webhooks/src/receiver/package-lock.json b/network-isolation/inbound-webhooks/src/receiver/package-lock.json new file mode 100644 index 000000000..bc5c2fbef --- /dev/null +++ b/network-isolation/inbound-webhooks/src/receiver/package-lock.json @@ -0,0 +1,1253 @@ +{ + "name": "webhook-receiver", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "webhook-receiver", + "version": "1.0.0", + "dependencies": { + "ibm-cloud-sdk-core": "5.9.5", + "ibm-cos-sdk": "1.15.2" + }, + "engines": { + "node": ">=22" + } + }, + "node_modules/@borewit/text-codec": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/@borewit/text-codec/-/text-codec-0.2.3.tgz", + "integrity": "sha512-49CycTz1aAZmvFcwkeFyhud1HUmRIB5Tabf7ALV+VA4Iu85MTfz2cUwzPagMFAdVBvrWdkCxG67I30tUwwpKsw==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/@tokenizer/inflate": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@tokenizer/inflate/-/inflate-0.4.1.tgz", + "integrity": "sha512-2mAv+8pkG6GIZiF1kNg1jAjh27IDxEPKwdGul3snfztFerfPGI1LjDezZp3i7BElXompqEtPmoPx6c2wgtWsOA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "token-types": "^6.1.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/@tokenizer/token": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@tokenizer/token/-/token-0.3.0.tgz", + "integrity": "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A==", + "license": "MIT" + }, + "node_modules/@types/debug": { + "version": "4.1.13", + "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.13.tgz", + "integrity": "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==", + "license": "MIT", + "dependencies": { + "@types/ms": "*" + } + }, + "node_modules/@types/ms": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz", + "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==", + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "18.19.130", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.130.tgz", + "integrity": "sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg==", + "license": "MIT", + "dependencies": { + "undici-types": "~5.26.4" + } + }, + "node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "license": "MIT", + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "license": "MIT" + }, + "node_modules/available-typed-arrays": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz", + "integrity": "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==", + "license": "MIT", + "dependencies": { + "possible-typed-array-names": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/axios": { + "version": "1.20.0", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.20.0.tgz", + "integrity": "sha512-r8aOh8j9cGKpgQAqpzrUHnSIc6a59Y3Xf/cv8sy1DrHCkZHzQGEuoq1tARk6qSyDdtQGSDgpb9kFlruzPvrgwg==", + "license": "MIT", + "dependencies": { + "follow-redirects": "^1.16.0", + "form-data": "^4.0.6", + "https-proxy-agent": "^5.0.1", + "proxy-from-env": "^2.1.0" + } + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/buffer": { + "version": "4.9.2", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-4.9.2.tgz", + "integrity": "sha512-xq+q3SRMOxGivLhBNaUdC64hDTQwejJ+H0T/NB1XMtTVEwNTrfFF3gAxiyW0Bu/xWEGhjVKgUcMhCrUy2+uCWg==", + "license": "MIT", + "dependencies": { + "base64-js": "^1.0.2", + "ieee754": "^1.1.4", + "isarray": "^1.0.0" + } + }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", + "license": "BSD-3-Clause" + }, + "node_modules/call-bind": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.9.tgz", + "integrity": "sha512-a/hy+pNsFUTR+Iz8TCJvXudKVLAnz/DyeSUo10I5yvFDQJBFU2s9uqQpoSrJlroHUKoKqzg+epxyP9lqFdzfBQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "get-intrinsic": "^1.3.0", + "set-function-length": "^1.2.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/camelcase": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", + "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/dotenv": { + "version": "16.6.1", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz", + "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", + "license": "MIT" + }, + "node_modules/file-type": { + "version": "21.3.4", + "resolved": "https://registry.npmjs.org/file-type/-/file-type-21.3.4.tgz", + "integrity": "sha512-Ievi/yy8DS3ygGvT47PjSfdFoX+2isQueoYP1cntFW1JLYAuS4GD7NUPGg4zv2iZfV52uDyk5w5Z0TdpRS6Q1g==", + "license": "MIT", + "dependencies": { + "@tokenizer/inflate": "^0.4.1", + "strtok3": "^10.3.4", + "token-types": "^6.1.1", + "uint8array-extras": "^1.4.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sindresorhus/file-type?sponsor=1" + } + }, + "node_modules/follow-redirects": { + "version": "1.16.3", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.3.tgz", + "integrity": "sha512-toOSoqN6d51Wjf1aOFJYcoVv1aND9rj/CwjLU0Vz40oDuSpWDayCeKe4JpL5NL0WdFvoOOCI3BRo69HahjbR1A==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/for-each": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.5.tgz", + "integrity": "sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==", + "license": "MIT", + "dependencies": { + "is-callable": "^1.2.7" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/form-data": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", + "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.4", + "mime-types": "^2.1.35" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/generator-function": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/generator-function/-/generator-function-2.0.1.tgz", + "integrity": "sha512-SFdFmIJi+ybC0vjlHN0ZGVGHc3lgE0DxPAT0djjVg+kjOnSqclqmj0KQ7ykTOLP6YxoqOvuAODGdcHJn+43q3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "license": "MIT", + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/ibm-cloud-sdk-core": { + "version": "5.9.5", + "resolved": "https://registry.npmjs.org/ibm-cloud-sdk-core/-/ibm-cloud-sdk-core-5.9.5.tgz", + "integrity": "sha512-FaHUOeRl3kBZ+vzIx+Tz10e0siOfXsXjxVCNku8lOrD1MReAU4GWeSFbjg5PbJd+GWJWqCuUVwqTjarRIyrdgA==", + "license": "Apache-2.0", + "dependencies": { + "@types/debug": "4.1.13", + "@types/node": "18.19.130", + "axios": "1.20.0", + "camelcase": "6.3.0", + "debug": "4.4.3", + "dotenv": "16.6.1", + "extend": "3.0.2", + "file-type": "21.3.4", + "form-data": "4.0.6", + "isstream": "0.1.2", + "jsonwebtoken": "9.0.3", + "load-esm": "1.0.3", + "mime-types": "2.1.35", + "retry-axios": "2.6.0", + "tough-cookie": "6.0.2" + }, + "engines": { + "node": ">=22" + } + }, + "node_modules/ibm-cos-sdk": { + "version": "1.15.2", + "resolved": "https://registry.npmjs.org/ibm-cos-sdk/-/ibm-cos-sdk-1.15.2.tgz", + "integrity": "sha512-koLQbA8l/EhQKglm3K2G8D9N1ypwAjl4vLnnpepTTTkhHtiIdmcBzKYqvdueVuJqAQWIK6XIvVaMfT/Em7F/Ow==", + "license": "Apache-2.0", + "dependencies": { + "buffer": "^4.9.2", + "jmespath": "^0.16.0", + "url": "^0.11.4", + "util": "^0.12.5", + "uuid": "^14.0.1", + "xml2js": "^0.6.2", + "xmlbuilder": "^10.1.1" + }, + "engines": { + "node": ">= 10.0.0" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/is-arguments": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/is-arguments/-/is-arguments-1.2.0.tgz", + "integrity": "sha512-7bVbi0huj/wrIAOzb8U1aszg9kdi3KN/CyU19CTI7tAoZYEZoL9yCDXpbXN+uPsuWnP02cyug1gleqq+TU+YCA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-callable": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz", + "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-generator-function": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/is-generator-function/-/is-generator-function-1.1.2.tgz", + "integrity": "sha512-upqt1SkGkODW9tsGNG5mtXTXtECizwtS2kA161M+gJPc1xdb/Ax629af6YrTwcOeQHbewrPNlE5Dx7kzvXTizA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.4", + "generator-function": "^2.0.0", + "get-proto": "^1.0.1", + "has-tostringtag": "^1.0.2", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-regex": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.2.1.tgz", + "integrity": "sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "gopd": "^1.2.0", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-typed-array": { + "version": "1.1.15", + "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.15.tgz", + "integrity": "sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ==", + "license": "MIT", + "dependencies": { + "which-typed-array": "^1.1.16" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "license": "MIT" + }, + "node_modules/isstream": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", + "integrity": "sha512-Yljz7ffyPbrLpLngrMtZ7NduUgVvi6wG9RJ9IUcyCd59YQ911PBJphODUcbOVbqYfxe1wuYf/LJ8PauMRwsM/g==", + "license": "MIT" + }, + "node_modules/jmespath": { + "version": "0.16.0", + "resolved": "https://registry.npmjs.org/jmespath/-/jmespath-0.16.0.tgz", + "integrity": "sha512-9FzQjJ7MATs1tSpnco1K6ayiYE3figslrXA72G2HQ/n76RzvYlofyi5QM+iX4YRs/pu3yzxlVQSST23+dMDknw==", + "license": "Apache-2.0", + "engines": { + "node": ">= 0.6.0" + } + }, + "node_modules/jsonwebtoken": { + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.3.tgz", + "integrity": "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g==", + "license": "MIT", + "dependencies": { + "jws": "^4.0.1", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^7.5.4" + }, + "engines": { + "node": ">=12", + "npm": ">=6" + } + }, + "node_modules/jwa": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz", + "integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==", + "license": "MIT", + "dependencies": { + "buffer-equal-constant-time": "^1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz", + "integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==", + "license": "MIT", + "dependencies": { + "jwa": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/load-esm": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/load-esm/-/load-esm-1.0.3.tgz", + "integrity": "sha512-v5xlu8eHD1+6r8EHTg6hfmO97LN8ugKtiXcy5e6oN72iD2r6u0RPfLl6fxM+7Wnh2ZRq15o0russMst44WauPA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + }, + { + "type": "buymeacoffee", + "url": "https://buymeacoffee.com/borewit" + } + ], + "license": "MIT", + "engines": { + "node": ">=13.2.0" + } + }, + "node_modules/lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==", + "license": "MIT" + }, + "node_modules/lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==", + "license": "MIT" + }, + "node_modules/lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==", + "license": "MIT" + }, + "node_modules/lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==", + "license": "MIT" + }, + "node_modules/lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==", + "license": "MIT" + }, + "node_modules/lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==", + "license": "MIT" + }, + "node_modules/lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==", + "license": "MIT" + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/object-inspect": { + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.14.0.tgz", + "integrity": "sha512-IVgHNlp/jwQX271+Xzoq9LZNTWXxZK+cEOrGBOBxXNbn7fapnZ+Ts6TVMgNOuAezwG2wdtnMX97tTPK6VEnuOQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/possible-typed-array-names": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz", + "integrity": "sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/proxy-from-env": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz", + "integrity": "sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/punycode": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz", + "integrity": "sha512-jmYNElW7yvO7TV33CjSmvSiE2yco3bV2czu/OzDKdMNVZQWfxCblURLhf+47syQRBntjfLdd/H0egrzIG+oaFQ==", + "license": "MIT" + }, + "node_modules/qs": { + "version": "6.17.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.17.1.tgz", + "integrity": "sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==", + "license": "BSD-3-Clause", + "dependencies": { + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/retry-axios": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/retry-axios/-/retry-axios-2.6.0.tgz", + "integrity": "sha512-pOLi+Gdll3JekwuFjXO3fTq+L9lzMQGcSq7M5gIjExcl3Gu1hd4XXuf5o3+LuSBsaULQH7DiNbsqPd1chVpQGQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=10.7.0" + }, + "peerDependencies": { + "axios": "*" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safe-regex-test": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/safe-regex-test/-/safe-regex-test-1.1.0.tgz", + "integrity": "sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "is-regex": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/sax": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/sax/-/sax-1.6.1.tgz", + "integrity": "sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=11.0.0" + } + }, + "node_modules/semver": { + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/set-function-length": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/side-channel": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/strtok3": { + "version": "10.8.0", + "resolved": "https://registry.npmjs.org/strtok3/-/strtok3-10.8.0.tgz", + "integrity": "sha512-e6bW3fD6V01DPmcbLfNtn0cjsiHvTKS/hivgbzqYMfHb/nLes4QQ0H5QBxlkPQayF4xv08AvlSgptGwN86Eemw==", + "license": "MIT", + "dependencies": { + "@tokenizer/token": "^0.3.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/tldts": { + "version": "7.5.6", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.5.6.tgz", + "integrity": "sha512-78a/2zOOpMAgcd+GhQMx8tQSGYojszqzAKhXzd5/t7lgyglt1INshF2tiVfWBw9NNYaMuMVCz1RAcggt383LTg==", + "license": "MIT", + "dependencies": { + "tldts-core": "^7.5.6" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "7.5.6", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.5.6.tgz", + "integrity": "sha512-ZKR8J39MaMREBzOCN6nKWxr0V3sAOhNxRth96uAwWLrliTYBKb+JhaUwkZl3naRSyd9HuJr6KPzS66oTCmYafw==", + "license": "MIT" + }, + "node_modules/token-types": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/token-types/-/token-types-6.2.0.tgz", + "integrity": "sha512-s9euYHM//T3loJtbNUYdbAzsMlvKBeRS+XCLFy+UGosMQH19Hwjap5k19i4PPAEJJBsVIpMpVTxl4fIqCuNfUg==", + "license": "MIT", + "dependencies": { + "@borewit/text-codec": "^0.2.3", + "@tokenizer/token": "^0.3.0", + "ieee754": "^1.2.1" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Borewit" + } + }, + "node_modules/tough-cookie": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.2.tgz", + "integrity": "sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA==", + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^7.0.5" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/uint8array-extras": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/uint8array-extras/-/uint8array-extras-1.6.0.tgz", + "integrity": "sha512-8iAasVS4wUx0gPLjH8Xtz2PeDzTSiy8QiLGu2DT3X5GU+egFEQhpnbtkehbAwjvDcxIERmCYcysiODFmE3Ud0Q==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/undici-types": { + "version": "5.26.5", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", + "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==", + "license": "MIT" + }, + "node_modules/url": { + "version": "0.11.4", + "resolved": "https://registry.npmjs.org/url/-/url-0.11.4.tgz", + "integrity": "sha512-oCwdVC7mTuWiPyjLUz/COz5TLk6wgp0RCsN+wHZ2Ekneac9w8uuV0njcbbie2ME+Vs+d6duwmYuR3HgQXs1fOg==", + "license": "MIT", + "dependencies": { + "punycode": "^1.4.1", + "qs": "^6.12.3" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/util": { + "version": "0.12.5", + "resolved": "https://registry.npmjs.org/util/-/util-0.12.5.tgz", + "integrity": "sha512-kZf/K6hEIrWHI6XqOFUiiMa+79wE/D8Q+NCNAWclkyg3b4d2k7s0QGepNjiABc+aR3N1PAyHL7p6UcLY6LmrnA==", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "is-arguments": "^1.0.4", + "is-generator-function": "^1.0.7", + "is-typed-array": "^1.1.3", + "which-typed-array": "^1.1.2" + } + }, + "node_modules/uuid": { + "version": "14.0.3", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-14.0.3.tgz", + "integrity": "sha512-Sc5u1VVln93y1Xnz4R+CunOZc7R9LUcTmhj7Rc7Eg3HVcf7rVn2FOoa812fe0W8p3jD7xeoGSYbfqCGGH2B6xw==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist-node/bin/uuid" + } + }, + "node_modules/which-typed-array": { + "version": "1.1.24", + "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.24.tgz", + "integrity": "sha512-wk4Mf4pR5mRP7eYuuTBCIQ9d0ud2Fv2jRLQpfgnRjbOxAFHmjKFValgTpitVKzJJS8ajnYQV2Du1SZ8j6b/EUQ==", + "license": "MIT", + "dependencies": { + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.9", + "call-bound": "^1.0.4", + "for-each": "^0.3.5", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/xml2js": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.6.2.tgz", + "integrity": "sha512-T4rieHaC1EXcES0Kxxj4JWgaUQHDk+qwHcYOCFHfiwKz7tOVPLq7Hjq9dM1WCMhylqMEfP7hMcOIChvotiZegA==", + "license": "MIT", + "dependencies": { + "sax": ">=0.6.0", + "xmlbuilder": "~11.0.0" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/xml2js/node_modules/xmlbuilder": { + "version": "11.0.1", + "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-11.0.1.tgz", + "integrity": "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==", + "license": "MIT", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/xmlbuilder": { + "version": "10.1.1", + "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-10.1.1.tgz", + "integrity": "sha512-OyzrcFLL/nb6fMGHbiRDuPup9ljBycsdCypwuyg5AAHvyWzGfChJpCXMG88AGTIMFhGZ9RccFN1e6lhg3hkwKg==", + "license": "MIT", + "engines": { + "node": ">=4.0" + } + } + } +} diff --git a/network-isolation/inbound-webhooks/src/receiver/package.json b/network-isolation/inbound-webhooks/src/receiver/package.json new file mode 100644 index 000000000..bffdf56d6 --- /dev/null +++ b/network-isolation/inbound-webhooks/src/receiver/package.json @@ -0,0 +1,17 @@ +{ + "name": "webhook-receiver", + "version": "1.0.0", + "description": "Code Engine function that receives webhooks and stores them in a COS bucket", + "private": true, + "main": "main.js", + "scripts": { + "test": "node --test main.test.js" + }, + "engines": { + "node": ">=24" + }, + "dependencies": { + "ibm-cloud-sdk-core": "5.9.5", + "ibm-cos-sdk": "1.15.2" + } +} diff --git a/network-isolation/inbound-webhooks/test-receiver b/network-isolation/inbound-webhooks/test-receiver new file mode 100755 index 000000000..c3bc44bd5 --- /dev/null +++ b/network-isolation/inbound-webhooks/test-receiver @@ -0,0 +1,120 @@ +#!/usr/bin/env bash + +# Manual smoke test for the deployed webhook-receiver function: sends one correctly signed webhook and +# several invalid requests with curl and checks the HTTP status codes. +# +# Prerequisites: +# - ./run completed +# - WEBHOOK_SECRET set in the environment (same value used for deployment) +# - curl, openssl, uuidgen; ibmcloud and jq (only to look up the function URL, skipped if RECEIVER_URL is set) +# +# The valid request stores one object in the bucket; the invalid requests must store nothing. +# Note: the secret is passed to openssl on the command line, so only use this for a test secret +# or on a machine you trust. + +set -euo pipefail + +PUBLIC_PROJECT=${PUBLIC_PROJECT:-webhook-public} +RECEIVER_FUNCTION=${RECEIVER_FUNCTION:-webhook-receiver} +ISOLATED_PROJECT=${ISOLATED_PROJECT:-webhook-isolated} +CONSUMER_APP=${CONSUMER_APP:-webhook-consumer} + + +echo "=== Checking prerequisites ===" + +if [ -z "${WEBHOOK_SECRET:-}" ]; then + echo "ERROR: WEBHOOK_SECRET is not set in the environment." + exit 1 +fi + +for tool in curl openssl uuidgen; do + command -v "$tool" >/dev/null || { echo "ERROR: '$tool' is missing."; exit 1; } +done + +if [ -z "${RECEIVER_URL:-}" ]; then + ibmcloud ce project select --name "$PUBLIC_PROJECT" + RECEIVER_URL=$(ibmcloud ce function get --name "$RECEIVER_FUNCTION" --output json | jq -r '.endpoint') +fi +echo "Receiver URL: $RECEIVER_URL" + + +echo +echo "=== Preparing payload ===" + +work_dir=$(mktemp -d) +trap 'rm -rf "$work_dir"' EXIT + +# the payload is sent byte for byte (--data-binary), so the signature matches +printf '%s' '{"zen":"Keep it logically awesome.","repository":{"full_name":"octo/test"},"sender":{"login":"curl-test"}}' > "$work_dir/payload.json" + +SIGNATURE=$(openssl dgst -sha256 -hmac "$WEBHOOK_SECRET" "$work_dir/payload.json" | awk '{print $NF}') +WRONG_SIGNATURE=$(printf '%064d' 0) + +FAILURES=0 + +# post EXPECTED_STATUS DESCRIPTION CURL_OPTION... +# Sends the payload with the given extra curl options, prints status and response body, +# and counts a failure if the status is not the expected one. +post() { + expected=$1 + description=$2 + shift 2 + + status=$(curl -sS -o "$work_dir/response.txt" -w '%{http_code}' -X POST "$RECEIVER_URL" \ + -H "Content-Type: application/json" --data-binary @"$work_dir/payload.json" "$@") + + if [ "$status" = "$expected" ]; then + echo "OK $description: $status (expected $expected)" + else + echo "FAIL $description: $status (expected $expected)" + FAILURES=$((FAILURES + 1)) + fi + echo " response: $(cat "$work_dir/response.txt")" +} + + +echo +echo "=== Valid request ===" + +DELIVERY_ID=$(uuidgen) +echo "Delivery ID: $DELIVERY_ID" +post 202 "valid signature" \ + -H "X-GitHub-Event: ping" -H "X-GitHub-Delivery: $DELIVERY_ID" -H "X-Hub-Signature-256: sha256=$SIGNATURE" + + +echo +echo "=== Invalid requests (nothing must be stored) ===" + +post 403 "wrong signature" \ + -H "X-GitHub-Event: ping" -H "X-GitHub-Delivery: $(uuidgen)" -H "X-Hub-Signature-256: sha256=$WRONG_SIGNATURE" + +post 403 "missing signature" \ + -H "X-GitHub-Event: ping" -H "X-GitHub-Delivery: $(uuidgen)" + +post 400 "valid signature, missing X-GitHub-Delivery" \ + -H "X-GitHub-Event: ping" -H "X-Hub-Signature-256: sha256=$SIGNATURE" + +post 400 "valid signature, unsafe X-GitHub-Delivery" \ + -H "X-GitHub-Event: ping" -H "X-GitHub-Delivery: ../evil" -H "X-Hub-Signature-256: sha256=$SIGNATURE" + +status=$(curl -sS -o "$work_dir/response.txt" -w '%{http_code}' "$RECEIVER_URL") +if [ "$status" = "405" ]; then + echo "OK GET: $status (expected 405)" +else + echo "FAIL GET: $status (expected 405)" + FAILURES=$((FAILURES + 1)) +fi + + +echo +echo "=== Result ===" + +if [ "$FAILURES" -gt 0 ]; then + echo "$FAILURES check(s) failed. Check the logs of function $RECEIVER_FUNCTION in IBM Cloud Logs." + exit 1 +fi + +echo "All checks passed." +echo +echo "To see the consumer processing delivery $DELIVERY_ID:" +echo " ibmcloud ce project select --name $ISOLATED_PROJECT && ibmcloud ce app logs --name $CONSUMER_APP"