Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions network-isolation/inbound-webhooks/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
**/node_modules/
61 changes: 61 additions & 0 deletions network-isolation/inbound-webhooks/README.md
Original file line number Diff line number Diff line change
@@ -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 `<REGISTRY>/receiver` and the consumer image `<REGISTRY>/consumer`.

```
REGISTRY=<registry>/<namespace> ./build
REGISTRY=<registry>/<namespace> ./run
```

With IBM Cloud Container Registry, use the private endpoint of your region, for example `REGISTRY=private.au.icr.io/<namespace>`. 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 <secret>` and to the receiver with `ibmcloud ce function update --code-bundle-secret <secret>`.

The unit tests of the receiver run with `npm ci && npm test` in [`src/receiver`](src/receiver).
29 changes: 29 additions & 0 deletions network-isolation/inbound-webhooks/build
Original file line number Diff line number Diff line change
@@ -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=<registry>/<namespace> 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/<namespace>. 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
132 changes: 132 additions & 0 deletions network-isolation/inbound-webhooks/run
Original file line number Diff line number Diff line change
@@ -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 <region>}"

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}")"
15 changes: 15 additions & 0 deletions network-isolation/inbound-webhooks/src/consumer/Dockerfile
Original file line number Diff line number Diff line change
@@ -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"]
120 changes: 120 additions & 0 deletions network-isolation/inbound-webhooks/src/consumer/cos.go
Original file line number Diff line number Diff line change
@@ -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)
}
Loading
Loading