In the previous post, I sent GitHub pull request webhooks to the new EventBridge Webhook Events, then through SQS to a Kiro CLI session on my laptop. Webhook Events is one of the launches I find most interesting in this first week of pre:Invent.
This time I wanted everything to run in AWS: the webhook triggers an agent on Amazon Bedrock AgentCore, and the agent posts a comment on the PR. EventBridge subscribers can call most AWS APIs directly, so I don't need a Lambda function between the bus and the agent.
For the comment, the agent writes to GitHub as a GitHub App whose private key lives in KMS. No GitHub token or key is stored anywhere in the account. The code is in the same repo, under agentcore/ and github-app/.
This post builds on the foundations laid out by part 1 of this series.
Calling the agent from the subscriber
A subscriber on the new Custom event bus can have a universal target. You name an AWS SDK service and action, and you write the request in JSONata. The target ARN has no account and no region:
arn:aws:events:::aws-sdk:bedrockagentcore:invokeAgentRuntime
The request goes in UniversalTargetParameters.Input:
{% {
"AgentRuntimeArn": "arn:aws:bedrock-agentcore:us-east-1:123456789012:runtime/kiro_gh_ack_agent-XXXXXXXXXX",
"RuntimeSessionId": "github-pr-" & $substring($hash($events[0].Data.repository.full_name & "#" & $string($events[0].Data.number), "SHA-256"), 0, 32),
"ContentType": "application/json",
"Payload": $string({
"repo": $events[0].Data.repository.full_name,
"number": $events[0].Data.number,
"action": $events[0].Data.action,
"delivery": $events[0].Metadata.`x-github-delivery`,
"prompt": "..."
})
} %}
Points to watch:
-
Field names are PascalCase, as in the API reference:
AgentRuntimeArn,Payload.CreateSubscriberonly checks a JSONata input for syntax, so a camelCase name is accepted at creation and fails at delivery, withCUSTOMER_VALIDATION ... missing required field(s)in the DLQ record. That record is the first place to look when something doesn't arrive. -
$eventsis an array. Universal targets batch events, so I use$events[0]withMaxBatchSize=1andMaxBatchWindowInSeconds=0, which gives one call per event. -
The session ID comes from the PR. A SHA-256 of
repo#numberputs every event of the same PR in the same AgentCore session, and it meets the 33-character minimum. -
The call times out after 30 seconds at most.
InvocationTimeoutSecondscan't go higher. A call that times out is retried, five times by default, so the agent should answer right away and run any long work asynchronously. - The agent must accept IAM (SigV4) calls. An agent behind a JWT authorizer, such as Cognito, rejects calls from EventBridge.
The delivery role needs bedrock-agentcore:InvokeAgentRuntime on the runtime and sqs:SendMessage on the DLQ.
A minimal agent
For this test I didn't want a framework. An AgentCore HTTP agent has to answer GET /ping and POST /invocations on port 8080, and Python's standard library is enough for that. The first version logs the event and returns an ack:
def do_POST(self):
event = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
ack = {"ack": True, "repo": event.get("repo"), "number": event.get("number"),
"session": self.headers.get("X-Amzn-Bedrock-AgentCore-Runtime-Session-Id")}
print(json.dumps(ack), flush=True) # ends up in CloudWatch
self._send(200, ack)
AgentCore can run code from a zip in S3 (codeConfiguration with PYTHON_3_13), so there is no container to build. When I opened a PR, the ack appeared in the runtime's log group a few seconds later, with the repo, the PR number, GitHub's delivery ID and the github-pr-... session ID.
Commenting on the PR without a GitHub secret
To post on GitHub, the agent needs credentials, and a GitHub webhook doesn't carry any. A delivery is a payload and a signature, and neither can be used to call the API.
I first looked at IAM outbound identity federation: with sts:GetWebIdentityToken, AWS gives your workload a signed JWT that an external service can trust. However, the GitHub API doesn't accept tokens from outside identity providers, though. GitHub issues OIDC tokens, which is how GitHub Actions gets into AWS, but it doesn't consume them. To call the API, you need a personal access token, an OAuth token or a GitHub App.
A GitHub App signs a short-lived JWT with its private key and exchanges it for an installation token, valid for one hour. KMS can produce that signature, so the setup is:
- create a GitHub App;
- import its private key into a non-exportable KMS key;
- let the agent sign the App's JWT with
kms:Sign.
The private key never sits on disk or in Secrets Manager. The agent's role gets kms:Sign on one key.
Create the App
GitHub has a manifest flow. You POST a JSON description of the App to github.com/settings/apps/new, you click Create, and GitHub redirects to a URL you choose with a code. You exchange that code for the App ID and its private key. The clickops can't be skipped, and github-app/create-app.py handles everything else. It serves a local page that submits the manifest, catches the redirect on localhost, and writes the key to a file with mode 600 without printing it (thanks Kiro!).
The manifest asks for the minimum:
{ "public": false,
"default_permissions": { "pull_requests": "write", "metadata": "read" },
"hook_attributes": { "url": "https://github.com/OWNER/REPO", "active": false } }
Creating the App doesn't install it. Install it from https://github.com/apps/<slug>/installations/new on the repos it should comment on. Until then, GET /repos/{repo}/installation returns 404.
Import the key into KMS
KMS accepts imported key material for asymmetric keys. You create a key with --origin EXTERNAL --key-spec RSA_2048 --key-usage SIGN_VERIFY, ask KMS for a wrapping key, and wrap the private key with RSA_AES_KEY_WRAP_SHA_256. An ephemeral AES key wraps the PKCS#8 DER key (OpenSSL's id-aes256-wrap-pad), and KMS's public key wraps the AES key with RSA-OAEP-SHA256. github-app/import-key-to-kms.sh does this in about twenty lines, then checks that the public key in KMS matches the one in the .pem.
After the import, I deleted the .pem. If I ever need the key outside KMS, GitHub can issue a new one.
Sign the JWT
GitHub expects RS256, which KMS calls RSASSA_PKCS1_V1_5_SHA_256:
header = b64url(json.dumps({"alg": "RS256", "typ": "JWT"}).encode())
claims = b64url(json.dumps({"iat": now - 60, "exp": now + 540, "iss": APP_ID}).encode())
sig = kms.sign(KeyId=KMS_KEY, Message=f"{header}.{claims}".encode(),
MessageType="RAW", SigningAlgorithm="RSASSA_PKCS1_V1_5_SHA_256")["Signature"]
jwt = f"{header}.{claims}.{b64url(sig)}"
You can check the signature from a shell before touching the agent: sign with aws kms sign, then call GET /app with curl. GitHub returns the App's name and permissions.
With the JWT, the agent:
- finds the installation for the PR's repo;
- requests an installation token limited to that repo and to
pull_requests: write; - posts the comment through the issues API.
This takes about two seconds, well within the 30-second limit. On my test PR, the App's comment appeared about forty seconds after I opened it: "Acknowledged opened on this pull request, via EventBridge Webhook Events and AgentCore."
Lessons learnt while developing this
- I wanted to learn about Webhook Events and found out Eventbridge now has universal target. Between GitHub and the agent, no code of mine runs. The agent is the only thing I deployed.
-
A GitHub App with its key in KMS. I'll use it for any AWS workload that has to write to GitHub. A single
kms:Signpermission is easy to grant, to audit in CloudTrail and to revoke.
I plugged in a dummy agent. But you can develop or deploy you own harness and run your development farm!
Top comments (0)