Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(cdp): re-sign aws sigv4 requests at fetch time (#65215)

Meikel Ratza2b235f9e23b
diff --git a/nodejs/src/cdp/async-functions/fetch-handler.ts b/nodejs/src/cdp/async-functions/fetch-handler.ts
index bdffe61cd3ba..cbe7c1d428b2 100644
--- a/nodejs/src/cdp/async-functions/fetch-handler.ts
+++ b/nodejs/src/cdp/async-functions/fetch-handler.ts
@@ -20,12 +20,20 @@ registerAsyncFunction('fetch', {
: JSON.stringify(fetchOptions.body)
: fetchOptions?.body
+ // Hog templates targeting AWS services (Kinesis, SQS, …) pass `aws_sigv4`
+ // here instead of computing the Authorization header in Hog. The fetch
+ // executor re-signs on every attempt so a retry can never carry a stale
+ // signature past AWS's 5-minute expiry window. Only include the key when
+ // it's actually set — Zod preserves an `aws_sigv4: undefined` own property
+ // on the parsed object, which would otherwise leak into every non-AWS
+ // template's queueParameters snapshot.
const fetchQueueParameters = CyclotronInvocationQueueParametersFetchSchema.parse({
type: 'fetch',
url,
method,
body,
headers: pickBy(headers, (v) => typeof v == 'string'),
+ ...(fetchOptions?.aws_sigv4 ? { aws_sigv4: fetchOptions.aws_sigv4 } : {}),
})
result.invocation.queueParameters = fetchQueueParameters
diff --git a/nodejs/src/cdp/cdp-e2e.test.ts b/nodejs/src/cdp/cdp-e2e.test.ts
index c1cf1f201f81..75c91c42fd9e 100644
--- a/nodejs/src/cdp/cdp-e2e.test.ts
+++ b/nodejs/src/cdp/cdp-e2e.test.ts
@@ -271,6 +271,263 @@ describe('CDP Consumer loop', () => {
])
})
+ // Regression coverage for the production wire shape of an outgoing Kinesis
+ // PutRecord. The pre-refactor Python template test
+ // (posthog/cdp/templates/aws_kinesis/test_template_aws_kinesis.py) asserted a
+ // similar shape but ran against the Python Hog VM, whose `jsonStringify`
+ // formats objects WITH spaces (`{"k": "v"}`). The Node Hog VM — what CDP
+ // actually runs in production — formats WITHOUT spaces (`{"k":"v"}`), so the
+ // Python test was locking in a body the Node runtime never produced. This
+ // e2e test uses the Node values (body + corresponding signature) so a
+ // regression in Hog body construction, executor wiring, credential lookup,
+ // or signer canonical-request handling will all flip the signature hex and
+ // fail this test.
+ it('matches the production outgoing request shape for the kinesis template fixture', async () => {
+ const fixedTime = new Date('2024-04-16T12:34:51Z').getTime()
+ const dateSpy = jest.spyOn(Date, 'now').mockReturnValue(fixedTime)
+
+ try {
+ mockFetch.mockResolvedValueOnce({
+ status: 200,
+ json: () => Promise.resolve({ ok: true }),
+ text: () => Promise.resolve('{"ok":true}'),
+ headers: { 'Content-Type': 'application/json' },
+ dump: () => Promise.resolve(),
+ })
+
+ // Same Hog body the production Kinesis template produces, parameterised
+ // off `inputs` so the test exercises the input lookup path end-to-end.
+ const hog = `
+ let payload := jsonStringify({
+ 'StreamName': inputs.aws_kinesis_stream_name,
+ 'PartitionKey': inputs.aws_kinesis_partition_key ?? generateUUIDv4(),
+ 'Data': base64Encode(jsonStringify(inputs.payload)),
+ })
+
+ let res := fetch(f'https://kinesis.{inputs.aws_region}.amazonaws.com', {
+ 'method': 'POST',
+ 'headers': {
+ 'Content-Type': 'application/x-amz-json-1.1',
+ 'X-Amz-Target': 'Kinesis_20131202.PutRecord',
+ },
+ 'body': payload,
+ 'aws_sigv4': {
+ 'service': 'kinesis',
+ 'region': inputs.aws_region,
+ 'access_key_id_input': 'aws_access_key_id',
+ 'secret_access_key_input': 'aws_secret_access_key',
+ },
+ });
+
+ print('Fetch response:', res);
+ `
+
+ await insertHogFunction({
+ type: 'destination',
+ hog,
+ bytecode: await compileHog(hog),
+ inputs_schema: [
+ { key: 'aws_access_key_id', type: 'string', label: 'AKID', secret: true, required: true },
+ { key: 'aws_secret_access_key', type: 'string', label: 'SK', secret: true, required: true },
+ { key: 'aws_region', type: 'string', label: 'region', secret: false, required: true },
+ {
+ key: 'aws_kinesis_stream_name',
+ type: 'string',
+ label: 'stream',
+ secret: false,
+ required: true,
+ },
+ {
+ key: 'aws_kinesis_partition_key',
+ type: 'string',
+ label: 'partition',
+ secret: false,
+ required: false,
+ },
+ { key: 'payload', type: 'json', label: 'payload', secret: false, required: true },
+ ],
+ inputs: {
+ aws_region: { value: 'aws_region' },
+ aws_kinesis_stream_name: { value: 'aws_kinesis_stream_arn' },
+ aws_kinesis_partition_key: { value: '1' },
+ payload: { value: { hello: 'world' } },
+ },
+ encrypted_inputs: hub.encryptedFields.encrypt(
+ JSON.stringify({
+ aws_access_key_id: { value: 'aws_access_key_id' },
+ aws_secret_access_key: { value: 'aws_secret_access_key' },
+ })
+ ),
+ ...HOG_FILTERS_EXAMPLES.no_filters,
+ } as any)
+
+ await eventsConsumer.processBatch([globals])
+
+ await waitForExpect(() => {
+ const kinesisCalls = mockFetch.mock.calls.filter((c: any[]) => String(c[0]).includes('kinesis.'))
+ expect(kinesisCalls.length).toBe(1)
+ }, 5000)
+
+ const kinesisCall = mockFetch.mock.calls.find((c: any[]) => String(c[0]).includes('kinesis.'))
+ expect(kinesisCall).toBeDefined()
+ const [url, opts] = kinesisCall as [string, any]
+
+ // Body bytes the Node Hog VM emits for this input (no spaces between
+ // JSON tokens), and the SigV4 signature derived from THOSE bytes plus
+ // the frozen `20240416T123451Z` timestamp. The byte-compatibility of
+ // the signer itself (matching the canonical AWS docs algorithm) is
+ // separately locked in by the `aws-sigv4.test.ts` unit fixture.
+ expect(url).toBe('https://kinesis.aws_region.amazonaws.com')
+ expect(opts).toMatchObject({
+ method: 'POST',
+ body: '{"StreamName":"aws_kinesis_stream_arn","PartitionKey":"1","Data":"eyJoZWxsbyI6IndvcmxkIn0="}',
+ headers: {
+ 'Content-Type': 'application/x-amz-json-1.1',
+ 'X-Amz-Target': 'Kinesis_20131202.PutRecord',
+ 'X-Amz-Date': '20240416T123451Z',
+ Host: 'kinesis.aws_region.amazonaws.com',
+ Authorization:
+ 'AWS4-HMAC-SHA256 Credential=aws_access_key_id/20240416/aws_region/kinesis/aws4_request, ' +
+ 'SignedHeaders=content-type;host;x-amz-date;x-amz-target, ' +
+ 'Signature=19caaa3f67e2214daf7c0318dd0fa92ccf94d94208aabf526b82f8990ed2607b',
+ },
+ })
+ } finally {
+ dateSpy.mockRestore()
+ }
+ })
+
+ // E2E coverage for the AWS SigV4 fetch-time signing path. The regression this
+ // guards against: secrets land in `encrypted_inputs` after `move_secret_inputs`
+ // runs on save, so the executor has to look them up there — not in `inputs`,
+ // which is empty for `secret: true` keys. If we ever break that lookup the
+ // upstream gets an unsigned request and AWS 401s. Also covers retry — the
+ // second attempt must carry a freshly-signed Authorization header, not a
+ // reused stale one from the first attempt.
+ it('should sign aws sigv4 fetches from encrypted_inputs on both initial attempt and retry', async () => {
+ const ACCESS_KEY = 'AKIDEXAMPLE'
+ const SECRET_KEY = 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY'
+
+ const sigv4FetchCalls: Array<{ url: string; opts: any }> = []
+ let kinesisCallCount = 0
+ mockFetch.mockImplementation((url: string, opts: any) => {
+ if (url.includes('kinesis.')) {
+ sigv4FetchCalls.push({ url, opts })
+ kinesisCallCount++
+ if (kinesisCallCount === 1) {
+ // Delay the first 500 by long enough that attempt-2 signs in a
+ // different wall-clock second. X-Amz-Date is second-resolution,
+ // so without this delay both attempts would land in the same
+ // second and produce identical signatures — masking whether the
+ // retry actually re-signed or just reused the original payload.
+ return new Promise((resolve) =>
+ setTimeout(
+ () =>
+ resolve({
+ status: 500,
+ json: () => Promise.resolve({}),
+ text: () => Promise.resolve(''),
+ headers: {},
+ dump: () => Promise.resolve(),
+ }),
+ 1500
+ )
+ )
+ }
+ }
+ return Promise.resolve({
+ status: 200,
+ json: () => Promise.resolve({ ok: true }),
+ text: () => Promise.resolve('{"ok":true}'),
+ headers: { 'Content-Type': 'application/json' },
+ dump: () => Promise.resolve(),
+ })
+ })
+
+ const hog = `
+ let res := fetch('https://kinesis.us-east-1.amazonaws.com', {
+ 'method': 'POST',
+ 'headers': {
+ 'Content-Type': 'application/x-amz-json-1.1',
+ 'X-Amz-Target': 'Kinesis_20131202.PutRecord',
+ },
+ 'body': '{"StreamName":"s","PartitionKey":"p","Data":"ZA=="}',
+ 'aws_sigv4': {
+ 'service': 'kinesis',
+ 'region': 'us-east-1',
+ 'access_key_id_input': 'aws_access_key_id',
+ 'secret_access_key_input': 'aws_secret_access_key',
+ },
+ });
+ print('Fetch response:', res);
+ `
+
+ await insertHogFunction({
+ type: 'destination',
+ hog,
+ bytecode: await compileHog(hog),
+ inputs_schema: [
+ { key: 'aws_access_key_id', type: 'string', label: 'AKID', secret: true, required: true },
+ { key: 'aws_secret_access_key', type: 'string', label: 'SK', secret: true, required: true },
+ ],
+ inputs: {},
+ // Mirror what Django's `move_secret_inputs` produces in prod: secret
+ // inputs are Fernet-encrypted on `encrypted_inputs`. The Node manager
+ // detects the string form and decrypts back to the plaintext map shape
+ // before the executor sees the function.
+ encrypted_inputs: hub.encryptedFields.encrypt(
+ JSON.stringify({
+ aws_access_key_id: { value: ACCESS_KEY },
+ aws_secret_access_key: { value: SECRET_KEY },
+ })
+ ),
+ ...HOG_FILTERS_EXAMPLES.no_filters,
+ } as any)
+
+ // The default `fnFetchNoFilters` from beforeEach also matches this event;
+ // we expect both to fire, but we only inspect the Kinesis ones.
+ await eventsConsumer.processBatch([globals])
+
+ await waitForExpect(() => {
+ expect(sigv4FetchCalls.length).toBeGreaterThanOrEqual(2)
+ }, 5000).catch((e) => {
+ logger.warn('[TESTS] Expected two Kinesis fetch attempts (initial + retry)', {
+ sigv4FetchCount: sigv4FetchCalls.length,
+ allFetchCalls: mockFetch.mock.calls.length,
+ })
+ throw e
+ })
+
+ // Every attempt (including the retry) must carry a fresh SigV4 Authorization
+ // header derived from the decrypted `encrypted_inputs` map. A regression in
+ // the lookup path would either crash with the "input not found" error or
+ // ship an unsigned request — both visible here.
+ const sigv4Authorizations = sigv4FetchCalls.slice(0, 2).map(({ opts }) => {
+ const headers = (opts?.headers ?? {}) as Record<string, string>
+ return headers['Authorization'] ?? headers.authorization
+ })
+ const sigv4AmzDates = sigv4FetchCalls.slice(0, 2).map(({ opts }) => {
+ const headers = (opts?.headers ?? {}) as Record<string, string>
+ return headers['X-Amz-Date'] ?? headers['x-amz-date']
+ })
+
+ for (const auth of sigv4Authorizations) {
+ expect(auth).toMatch(
+ /^AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE\/\d{8}\/us-east-1\/kinesis\/aws4_request, SignedHeaders=[a-z0-9;-]+, Signature=[a-f0-9]{64}$/
+ )
+ }
+
+ // A retry must NOT reuse the signature from the first attempt. The 1.5s
+ // delay on the 500 response forces the two attempts to sign in different
+ // wall-clock seconds, so a correct implementation produces different
+ // X-Amz-Date values and therefore different signatures. A regression to
+ // "sign once, reuse on retry" makes these match and AWS returns
+ // InvalidSignatureException whenever the retry crosses the 5-minute
+ // signature window.
+ expect(sigv4AmzDates[0]).not.toEqual(sigv4AmzDates[1])
+ expect(sigv4Authorizations[0]).not.toEqual(sigv4Authorizations[1])
+ })
+
it('should handle fetch failures with retries', async () => {
mockFetch.mockImplementation(() => {
return Promise.resolve({
diff --git a/nodejs/src/cdp/services/hog-executor.service.test.ts b/nodejs/src/cdp/services/hog-executor.service.test.ts
index add383481843..ace8730d2be9 100644
--- a/nodejs/src/cdp/services/hog-executor.service.test.ts
+++ b/nodejs/src/cdp/services/hog-executor.service.test.ts
@@ -1290,6 +1290,193 @@ describe('Hog Executor', () => {
expect(result.invocation.queueScheduledAt).toBeUndefined()
})
+ describe('aws_sigv4', () => {
+ // `secret: true` HogFunction inputs land in `encrypted_inputs` after
+ // Django's `move_secret_inputs` runs on save. The Node manager decrypts
+ // `encrypted_inputs` in memory before the executor sees the function, so
+ // by the time we reach the fetch path it's a plaintext map keyed by
+ // input name. Seed *that* field — not `inputs` — so the tests mirror the
+ // production data shape for the Kinesis template.
+ const seedAwsCredentialInputs = (invocation: CyclotronJobInvocationHogFunction) => {
+ invocation.hogFunction.encrypted_inputs = {
+ ...(invocation.hogFunction.encrypted_inputs ?? {}),
+ aws_access_key_id: { value: 'AKIDEXAMPLE' },
+ aws_secret_access_key: { value: 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY' },
+ } as any
+ }
+
+ const sigv4Refs = {
+ service: 'kinesis',
+ region: 'us-east-1',
+ access_key_id_input: 'aws_access_key_id',
+ secret_access_key_input: 'aws_secret_access_key',
+ }
+
+ it('signs the request and Authorization header arrives at the upstream', async () => {
+ let receivedAuth: string | undefined
+ let receivedAmzDate: string | undefined
+ mockRequest.mockImplementation((req: any, res: any) => {
+ receivedAuth = req.headers.authorization
+ receivedAmzDate = req.headers['x-amz-date']
+ res.writeHead(200, { 'Content-Type': 'text/plain' })
+ res.end('ok')
+ })
+
+ const invocation = await createFetchInvocation({
+ url: `${baseUrl}/`,
+ method: 'POST',
+ body: '{}',
+ headers: { 'Content-Type': 'application/x-amz-json-1.1' },
+ aws_sigv4: sigv4Refs,
+ })
+ seedAwsCredentialInputs(invocation)
+
+ await executor.executeFetch(invocation)
+
+ expect(receivedAmzDate).toBe('20250101T000000Z')
+ expect(receivedAuth).toMatch(
+ /^AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE\/20250101\/us-east-1\/kinesis\/aws4_request, SignedHeaders=[a-z0-9;-]+, Signature=[a-f0-9]{64}$/
+ )
+ })
+
+ // Customer impact this prevents: the original bug ticket had a request
+ // signed at T, queued behind a timed-out attempt, then retried >5 min
+ // later — AWS rejected the retry with InvalidSignatureException because
+ // the X-Amz-Date inside the Authorization no longer matched server time.
+ it('produces a fresh signature on retry instead of reusing the original', async () => {
+ const receivedAuthHeaders: string[] = []
+ const receivedAmzDates: string[] = []
+ let callCount = 0
+ mockRequest.mockImplementation((req: any, res: any) => {
+ receivedAuthHeaders.push(req.headers.authorization)
+ receivedAmzDates.push(req.headers['x-amz-date'])
+ callCount++
+ if (callCount === 1) {
+ res.writeHead(500, { 'Content-Type': 'text/plain' })
+ res.end('first attempt fails')
+ } else {
+ res.writeHead(200, { 'Content-Type': 'text/plain' })
+ res.end('second attempt ok')
+ }
+ })
+
+ const invocation = await createFetchInvocation({
+ url: `${baseUrl}/`,
+ method: 'POST',
+ body: '{}',
+ headers: { 'Content-Type': 'application/x-amz-json-1.1' },
+ aws_sigv4: sigv4Refs,
+ })
+ seedAwsCredentialInputs(invocation)
+
+ let result = await executor.executeFetch(invocation)
+ expect(result.invocation.state.attempts).toBe(1)
+
+ // Simulate the cyclotron queue + backoff: by the time the retry
+ // actually runs, >6 minutes have passed. With the old "sign once
+ // in Hog" path this would push the signature past AWS's 5-minute
+ // window and the retry would 400 with InvalidSignatureException.
+ const retryTime = DateTime.fromObject({ year: 2025, month: 1, day: 1 }, { zone: 'UTC' }).plus({
+ minutes: 6,
+ })
+ jest.spyOn(Date, 'now').mockReturnValue(retryTime.toMillis())
+
+ result = await executor.executeFetch(result.invocation)
+
+ expect(receivedAmzDates[0]).toBe('20250101T000000Z')
+ expect(receivedAmzDates[1]).toBe('20250101T000600Z')
+ expect(receivedAuthHeaders[0]).not.toBe(receivedAuthHeaders[1])
+ expect(result.error).toBeUndefined()
+ })
+
+ // Defense in depth: queue payloads should never carry a stale
+ // Authorization, but if one ever leaks in (e.g. through a custom
+ // template that sets it directly), it must not be used.
+ it('overwrites any stale Authorization header sitting in the queue payload', async () => {
+ let receivedAuth: string | undefined
+ mockRequest.mockImplementation((req: any, res: any) => {
+ receivedAuth = req.headers.authorization
+ res.writeHead(200, { 'Content-Type': 'text/plain' })
+ res.end('ok')
+ })
+
+ const invocation = await createFetchInvocation({
+ url: `${baseUrl}/`,
+ method: 'POST',
+ body: '{}',
+ headers: {
+ 'Content-Type': 'application/x-amz-json-1.1',
+ Authorization: 'AWS4-HMAC-SHA256 Credential=STALE/19700101/us-east-1/kinesis/aws4_request, ...',
+ 'X-Amz-Date': '19700101T000000Z',
+ },
+ aws_sigv4: sigv4Refs,
+ })
+ seedAwsCredentialInputs(invocation)
+
+ await executor.executeFetch(invocation)
+
+ expect(receivedAuth).not.toContain('STALE')
+ expect(receivedAuth).toContain('AKIDEXAMPLE/20250101/us-east-1/kinesis/aws4_request')
+ })
+
+ // Defense in depth for an unusual case: if a custom template wires
+ // up the credential as a non-secret input (`secret: false`), the value
+ // will live on `inputs` rather than `encrypted_inputs`. The lookup
+ // must fall through to `inputs` so signing still works.
+ it('falls back to plaintext inputs when encrypted_inputs does not carry the credential', async () => {
+ let receivedAuth: string | undefined
+ mockRequest.mockImplementation((req: any, res: any) => {
+ receivedAuth = req.headers.authorization
+ res.writeHead(200, { 'Content-Type': 'text/plain' })
+ res.end('ok')
+ })
+
+ const invocation = await createFetchInvocation({
+ url: `${baseUrl}/`,
+ method: 'POST',
+ body: '{}',
+ headers: { 'Content-Type': 'application/x-amz-json-1.1' },
+ aws_sigv4: sigv4Refs,
+ })
+ invocation.hogFunction.inputs = {
+ ...(invocation.hogFunction.inputs ?? {}),
+ aws_access_key_id: { value: 'AKIDEXAMPLE' },
+ aws_secret_access_key: { value: 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY' },
+ } as any
+
+ await executor.executeFetch(invocation)
+
+ expect(receivedAuth).toContain('AKIDEXAMPLE/20250101/us-east-1/kinesis/aws4_request')
+ })
+
+ // If the input referenced by `*_input` is missing or non-string we must
+ // NOT fall through and ship an unsigned request to AWS — that'd 403 and
+ // potentially leak the request body in error logs.
+ it('errors loudly when the referenced credential input is missing', async () => {
+ mockRequest.mockImplementation((req: any, res: any) => {
+ res.writeHead(200, { 'Content-Type': 'text/plain' })
+ res.end('ok')
+ })
+
+ const invocation = await createFetchInvocation({
+ url: `${baseUrl}/`,
+ method: 'POST',
+ body: '{}',
+ headers: { 'Content-Type': 'application/x-amz-json-1.1' },
+ aws_sigv4: sigv4Refs,
+ })
+ // Intentionally do NOT seed inputs.
+
+ const result = await executor.executeFetch(invocation)
+
+ expect(mockRequest).not.toHaveBeenCalled()
+ expect(result.error).toBeInstanceOf(Error)
+ expect(result.error.message).toContain('AWS SigV4 signing failed')
+ expect(result.error.message).toContain('aws_access_key_id')
+ expect(result.error.message).toContain('aws_secret_access_key')
+ })
+ })
+
it('respects maxFetchRetries option to disable retries', async () => {
mockRequest.mockImplementation((req: any, res: any) => {
res.writeHead(500, { 'Content-Type': 'text/plain' })
diff --git a/nodejs/src/cdp/services/hog-executor.service.ts b/nodejs/src/cdp/services/hog-executor.service.ts
index 7e816d971bfe..a8388c80d565 100644
--- a/nodejs/src/cdp/services/hog-executor.service.ts
+++ b/nodejs/src/cdp/services/hog-executor.service.ts
@@ -28,6 +28,7 @@ import type {
MinimalLogEntry,
} from '../types'
import { createAddLogFunction, destinationE2eLagMsSummary, sanitizeLogMessage } from '../utils'
+import { resolveAwsSigV4Credentials, signAwsRequest } from '../utils/aws-sigv4'
import { execHog } from '../utils/hog-exec'
import { convertToHogFunctionFilterGlobal, filterFunctionInstrumented } from '../utils/hog-function-filtering'
import { createInvocation, createInvocationResult } from '../utils/invocation-utils'
@@ -793,7 +794,32 @@ export class HogExecutorService {
}
}
- const fetchParams: FetchOptions = { method, headers }
+ // AWS SigV4 signatures expire after ~5 minutes. Sign immediately before the
+ // fetch (every attempt — including retries) so a request that sat in the
+ // backoff queue or whose first attempt timed out cannot reach AWS with a
+ // stale signature. Signing artifacts (Authorization, X-Amz-Date) are
+ // regenerated here and never persisted back to queueParameters. Credential
+ // resolution + missing-input handling live in `aws-sigv4.ts` — see
+ // `resolveAwsSigV4Credentials` for the encrypted_inputs/inputs lookup order.
+ let signedHeaders = headers
+ if (params.aws_sigv4) {
+ const resolved = resolveAwsSigV4Credentials(params.aws_sigv4, invocation.hogFunction)
+ if (!resolved.ok) {
+ addLog('error', resolved.error)
+ result.error = new Error(resolved.error)
+ result.finished = true
+ return result
+ }
+ signedHeaders = signAwsRequest({
+ method,
+ url: params.url,
+ body: params.body ?? '',
+ headers,
+ credentials: resolved.credentials,
+ })
+ }
+
+ const fetchParams: FetchOptions = { method, headers: signedHeaders }
if (!['GET', 'HEAD'].includes(method) && params.body) {
fetchParams.body = params.body
diff --git a/nodejs/src/cdp/utils/aws-sigv4.test.ts b/nodejs/src/cdp/utils/aws-sigv4.test.ts
new file mode 100644
index 000000000000..a2aa0137825d
--- /dev/null
+++ b/nodejs/src/cdp/utils/aws-sigv4.test.ts
@@ -0,0 +1,337 @@
+import { CyclotronInvocationQueueParametersFetchAwsSigV4Type } from '~/schema/cyclotron'
+
+import { HogFunctionType } from '../types'
+import { resolveAwsSigV4Credentials, signAwsRequest } from './aws-sigv4'
+
+describe('signAwsRequest', () => {
+ const fixedNow = new Date('2015-08-30T12:36:00Z')
+
+ // AWS published test vector: get-vanilla
+ // https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html
+ // Service: 'service', region: 'us-east-1'
+ // AKID: AKIDEXAMPLE / SK: wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY
+ // Expected signature: 5fa00fa31553b73ebf1942676e86291e8372ff2a2260956d9b8aae1d763fbf31
+ it('matches AWS get-vanilla test vector', () => {
+ const headers = signAwsRequest({
+ method: 'GET',
+ url: 'https://example.amazonaws.com/',
+ body: '',
+ credentials: {
+ service: 'service',
+ region: 'us-east-1',
+ access_key_id: 'AKIDEXAMPLE',
+ secret_access_key: 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY',
+ },
+ now: fixedNow,
+ })
+
+ expect(headers['X-Amz-Date']).toBe('20150830T123600Z')
+ expect(headers.Authorization).toBe(
+ 'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20150830/us-east-1/service/aws4_request, ' +
+ 'SignedHeaders=host;x-amz-date, ' +
+ 'Signature=5fa00fa31553b73ebf1942676e86291e8372ff2a2260956d9b8aae1d763fbf31'
+ )
+ })
+
+ // Smoke test: same inputs at the same time yield the same signature.
+ it('is deterministic for a fixed timestamp', () => {
+ const args = {
+ method: 'POST',
+ url: 'https://kinesis.us-east-1.amazonaws.com/',
+ body: '{"StreamName":"s","PartitionKey":"p","Data":"ZA=="}',
+ headers: {
+ 'Content-Type': 'application/x-amz-json-1.1',
+ 'X-Amz-Target': 'Kinesis_20131202.PutRecord',
+ },
+ credentials: {
+ service: 'kinesis',
+ region: 'us-east-1',
+ access_key_id: 'AKIDEXAMPLE',
+ secret_access_key: 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY',
+ },
+ now: fixedNow,
+ }
+ expect(signAwsRequest(args)).toEqual(signAwsRequest(args))
+ })
+
+ // Re-signing must produce a different signature/timestamp when `now` advances —
+ // this is the property the cyclotron retry path relies on to avoid AWS's
+ // 5-minute signature expiry window.
+ it('produces a fresh signature when re-signed with a later timestamp', () => {
+ const base = {
+ method: 'POST',
+ url: 'https://kinesis.us-east-1.amazonaws.com/',
+ body: '{}',
+ credentials: {
+ service: 'kinesis',
+ region: 'us-east-1',
+ access_key_id: 'AKIDEXAMPLE',
+ secret_access_key: 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY',
+ },
+ }
+ const first = signAwsRequest({ ...base, now: new Date('2026-06-22T07:28:57Z') })
+ const second = signAwsRequest({ ...base, now: new Date('2026-06-22T07:35:54Z') })
+
+ expect(first['X-Amz-Date']).toBe('20260622T072857Z')
+ expect(second['X-Amz-Date']).toBe('20260622T073554Z')
+ expect(first.Authorization).not.toBe(second.Authorization)
+ })
+
+ // Stale signing artifacts inherited from a previous attempt's queue payload
+ // must be discarded — otherwise we'd resign on top of an old Authorization.
+ it('strips stale Authorization and X-Amz-Date headers before re-signing', () => {
+ const headers = signAwsRequest({
+ method: 'POST',
+ url: 'https://kinesis.us-east-1.amazonaws.com/',
+ body: '{}',
+ headers: {
+ 'Content-Type': 'application/x-amz-json-1.1',
+ Authorization: 'AWS4-HMAC-SHA256 Credential=STALE/19700101/us-east-1/kinesis/aws4_request, ...',
+ 'X-Amz-Date': '19700101T000000Z',
+ },
+ credentials: {
+ service: 'kinesis',
+ region: 'us-east-1',
+ access_key_id: 'AKIDEXAMPLE',
+ secret_access_key: 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY',
+ },
+ now: fixedNow,
+ })
+
+ expect(headers.Authorization).not.toContain('STALE')
+ expect(headers.Authorization).toContain('Credential=AKIDEXAMPLE/20150830/us-east-1/kinesis/aws4_request')
+ expect(headers['X-Amz-Date']).toBe('20150830T123600Z')
+ })
+
+ it('includes X-Amz-Security-Token in signed headers when session token is provided', () => {
+ const headers = signAwsRequest({
+ method: 'POST',
+ url: 'https://kinesis.us-east-1.amazonaws.com/',
+ body: '{}',
+ credentials: {
+ service: 'kinesis',
+ region: 'us-east-1',
+ access_key_id: 'AKIDEXAMPLE',
+ secret_access_key: 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY',
+ session_token: 'session-token-value',
+ },
+ now: fixedNow,
+ })
+
+ expect(headers['X-Amz-Security-Token']).toBe('session-token-value')
+ expect(headers.Authorization).toContain('x-amz-security-token')
+ })
+
+ it('derives Host from the URL', () => {
+ const headers = signAwsRequest({
+ method: 'POST',
+ url: 'https://kinesis.eu-central-1.amazonaws.com/',
+ body: '{}',
+ credentials: {
+ service: 'kinesis',
+ region: 'eu-central-1',
+ access_key_id: 'AKIDEXAMPLE',
+ secret_access_key: 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY',
+ },
+ now: fixedNow,
+ })
+
+ expect(headers.Host).toBe('kinesis.eu-central-1.amazonaws.com')
+ })
+
+ // Regression for the pre-refactor Hog-side signer. Before signing moved out of
+ // the Kinesis Hog template, `test_template_aws_kinesis.py` asserted the exact
+ // outgoing Authorization header for this frozen time + input fixture, including
+ // the signature hex `65b18913...`. If the Node signer ever diverges from that
+ // shape we lose backwards compatibility with the prior production signatures
+ // and any external system relying on identical canonical-request semantics.
+ it('matches the in-Hog Kinesis signer for the test_template_aws_kinesis fixture', () => {
+ const headers = signAwsRequest({
+ method: 'POST',
+ url: 'https://kinesis.aws_region.amazonaws.com',
+ body: '{"StreamName": "aws_kinesis_stream_arn", "PartitionKey": "1", "Data": "eyJoZWxsbyI6ICJ3b3JsZCJ9"}',
+ headers: {
+ 'Content-Type': 'application/x-amz-json-1.1',
+ 'X-Amz-Target': 'Kinesis_20131202.PutRecord',
+ },
+ credentials: {
+ service: 'kinesis',
+ region: 'aws_region',
+ access_key_id: 'aws_access_key_id',
+ secret_access_key: 'aws_secret_access_key',
+ },
+ now: new Date('2024-04-16T12:34:51Z'),
+ })
+
+ expect(headers).toEqual({
+ 'Content-Type': 'application/x-amz-json-1.1',
+ 'X-Amz-Target': 'Kinesis_20131202.PutRecord',
+ 'X-Amz-Date': '20240416T123451Z',
+ Host: 'kinesis.aws_region.amazonaws.com',
+ Authorization:
+ 'AWS4-HMAC-SHA256 Credential=aws_access_key_id/20240416/aws_region/kinesis/aws4_request, ' +
+ 'SignedHeaders=content-type;host;x-amz-date;x-amz-target, ' +
+ 'Signature=65b18913b42d8a7a1d33c0711da192d5a2e99eb79fb08ab3e5eefb6488b903ff',
+ })
+ })
+
+ // Regression guard: a malformed percent-encoded query segment (e.g.
+ // `?metric=p95%tile` or a bare `%`) used to crash `decodeURIComponent`
+ // and let a URIError bubble out of `signAwsRequest`, failing the entire
+ // fetch attempt instead of producing a signature. Kinesis doesn't carry
+ // query strings, but the canonical-query-string code is general-purpose
+ // and ships with SQS / EventBridge ambitions.
+ it('does not throw on malformed percent-encoded query strings', () => {
+ expect(() =>
+ signAwsRequest({
+ method: 'GET',
+ url: 'https://kinesis.us-east-1.amazonaws.com/?metric=p95%tile&ok=hello%20world&bad=%',
+ body: '',
+ credentials: {
+ service: 'kinesis',
+ region: 'us-east-1',
+ access_key_id: 'AKIDEXAMPLE',
+ secret_access_key: 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY',
+ },
+ now: fixedNow,
+ })
+ ).not.toThrow()
+ })
+})
+
+describe('resolveAwsSigV4Credentials', () => {
+ const sigv4Refs: CyclotronInvocationQueueParametersFetchAwsSigV4Type = {
+ service: 'kinesis',
+ region: 'us-east-1',
+ access_key_id_input: 'aws_access_key_id',
+ secret_access_key_input: 'aws_secret_access_key',
+ }
+
+ const hogFunctionWith = (
+ encrypted: Record<string, { value: unknown }> | null = null,
+ inputs: Record<string, { value: unknown }> | null = null
+ ): Pick<HogFunctionType, 'inputs' | 'encrypted_inputs'> =>
+ ({
+ inputs: inputs as any,
+ encrypted_inputs: encrypted as any,
+ }) as Pick<HogFunctionType, 'inputs' | 'encrypted_inputs'>
+
+ it('resolves credentials from encrypted_inputs (the production path for secret: true)', () => {
+ const result = resolveAwsSigV4Credentials(
+ sigv4Refs,
+ hogFunctionWith({
+ aws_access_key_id: { value: 'AKIDEXAMPLE' },
+ aws_secret_access_key: { value: 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY' },
+ })
+ )
+
+ expect(result.ok).toBe(true)
+ if (result.ok) {
+ expect(result.credentials.access_key_id).toBe('AKIDEXAMPLE')
+ expect(result.credentials.secret_access_key).toBe('wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY')
+ expect(result.credentials.region).toBe('us-east-1')
+ expect(result.credentials.service).toBe('kinesis')
+ expect(result.credentials.session_token).toBeUndefined()
+ }
+ })
+
+ it('falls back to plaintext inputs when encrypted_inputs is missing the key', () => {
+ const result = resolveAwsSigV4Credentials(
+ sigv4Refs,
+ hogFunctionWith(null, {
+ aws_access_key_id: { value: 'AKIDEXAMPLE' },
+ aws_secret_access_key: { value: 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY' },
+ })
+ )
+
+ expect(result.ok).toBe(true)
+ })
+
+ it('returns the encrypted_inputs value when both fields define the key', () => {
+ const result = resolveAwsSigV4Credentials(
+ sigv4Refs,
+ hogFunctionWith(
+ {
+ aws_access_key_id: { value: 'FROM_ENCRYPTED' },
+ aws_secret_access_key: { value: 'SECRET_ENCRYPTED' },
+ },
+ {
+ aws_access_key_id: { value: 'FROM_PLAINTEXT' },
+ aws_secret_access_key: { value: 'SECRET_PLAINTEXT' },
+ }
+ )
+ )
+
+ expect(result.ok).toBe(true)
+ if (result.ok) {
+ expect(result.credentials.access_key_id).toBe('FROM_ENCRYPTED')
+ expect(result.credentials.secret_access_key).toBe('SECRET_ENCRYPTED')
+ }
+ })
+
+ it('reports both missing inputs in the error message', () => {
+ const result = resolveAwsSigV4Credentials(sigv4Refs, hogFunctionWith())
+ expect(result.ok).toBe(false)
+ if (!result.ok) {
+ expect(result.error).toContain('aws_access_key_id')
+ expect(result.error).toContain('aws_secret_access_key')
+ expect(result.error).toContain('Refusing to send an unsigned request')
+ }
+ })
+
+ it('reports only the missing input when only one is absent', () => {
+ const result = resolveAwsSigV4Credentials(
+ sigv4Refs,
+ hogFunctionWith({ aws_access_key_id: { value: 'AKIDEXAMPLE' } })
+ )
+ expect(result.ok).toBe(false)
+ if (!result.ok) {
+ expect(result.error).toContain('aws_secret_access_key')
+ expect(result.error).not.toContain('aws_access_key_id')
+ }
+ })
+
+ it('treats non-string values as missing (defensive: an int or null would silently break signing)', () => {
+ const result = resolveAwsSigV4Credentials(
+ sigv4Refs,
+ hogFunctionWith({
+ aws_access_key_id: { value: 12345 },
+ aws_secret_access_key: { value: null },
+ })
+ )
+ expect(result.ok).toBe(false)
+ })
+
+ it('includes session_token when session_token_input is provided and resolves', () => {
+ const result = resolveAwsSigV4Credentials(
+ { ...sigv4Refs, session_token_input: 'aws_session_token' },
+ hogFunctionWith({
+ aws_access_key_id: { value: 'AKIDEXAMPLE' },
+ aws_secret_access_key: { value: 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY' },
+ aws_session_token: { value: 'session-token-value' },
+ })
+ )
+
+ expect(result.ok).toBe(true)
+ if (result.ok) {
+ expect(result.credentials.session_token).toBe('session-token-value')
+ }
+ })
+
+ // A missing optional session token should not fail-closed — the request is
+ // still signable with just the long-term credentials.
+ it('skips session_token when session_token_input is set but the input is missing', () => {
+ const result = resolveAwsSigV4Credentials(
+ { ...sigv4Refs, session_token_input: 'aws_session_token' },
+ hogFunctionWith({
+ aws_access_key_id: { value: 'AKIDEXAMPLE' },
+ aws_secret_access_key: { value: 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY' },
+ })
+ )
+
+ expect(result.ok).toBe(true)
+ if (result.ok) {
+ expect(result.credentials.session_token).toBeUndefined()
+ }
+ })
+})
diff --git a/nodejs/src/cdp/utils/aws-sigv4.ts b/nodejs/src/cdp/utils/aws-sigv4.ts
new file mode 100644
index 000000000000..437917bc62c4
--- /dev/null
+++ b/nodejs/src/cdp/utils/aws-sigv4.ts
@@ -0,0 +1,227 @@
+import { createHash, createHmac } from 'node:crypto'
+
+import { CyclotronInvocationQueueParametersFetchAwsSigV4Type } from '~/schema/cyclotron'
+
+import { HogFunctionType } from '../types'
+
+export type AwsSigV4Credentials = {
+ service: string
+ region: string
+ access_key_id: string
+ secret_access_key: string
+ session_token?: string
+}
+
+export type ResolvedAwsSigV4Credentials = { ok: true; credentials: AwsSigV4Credentials } | { ok: false; error: string }
+
+export type SignAwsRequestArgs = {
+ method: string
+ url: string
+ body?: string | null
+ headers?: Record<string, string>
+ credentials: AwsSigV4Credentials
+ now?: Date
+}
+
+const ALGORITHM = 'AWS4-HMAC-SHA256'
+
+// Headers that are signing artifacts — must always be rebuilt, never inherited
+// from a previous attempt's queue payload.
+const SIGNING_HEADERS = new Set(['authorization', 'x-amz-date', 'x-amz-content-sha256', 'x-amz-security-token'])
+
+function sha256Hex(input: string): string {
+ return createHash('sha256').update(input).digest('hex')
+}
+
+function hmac(key: Buffer | string, data: string): Buffer {
+ return createHmac('sha256', key).update(data).digest()
+}
+
+function deriveSigningKey(secret: string, date: string, region: string, service: string): Buffer {
+ const kDate = hmac(`AWS4${secret}`, date)
+ const kRegion = hmac(kDate, region)
+ const kService = hmac(kRegion, service)
+ return hmac(kService, 'aws4_request')
+}
+
+// AWS canonical URI encoding: encodeURIComponent + reserved-char fixes.
+// Unreserved per RFC 3986: A-Z a-z 0-9 - _ . ~. Slashes are kept as path separators.
+function awsUriEncode(input: string, encodeSlash: boolean): string {
+ let out = ''
+ for (const ch of input) {
+ if (/[A-Za-z0-9\-_.~]/.test(ch)) {
+ out += ch
+ } else if (ch === '/' && !encodeSlash) {
+ out += ch
+ } else {
+ out += encodeURIComponent(ch).replace(/[!'()*]/g, (c) => '%' + c.charCodeAt(0).toString(16).toUpperCase())
+ }
+ }
+ return out
+}
+
+// Decode a single percent-encoded query-string segment. Bare `%` or `%X` (no
+// second hex digit) makes `decodeURIComponent` throw URIError; AWS canonical
+// encoding still needs to produce *some* string, so we treat malformed input
+// as opaque and re-encode it as-is. Callers must not surface URIError from a
+// signing path — a thrown error here fails the entire fetch instead of letting
+// the upstream return a normal 400.
+function safeDecodeQuerySegment(s: string): string {
+ try {
+ return decodeURIComponent(s)
+ } catch {
+ return s
+ }
+}
+
+function canonicalQueryString(search: string): string {
+ if (!search || search === '?') {
+ return ''
+ }
+ const params: [string, string][] = []
+ for (const part of search.replace(/^\?/, '').split('&')) {
+ if (!part) {
+ continue
+ }
+ const eq = part.indexOf('=')
+ const k = eq === -1 ? part : part.slice(0, eq)
+ const v = eq === -1 ? '' : part.slice(eq + 1)
+ params.push([awsUriEncode(safeDecodeQuerySegment(k), true), awsUriEncode(safeDecodeQuerySegment(v), true)])
+ }
+ params.sort(([a1, a2], [b1, b2]) => (a1 < b1 ? -1 : a1 > b1 ? 1 : a2 < b2 ? -1 : a2 > b2 ? 1 : 0))
+ return params.map(([k, v]) => `${k}=${v}`).join('&')
+}
+
+function formatAmzDate(d: Date): { amzDate: string; date: string } {
+ const pad = (n: number, w = 2) => n.toString().padStart(w, '0')
+ const yyyy = d.getUTCFullYear().toString()
+ const mm = pad(d.getUTCMonth() + 1)
+ const dd = pad(d.getUTCDate())
+ const hh = pad(d.getUTCHours())
+ const mi = pad(d.getUTCMinutes())
+ const ss = pad(d.getUTCSeconds())
+ return { amzDate: `${yyyy}${mm}${dd}T${hh}${mi}${ss}Z`, date: `${yyyy}${mm}${dd}` }
+}
+
+/**
+ * Signs an HTTP request with AWS Signature Version 4.
+ *
+ * Returns a fresh headers object that callers should USE INSTEAD OF any prior
+ * `Authorization` / `X-Amz-Date` headers — those are signing artifacts that
+ * become invalid on every retry, so we strip any inherited values before
+ * recomputing them.
+ *
+ * The signature is bound to `now` (defaults to current wall clock). AWS rejects
+ * signatures older than ~5 minutes, so this function must be called immediately
+ * before each fetch attempt — not at request-construction time.
+ */
+export function signAwsRequest({
+ method,
+ url,
+ body,
+ headers,
+ credentials,
+ now,
+}: SignAwsRequestArgs): Record<string, string> {
+ const parsed = new URL(url)
+ // Read time via `Date.now()` so test seams that mock `Date.now` (the standard
+ // PostHog jest pattern) flow through to the signature timestamp.
+ const { amzDate, date } = formatAmzDate(now ?? new Date(Date.now()))
+
+ const baseHeaders: Record<string, string> = {}
+ for (const [k, v] of Object.entries(headers ?? {})) {
+ if (!SIGNING_HEADERS.has(k.toLowerCase())) {
+ baseHeaders[k] = v
+ }
+ }
+ baseHeaders['Host'] = parsed.host
+ baseHeaders['X-Amz-Date'] = amzDate
+ if (credentials.session_token) {
+ baseHeaders['X-Amz-Security-Token'] = credentials.session_token
+ }
+
+ const sortedHeaderEntries = Object.entries(baseHeaders)
+ .map(([k, v]) => [k.toLowerCase(), v.trim().replace(/\s+/g, ' ')] as [string, string])
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
+
+ const canonicalHeaders = sortedHeaderEntries.map(([k, v]) => `${k}:${v}`).join('\n') + '\n'
+ const signedHeaders = sortedHeaderEntries.map(([k]) => k).join(';')
+
+ const path = parsed.pathname || '/'
+ const canonicalRequest = [
+ method.toUpperCase(),
+ awsUriEncode(path, false),
+ canonicalQueryString(parsed.search),
+ canonicalHeaders,
+ signedHeaders,
+ sha256Hex(body ?? ''),
+ ].join('\n')
+
+ const credentialScope = `${date}/${credentials.region}/${credentials.service}/aws4_request`
+ const stringToSign = [ALGORITHM, amzDate, credentialScope, sha256Hex(canonicalRequest)].join('\n')
+
+ const signingKey = deriveSigningKey(credentials.secret_access_key, date, credentials.region, credentials.service)
+ const signature = createHmac('sha256', signingKey).update(stringToSign).digest('hex')
+
+ const authorization =
+ `${ALGORITHM} Credential=${credentials.access_key_id}/${credentialScope}, ` +
+ `SignedHeaders=${signedHeaders}, ` +
+ `Signature=${signature}`
+
+ return {
+ ...baseHeaders,
+ Authorization: authorization,
+ }
+}
+
+/**
+ * Resolves the AWS credentials referenced by an `aws_sigv4` queue payload from a
+ * HogFunction's inputs.
+ *
+ * `secret: true` HogFunction inputs land in `encrypted_inputs` after Django's
+ * `move_secret_inputs` runs on save (and the Node manager decrypts that field in
+ * memory). The Kinesis credential inputs are flagged `secret: true`, so check
+ * `encrypted_inputs` first; fall back to `inputs` for the unusual case of a
+ * non-secret credential.
+ *
+ * Returns a tagged union so callers can fail closed on missing inputs without
+ * shipping an unsigned request to AWS. The error message lists the input keys
+ * that could not be resolved so the failure is debuggable from logs alone.
+ */
+export function resolveAwsSigV4Credentials(
+ sigv4: CyclotronInvocationQueueParametersFetchAwsSigV4Type,
+ hogFunction: Pick<HogFunctionType, 'inputs' | 'encrypted_inputs'>
+): ResolvedAwsSigV4Credentials {
+ const lookup = (key: string): unknown =>
+ hogFunction.encrypted_inputs?.[key]?.value ?? hogFunction.inputs?.[key]?.value
+
+ const accessKeyId = lookup(sigv4.access_key_id_input)
+ const secretAccessKey = lookup(sigv4.secret_access_key_input)
+ const sessionToken = sigv4.session_token_input ? lookup(sigv4.session_token_input) : undefined
+
+ const missing: string[] = []
+ if (typeof accessKeyId !== 'string') {
+ missing.push(sigv4.access_key_id_input)
+ }
+ if (typeof secretAccessKey !== 'string') {
+ missing.push(sigv4.secret_access_key_input)
+ }
+
+ if (missing.length > 0) {
+ return {
+ ok: false,
+ error: `AWS SigV4 signing failed: input(s) ${missing.join(', ')} not found on hog function or not a string. Refusing to send an unsigned request to AWS.`,
+ }
+ }
+
+ return {
+ ok: true,
+ credentials: {
+ service: sigv4.service,
+ region: sigv4.region,
+ access_key_id: accessKeyId as string,
+ secret_access_key: secretAccessKey as string,
+ session_token: typeof sessionToken === 'string' ? sessionToken : undefined,
+ },
+ }
+}
diff --git a/nodejs/src/schema/cyclotron.ts b/nodejs/src/schema/cyclotron.ts
index 8343e5128dd2..4cb047e65d70 100644
--- a/nodejs/src/schema/cyclotron.ts
+++ b/nodejs/src/schema/cyclotron.ts
@@ -61,6 +61,27 @@ export type CyclotronInputType = z.infer<typeof CyclotronInputSchema>
export type CyclotronInputMappingType = z.infer<typeof CyclotronInputMappingSchema>
+// When `aws_sigv4` is present on a fetch queue payload, the cyclotron fetch
+// executor re-signs the request with AWS Signature V4 immediately before each
+// attempt (including retries), overwriting any stale `Authorization` and
+// `X-Amz-Date` headers. This is the only path that keeps a retry within AWS's
+// 5-minute signature window — never embed a pre-signed Authorization header
+// in the queue payload.
+//
+// Credentials are NOT carried on the queue payload — the `*_input` fields are
+// input-key references that the executor resolves against `HogFunction.inputs`
+// at fetch time. The cyclotron `cyclotron_jobs.state` blob is plaintext JSON;
+// embedding credential strings on the queue payload would defeat the at-rest
+// encryption that `EncryptedJSONStringField` provides on
+// `posthog_hogfunction.encrypted_inputs`.
+export const CyclotronInvocationQueueParametersFetchAwsSigV4Schema = z.object({
+ service: z.string(),
+ region: z.string(),
+ access_key_id_input: z.string(),
+ secret_access_key_input: z.string(),
+ session_token_input: z.string().optional(),
+})
+
export const CyclotronInvocationQueueParametersFetchSchema = z.object({
type: z.literal('fetch'),
url: z.string(),
@@ -68,6 +89,7 @@ export const CyclotronInvocationQueueParametersFetchSchema = z.object({
body: z.union([z.string(), z.null()]).optional(),
max_tries: z.number().optional(),
headers: z.record(z.string(), z.string()).optional(),
+ aws_sigv4: CyclotronInvocationQueueParametersFetchAwsSigV4Schema.optional(),
})
export const CyclotronInvocationQueueParametersEmailSchema = z.object({
@@ -88,6 +110,9 @@ export const CyclotronInvocationQueueParametersEmailSchema = z.object({
html: z.string(),
})
+export type CyclotronInvocationQueueParametersFetchAwsSigV4Type = z.infer<
+ typeof CyclotronInvocationQueueParametersFetchAwsSigV4Schema
+>
export type CyclotronInvocationQueueParametersFetchType = z.infer<typeof CyclotronInvocationQueueParametersFetchSchema>
export type CyclotronInvocationQueueParametersEmailType = z.infer<typeof CyclotronInvocationQueueParametersEmailSchema>
diff --git a/posthog/cdp/templates/aws_kinesis/template_aws_kinesis.py b/posthog/cdp/templates/aws_kinesis/template_aws_kinesis.py
index 38c8828dec9c..abc6f943631a 100644
--- a/posthog/cdp/templates/aws_kinesis/template_aws_kinesis.py
+++ b/posthog/cdp/templates/aws_kinesis/template_aws_kinesis.py
@@ -11,74 +11,26 @@ template: HogFunctionTemplateDC = HogFunctionTemplateDC(
category=["Analytics"],
code_language="hog",
code="""
-fun getPayload() {
- let region := inputs.aws_region
- let service := 'kinesis'
- let amzDate := formatDateTime(now(), '%Y%m%dT%H%i%sZ')
- let date := formatDateTime(now(), '%Y%m%d')
+let payload := jsonStringify({
+ 'StreamName': inputs.aws_kinesis_stream_name,
+ 'PartitionKey': inputs.aws_kinesis_partition_key ?? generateUUIDv4(),
+ 'Data': base64Encode(jsonStringify(inputs.payload)),
+})
- let payload := jsonStringify({
- 'StreamName': inputs.aws_kinesis_stream_name,
- 'PartitionKey': inputs.aws_kinesis_partition_key ?? generateUUIDv4(),
- 'Data': base64Encode(jsonStringify(inputs.payload)),
- })
-
- let requestHeaders := {
+let res := fetch(f'https://kinesis.{inputs.aws_region}.amazonaws.com', {
+ 'method': 'POST',
+ 'headers': {
'Content-Type': 'application/x-amz-json-1.1',
'X-Amz-Target': 'Kinesis_20131202.PutRecord',
- 'X-Amz-Date': amzDate,
- 'Host': f'kinesis.{region}.amazonaws.com',
- }
-
- let canonicalHeaderParts := []
- for (let key, value in requestHeaders) {
- let val := replaceAll(trim(value), '\\\\s+', ' ')
- canonicalHeaderParts := arrayPushBack(canonicalHeaderParts, f'{lower(key)}:{val}')
- }
- let canonicalHeaders := arrayStringConcat(arraySort(canonicalHeaderParts), '\\n') || '\\n'
-
- let signedHeaderParts := []
- for (let key, value in requestHeaders) {
- signedHeaderParts := arrayPushBack(signedHeaderParts, lower(key))
- }
- let signedHeaders := arrayStringConcat(arraySort(signedHeaderParts), ';')
-
- let canonicalRequest := arrayStringConcat([
- 'POST',
- '/',
- '',
- canonicalHeaders,
- signedHeaders,
- sha256Hex(payload),
- ], '\\n')
-
- let credentialScope := f'{date}/{region}/{service}/aws4_request'
- let stringToSign := arrayStringConcat([
- 'AWS4-HMAC-SHA256',
- amzDate,
- credentialScope,
- sha256Hex(canonicalRequest),
- ], '\\n')
-
- let signature := sha256HmacChainHex([
- f'AWS4{inputs.aws_secret_access_key}', date, region, service, 'aws4_request', stringToSign
- ])
-
- let authorizationHeader :=
- f'AWS4-HMAC-SHA256 Credential={inputs.aws_access_key_id}/{credentialScope}, ' ||
- f'SignedHeaders={signedHeaders}, ' ||
- f'Signature={signature}'
-
- requestHeaders['Authorization'] := authorizationHeader
-
- return {
- 'headers': requestHeaders,
- 'body': payload,
- 'method': 'POST'
- }
-}
-
-let res := fetch(f'https://kinesis.{inputs.aws_region}.amazonaws.com', getPayload())
+ },
+ 'body': payload,
+ 'aws_sigv4': {
+ 'service': 'kinesis',
+ 'region': inputs.aws_region,
+ 'access_key_id_input': 'aws_access_key_id',
+ 'secret_access_key_input': 'aws_secret_access_key',
+ },
+})
if (res.status >= 200 and res.status < 300) {
print('Event sent successfully!')
diff --git a/posthog/cdp/templates/aws_kinesis/test_template_aws_kinesis.py b/posthog/cdp/templates/aws_kinesis/test_template_aws_kinesis.py
index 8a284a7addde..248f120aceae 100644
--- a/posthog/cdp/templates/aws_kinesis/test_template_aws_kinesis.py
+++ b/posthog/cdp/templates/aws_kinesis/test_template_aws_kinesis.py
@@ -20,18 +20,25 @@ class TestTemplateAwsKinesis(BaseHogFunctionTemplateTest):
}
)
+ # The Hog template now hands signing off to the Node.js cyclotron fetch executor,
+ # which re-signs on every attempt. The aws_sigv4 bag carries input-key references,
+ # not credential values — the executor resolves them from HogFunction.inputs at
+ # fetch time so secrets never enter the plaintext queue payload.
assert res.result is None
assert self.get_mock_fetch_calls()[0] == (
"https://kinesis.aws_region.amazonaws.com",
{
+ "method": "POST",
"headers": {
"Content-Type": "application/x-amz-json-1.1",
"X-Amz-Target": "Kinesis_20131202.PutRecord",
- "X-Amz-Date": "20240416T123451Z",
- "Host": "kinesis.aws_region.amazonaws.com",
- "Authorization": "AWS4-HMAC-SHA256 Credential=aws_access_key_id/20240416/aws_region/kinesis/aws4_request, SignedHeaders=content-type;host;x-amz-date;x-amz-target, Signature=65b18913b42d8a7a1d33c0711da192d5a2e99eb79fb08ab3e5eefb6488b903ff",
},
"body": '{"StreamName": "aws_kinesis_stream_arn", "PartitionKey": "1", "Data": "eyJoZWxsbyI6ICJ3b3JsZCJ9"}',
- "method": "POST",
+ "aws_sigv4": {
+ "service": "kinesis",
+ "region": "aws_region",
+ "access_key_id_input": "aws_access_key_id",
+ "secret_access_key_input": "aws_secret_access_key",
+ },
},
)