Skip to content

feat(caretaker): implement Cloud Run webhook ingestion service#28015

Open
chadd28 wants to merge 20 commits into
google-gemini:mainfrom
chadd28:feature/caretaker-agent
Open

feat(caretaker): implement Cloud Run webhook ingestion service#28015
chadd28 wants to merge 20 commits into
google-gemini:mainfrom
chadd28:feature/caretaker-agent

Conversation

@chadd28

@chadd28 chadd28 commented Jun 18, 2026

Copy link
Copy Markdown

Summary

Implements the Cloud Run Webhook Ingestion Service for the Caretaker Agent. The service acts as an entry point for GitHub webhooks, verifies incoming payload signatures, stores new issue entries using Firestore transactions, and publishes sanitized issue metadata to a GCP Pub/Sub topic for downstream processing.

Details

  • Server (server.ts): The main Express server (to be hosted on Cloud Run) that receives GitHub issues.opened events, validates their signature, adds the issue to Firestore, and publishes the issue details to Pub/Sub.
  • Auth Verification (auth/github.ts): HMAC SHA-256 signature verification helper using node:crypto and a secure timing-safe equality check.
  • Store (db/issuesStore.ts): Initializes new issues in Firestore using a transaction.
  • Tests: Added issuesStore.test.ts (Firestore mock tests) and github.test.ts (HMAC signature verification tests).

How to Validate

Run unit tests in the service directory:

cd tools/caretaker-agent/cloudrun/ingestion-service
npm install
npx vitest run

Pre-Merge Checklist

  • Updated relevant documentation and README (if needed)
  • Added/updated tests (if needed)
  • Noted breaking changes (if any)
  • Validated on required platforms/methods:
    • MacOS
      • npm run
      • npx
      • Docker
      • Podman
      • Seatbelt
    • Windows
      • npm run
      • npx
      • Docker
    • Linux
      • npm run
      • npx
      • Docker

@galz10

@github-actions github-actions Bot added the size/l A large sized PR label Jun 18, 2026
@github-actions

github-actions Bot commented Jun 18, 2026

Copy link
Copy Markdown

📊 PR Size: size/XL

  • Lines changed: 1479
  • Additions: +994
  • Deletions: -485
  • Files changed: 13

@chadd28 chadd28 marked this pull request as ready for review June 18, 2026 19:38
@chadd28 chadd28 requested a review from a team as a code owner June 18, 2026 19:38
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a new ingestion service for the Caretaker Agent, designed to run on Cloud Run. The service acts as a secure gateway for GitHub webhooks, handling event validation, deduplication via Firestore transactions, and message queuing through Pub/Sub. This infrastructure enables automated downstream triage workflows for incoming GitHub issues.

Highlights

  • Webhook Ingestion Service: Implemented a new Express-based service to receive and process GitHub 'issues.opened' webhooks.
  • Security & Verification: Added HMAC SHA-256 signature verification using timing-safe equality checks to ensure payload authenticity.
  • Data Persistence: Integrated Firestore transactions to reliably store issue metadata and prevent duplicate entries.
  • Downstream Integration: Configured Pub/Sub publishing to forward sanitized issue data for further processing.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize the Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a new Express-based ingestion service for a triage worker, featuring GitHub webhook signature verification, Firestore storage for tracking issues, and Pub/Sub integration. The review feedback highlights three critical security and reliability improvements: validating the signature length and payload type in the GitHub auth module to prevent crashes and DoS attacks, escaping the issue body to mitigate prompt injection vulnerabilities, and checking the return value of the issue creation transaction to prevent duplicate Pub/Sub messages.

Comment thread tools/caretaker-agent/cloudrun/ingestion-service/auth/github.ts Outdated
}

// Payload preprocessing
const sanitizedBody = `<untrusted_context>\n${payload.issue?.body || ''}\n</untrusted_context>`;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Wrapping untrusted user input directly in <untrusted_context> tags without escaping or sanitizing the input makes the system vulnerable to prompt injection. An attacker could include </untrusted_context> in their issue body to escape the context block and inject malicious instructions.

Sanitize or escape any occurrences of </untrusted_context> in the issue body before wrapping it.

  const rawBody = payload.issue?.body || '';
  const escapedBody = rawBody.replace(/<\/untrusted_context>/g, '[escaped_untrusted_context_tag]');
  const sanitizedBody = `\<untrusted_context\>\n\${escapedBody}\n\</untrusted_context\>`;

Comment thread tools/caretaker-agent/cloudrun/ingestion-service/server.ts Outdated
@gemini-cli gemini-cli Bot added the status/need-issue Pull requests that need to have an associated issue. label Jun 18, 2026
@chadd28 chadd28 force-pushed the feature/caretaker-agent branch from ef27d32 to 5650049 Compare June 22, 2026 21:51
COPY . .
EXPOSE 8080
CMD ["npx", "tsx", "server.ts"]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Production anti-pattern.
Running tsx (or ts-node) in a production container introduces significant memory overhead and startup latency. Add a "build": "tsc" script to package.json and run the compiled JavaScript here instead.

Suggested change
RUN npm run build
CMD ["node", "dist/server.js"]


// Publish to Pub/Sub
const dataBuffer = Buffer.from(JSON.stringify(processedData));
const messageId = await topic.publishMessage({ data: dataBuffer });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P0] Dual-write failure state permanently drops retried webhooks.
If the Firestore write succeeds but the Pub/Sub publish fails, the server returns a 500 error, and GitHub will retry. On the retry, createIssue returns false (since the document already exists), causing the endpoint to return 200 early and skip the Pub/Sub publish entirely. The issue will never be processed downstream. You should publish to Pub/Sub even if the DB document exists (assuming downstream is idempotent) or rely entirely on Pub/Sub and let the downstream worker deduplicate.

});

app.post('/webhook', async (req, res) => {
const signature = req.headers['x-hub-signature-256'] as string | undefined;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Unsafe header cast.
Express headers can be an array (string[]) if multiple headers with the same name are sent. If an array is passed, downstream checks like signature.length will evaluate the array length rather than string length.

Suggested change
const signature = req.headers['x-hub-signature-256'] as string | undefined;
const header = req.headers['x-hub-signature-256'];
const signature = Array.isArray(header) ? header[0] : header;

Comment thread tools/caretaker-agent/cloudrun/ingestion-service/db/issuesStore.ts Outdated
Comment thread tools/caretaker-agent/cloudrun/ingestion-service/server.ts Outdated
let payload: GitHubWebhookPayload;
try {
payload = JSON.parse(req.body.toString()) as GitHubWebhookPayload;
} catch {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Blind type casting.
The explicit cast as GitHubWebhookPayload bypasses runtime safety. At minimum, we should validate the presence of payload.issue.number and payload.repository.full_name before assuming the structure exists to avoid unexpected undefined errors downstream.


// Payload preprocessing
const sanitizedBody = `<untrusted_context>\n${payload.issue?.body || ''}\n</untrusted_context>`;
const processedData = {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Misleading variable name / Missing sanitization.
This is not actually sanitized. If a user maliciously includes </untrusted_context> in their GitHub issue description, they will break out of the LLM context wrapper downstream. Rename this to wrappedBody to be accurate, or implement actual tag escaping/stripping.

@galdawave galdawave left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P0] Missing core unit tests.
The PR introduces complex routing, orchestrating validation, DB writes, and Pub/Sub publishing in server.ts without a corresponding server.test.ts. This violates the testing standard criteria. Please add tests that mock the Firestore and Pub/Sub clients to verify the endpoint behavior.

chadd28 added 2 commits June 22, 2026 17:17
…estion service

- Fix dual-write failure: verify issue is UNTRIAGED before ignoring duplicate database entries, resolving Pub/Sub retries at ingestion to avoid wasting downstream worker startup costs.
- Fix unsafe header cast: safely extract first element if header is a string array.
- Fix blind payload type casting: validate that payload is a non-null object and verify required fields exist before processing.
- Fix missing sanitization: rename to wrappedBody and escape context breakout tags.
- Use pre-validated variables (issueNumber, repository) directly in payload preprocessing.
number?: number;
title?: string;
};
repository?: {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we specify the format of this in a comment? is it an HTTPS URI or an [org]/[repo] id?

!databaseId ||
!collectionName
) {
throw new Error('Missing required environment variables');

@gundermanc gundermanc Jun 25, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

minor nit: might be nice to log which variable we're missing.

This is also an opportunity to encapsulate the failure a bit.

Could have something like

const projectId = getEnvironmentVariable('PROJECT_ID');
const topicId = getEnvironmentVariable('TOPIC_ID');
...

function getEnvironmentVariable(name: string | undefined): string {
    const value = process.env[name];
    if (!value || typeof value !== 'string') {
        throw new Error(`Undefined required environment variable ${name}`);
    }
}

const issuesStore = new IssuesStore(db, collectionName);

// Middleware: read incoming JSON payloads as raw Buffer bytes
app.use(express.raw({ type: 'application/json', limit: '1mb' }));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's the failure mode if the request is too large? Do we dead letter or is there another opportunity to process the event?

app.use(express.raw({ type: 'application/json', limit: '1mb' }));

app.get('/', (req, res) => {
res.send('Hello World!');

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we send anything back here?

FWIW I've commonly seen a Git SHA returned from endpoints to make it really easy to check that deployment succeeded.

Comment thread tools/caretaker-agent/cloudrun/ingestion-service/app.ts Outdated
title: payload.issue?.title,
};

const [owner, repo] = repository.split('/');

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it possible we get an unexpected repo specifier format (e.g.: a full URI) and this results in unexpected behavior (e.g.: creating malformed or erroneous DB entries)?

issueNumber: number,
): DocumentReference {
const docId = `github_${owner}_${repo}_${issueNumber}`;
return this.db.collection(this.collectionName).doc(docId);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We are storing issues right in the top level Firestore collection passed in via the environment variable.

This means that any new data types we store will be in this same collection as well, or perhaps nested, leaving the top level collection containing nested collections and individual issues docs.

Should we proactively create a nested collection for issues to keep the door open to extend this?

@gundermanc gundermanc left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. I left a few comments. I think there might be one floating promise.

@chadd28

chadd28 commented Jun 25, 2026

Copy link
Copy Markdown
Author

I have pushed the remaining commits addressing your review feedback.

Specifically, in the final commit, I enabled strict ESLint checks for the tools/ folder and resolved all outstanding lint and type-safety warnings. Could you double-check that my changes to eslint.config.js look good to you @gundermanc ?

Here are my thoughts on some of the points you raised:

  • On Testing Strategy (mocks vs emulators): I'll think about setting up more realistic integration testing down the line in a later PR. I decided to keep the unit mocks for now to keep the scope of this PR manageable.
  • On Firestore Collection Design (flat vs nested): Since this service has its own dedicated Firestore database, we can easily create separate top-level collections (like /users, /rules for example) instead of nesting everything under a single root.
  • On Large Requests (HTTP 413 & DLQ): I think we'll just log the error. We shouldn't have it happen unless it's a DDoS or anomalous payload anyway.

next: express.NextFunction,
) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
const error = err as { status?: number; message?: string };

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we eliminate this as as well? I'd recommend blanket avoiding the as keyword altogether as it's almost always a footgun.

I think you can test the existence of specific properties, like status, if needed via the in keyword.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

resolved! Used property checking ('status' in err)

issueNumber: number,
): DocumentReference<IssueDocument> {
const docId = `github_${owner}_${repo}_${issueNumber}`;
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we eliminate this cast as well?

@rsloane82-create

rsloane82-create commented Jun 26, 2026 via email

Copy link
Copy Markdown

@rsloane82-create

rsloane82-create commented Jun 26, 2026 via email

Copy link
Copy Markdown

@gemini-cli

gemini-cli Bot commented Jun 26, 2026

Copy link
Copy Markdown
Contributor

Hi there! Thank you for your interest in contributing to Gemini CLI.

To ensure we maintain high code quality and focus on our prioritized roadmap, we only guarantee review and consideration of pull requests for issues that are explicitly labeled as 'help wanted'.

This PR will be closed in 7 days if it remains without that designation. We encourage you to find and contribute to existing 'help wanted' issues in our backlog! Thank you for your understanding.

@gundermanc gundermanc enabled auto-merge June 26, 2026 20:55
Comment thread tools/caretaker-agent/cloudrun/ingestion-service/app.ts Fixed
Comment thread tools/caretaker-agent/cloudrun/ingestion-service/db/issuesStore.ts Fixed
auto-merge was automatically disabled June 26, 2026 21:42

Head branch was pushed to by a user without write access

@gundermanc gundermanc enabled auto-merge June 26, 2026 21:47
auto-merge was automatically disabled June 26, 2026 22:19

Head branch was pushed to by a user without write access

@gundermanc gundermanc enabled auto-merge June 26, 2026 22:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/l A large sized PR size/xl An extra large PR status/need-issue Pull requests that need to have an associated issue. status/pr-nudge-sent

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants