Skip to content

fix(lambda): handle missing context for some lambda functions#7445

Merged
purple4reina merged 6 commits intomasterfrom
joey/fix-lambda-authorizer-context-extraction
Feb 10, 2026
Merged

fix(lambda): handle missing context for some lambda functions#7445
purple4reina merged 6 commits intomasterfrom
joey/fix-lambda-authorizer-context-extraction

Conversation

@joeyzhao2018
Copy link
Copy Markdown
Contributor

@joeyzhao2018 joeyzhao2018 commented Feb 5, 2026

It is possible to create a lambda function without including the context in the method signature - they only receive an event parameter. Previously, the extractContext() function would throw "Could not extract context" when it couldn't find a context object with getRemainingTimeInMillis.

This change makes extractContext() return null instead of throwing, and updates the datadog() wrapper to skip timeout checking when context is not available. This allows these types of functions to be instrumented without crashing.

Fixes: DataDog/datadog-lambda-js#721

Please make sure your changes are properly tested!

What does this PR do?

Motivation

Additional Notes

Lambda Authorizers and some other Lambda handler types do not receive
a context object - they only receive an event parameter. Previously,
the extractContext() function would throw "Could not extract context"
when it couldn't find a context object with getRemainingTimeInMillis.

This change makes extractContext() return undefined instead of throwing,
and updates the datadog() wrapper to skip timeout checking when context
is not available. This allows Lambda Authorizers to be instrumented
without crashing.

Fixes: DataDog/datadog-lambda-js#721

Co-Authored-By: Claude Opus 4.5 <[email protected]>
@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Feb 5, 2026

Overall package size

Self size: 4.58 MB
Deduped: 5.42 MB
No deduping: 5.42 MB

Dependency sizes | name | version | self size | total size | |------|---------|-----------|------------| | import-in-the-middle | 2.0.6 | 81.92 kB | 813.08 kB | | dc-polyfill | 0.1.10 | 26.73 kB | 26.73 kB |

🤖 This report was automatically generated by heaviest-objects-in-the-universe

@codecov
Copy link
Copy Markdown

codecov bot commented Feb 5, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 80.31%. Comparing base (d5e899b) to head (b4f3039).
⚠️ Report is 21 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #7445      +/-   ##
==========================================
- Coverage   80.42%   80.31%   -0.12%     
==========================================
  Files         732      731       -1     
  Lines       31055    31134      +79     
==========================================
+ Hits        24975    25004      +29     
- Misses       6080     6130      +50     
Flag Coverage Δ
aiguard-macos 39.07% <ø> (-0.11%) ⬇️
aiguard-ubuntu 39.19% <ø> (-0.03%) ⬇️
aiguard-windows 38.93% <ø> (-0.14%) ⬇️
apm-capabilities-tracing-macos 48.82% <ø> (-0.08%) ⬇️
apm-capabilities-tracing-ubuntu 48.85% <ø> (-0.05%) ⬇️
apm-capabilities-tracing-windows 48.55% <ø> (-0.08%) ⬇️
apm-integrations-child-process 38.65% <ø> (-0.03%) ⬇️
apm-integrations-couchbase-18 37.40% <ø> (-0.03%) ⬇️
apm-integrations-couchbase-eol 38.04% <ø> (-0.03%) ⬇️
apm-integrations-oracledb 38.05% <ø> (-0.06%) ⬇️
appsec-express 55.45% <ø> (+<0.01%) ⬆️
appsec-fastify 52.03% <ø> (-0.04%) ⬇️
appsec-graphql 52.40% <ø> (+0.01%) ⬆️
appsec-kafka 44.70% <ø> (-0.02%) ⬇️
appsec-ldapjs 44.39% <ø> (-0.01%) ⬇️
appsec-lodash 44.07% <ø> (-0.01%) ⬇️
appsec-macos 58.51% <ø> (-0.04%) ⬇️
appsec-mongodb-core 49.29% <ø> (+0.02%) ⬆️
appsec-mongoose 49.98% <ø> (+0.01%) ⬆️
appsec-mysql 51.35% <ø> (+0.01%) ⬆️
appsec-node-serialize 43.58% <ø> (-0.01%) ⬇️
appsec-passport 48.15% <ø> (-0.04%) ⬇️
appsec-postgres 51.14% <ø> (+0.01%) ⬆️
appsec-sourcing 42.92% <ø> (-0.01%) ⬇️
appsec-template 43.75% <ø> (-0.01%) ⬇️
appsec-ubuntu 58.59% <ø> (+0.01%) ⬆️
appsec-windows 58.36% <ø> (-0.08%) ⬇️
instrumentations-instrumentation-bluebird 32.35% <ø> (+<0.01%) ⬆️
instrumentations-instrumentation-body-parser 40.86% <ø> (+0.03%) ⬆️
instrumentations-instrumentation-child_process 37.96% <ø> (-0.03%) ⬇️
instrumentations-instrumentation-cookie-parser 34.57% <ø> (-0.04%) ⬇️
instrumentations-instrumentation-express 34.92% <ø> (-0.04%) ⬇️
instrumentations-instrumentation-express-mongo-sanitize 34.71% <ø> (-0.04%) ⬇️
instrumentations-instrumentation-express-session 40.47% <ø> (-0.04%) ⬇️
instrumentations-instrumentation-fs 31.95% <ø> (+<0.01%) ⬆️
instrumentations-instrumentation-generic-pool 30.20% <ø> (+0.39%) ⬆️
instrumentations-instrumentation-http 39.67% <ø> (-0.06%) ⬇️
instrumentations-instrumentation-knex 32.35% <ø> (+<0.01%) ⬆️
instrumentations-instrumentation-mongoose 33.69% <ø> (-0.03%) ⬇️
instrumentations-instrumentation-multer 40.60% <ø> (+0.03%) ⬆️
instrumentations-instrumentation-mysql2 38.34% <ø> (-0.03%) ⬇️
instrumentations-instrumentation-passport 44.46% <ø> (+3.59%) ⬆️
instrumentations-instrumentation-passport-http 44.11% <ø> (+3.27%) ⬆️
instrumentations-instrumentation-passport-local 44.67% <ø> (+3.83%) ⬆️
instrumentations-instrumentation-pg 37.86% <ø> (-0.03%) ⬇️
instrumentations-instrumentation-promise 32.28% <ø> (+<0.01%) ⬆️
instrumentations-instrumentation-promise-js 32.29% <ø> (+<0.01%) ⬆️
instrumentations-instrumentation-q 32.33% <ø> (+<0.01%) ⬆️
instrumentations-instrumentation-url 32.25% <ø> (+<0.01%) ⬆️
instrumentations-instrumentation-when 32.30% <ø> (+<0.01%) ⬆️
llmobs-ai 41.48% <ø> (-0.03%) ⬇️
llmobs-anthropic 40.67% <ø> (-0.06%) ⬇️
llmobs-bedrock 39.55% <ø> (-0.05%) ⬇️
llmobs-google-genai 40.15% <ø> (-0.05%) ⬇️
llmobs-langchain 39.70% <ø> (-0.04%) ⬇️
llmobs-openai 44.52% <ø> (-0.06%) ⬇️
llmobs-vertex-ai 40.39% <ø> (-0.04%) ⬇️
platform-core 29.71% <ø> (+1.62%) ⬆️
platform-esbuild 32.89% <ø> (+1.40%) ⬆️
platform-instrumentations-misc 40.53% <ø> (+0.91%) ⬆️
platform-shimmer 36.14% <ø> (+1.31%) ⬆️
platform-unit-guardrails 31.27% <ø> (+0.89%) ⬆️
plugins-azure-event-hubs 24.02% <ø> (+1.38%) ⬆️
plugins-azure-service-bus 23.42% <ø> (+1.34%) ⬆️
plugins-bullmq 43.71% <ø> (+0.03%) ⬆️
plugins-cassandra 38.08% <ø> (-0.06%) ⬇️
plugins-cookie 25.08% <ø> (+1.38%) ⬆️
plugins-cookie-parser 24.87% <ø> (+1.37%) ⬆️
plugins-crypto 24.72% <ø> (+1.83%) ⬆️
plugins-dd-trace-api 38.50% <ø> (-0.03%) ⬇️
plugins-express-mongo-sanitize 25.04% <ø> (+1.36%) ⬆️
plugins-express-session 24.83% <ø> (+1.37%) ⬆️
plugins-fastify 42.59% <ø> (-0.04%) ⬇️
plugins-fetch 38.64% <ø> (-0.06%) ⬇️
plugins-fs 38.75% <ø> (-0.03%) ⬇️
plugins-generic-pool 24.06% <ø> (+1.38%) ⬆️
plugins-google-cloud-pubsub 45.80% <ø> (-0.03%) ⬇️
plugins-grpc 41.33% <ø> (-0.06%) ⬇️
plugins-handlebars 25.08% <ø> (+1.36%) ⬆️
plugins-hapi 40.49% <ø> (-0.04%) ⬇️
plugins-hono 40.76% <ø> (+0.03%) ⬆️
plugins-ioredis 38.55% <ø> (-0.03%) ⬇️
plugins-knex 24.80% <ø> (+1.29%) ⬆️
plugins-ldapjs 22.61% <ø> (+1.33%) ⬆️
plugins-light-my-request 24.48% <ø> (+1.33%) ⬆️
plugins-limitd-client 32.65% <ø> (+<0.01%) ⬆️
plugins-lodash 24.13% <ø> (+1.39%) ⬆️
plugins-mariadb 39.68% <ø> (-0.03%) ⬇️
plugins-memcached 38.28% <ø> (-0.03%) ⬇️
plugins-microgateway-core 39.51% <ø> (-0.04%) ⬇️
plugins-moleculer 40.88% <ø> (-0.06%) ⬇️
plugins-mongodb 39.60% <ø> (-0.06%) ⬇️
plugins-mongodb-core 39.20% <ø> (-0.03%) ⬇️
plugins-mongoose 39.22% <ø> (-0.06%) ⬇️
plugins-multer 24.83% <ø> (+1.37%) ⬆️
plugins-mysql 39.30% <ø> (-0.03%) ⬇️
plugins-mysql2 39.38% <ø> (-0.03%) ⬇️
plugins-node-serialize 25.12% <ø> (+1.38%) ⬆️
plugins-opensearch 37.92% <ø> (-0.06%) ⬇️
plugins-passport-http 24.91% <ø> (+1.35%) ⬆️
plugins-postgres 35.83% <ø> (+0.03%) ⬆️
plugins-process 24.72% <ø> (+1.83%) ⬆️
plugins-pug 25.08% <ø> (+1.38%) ⬆️
plugins-redis 39.03% <ø> (+0.13%) ⬆️
plugins-router 43.36% <ø> (+0.02%) ⬆️
plugins-sequelize 23.66% <ø> (+1.38%) ⬆️
plugins-test-and-upstream-amqp10 38.62% <ø> (-0.03%) ⬇️
plugins-test-and-upstream-amqplib 43.97% <ø> (-0.03%) ⬇️
plugins-test-and-upstream-apollo 39.34% <ø> (-0.08%) ⬇️
plugins-test-and-upstream-avsc 38.91% <ø> (-0.01%) ⬇️
plugins-test-and-upstream-bunyan 33.96% <ø> (-0.01%) ⬇️
plugins-test-and-upstream-connect 41.17% <ø> (+0.03%) ⬆️
plugins-test-and-upstream-graphql 40.30% <ø> (-0.03%) ⬇️
plugins-test-and-upstream-koa 40.76% <ø> (-0.03%) ⬇️
plugins-test-and-upstream-protobufjs 39.14% <ø> (-0.01%) ⬇️
plugins-test-and-upstream-rhea 44.22% <ø> (-0.06%) ⬇️
plugins-undici 39.44% <ø> (-0.06%) ⬇️
plugins-url 24.72% <ø> (+1.83%) ⬆️
plugins-valkey 38.17% <ø> (-0.03%) ⬇️
plugins-vm 24.72% <ø> (+1.83%) ⬆️
plugins-winston 34.34% <ø> (-0.03%) ⬇️
plugins-ws 42.25% <ø> (+1.39%) ⬆️
profiling-macos 40.07% <ø> (-0.10%) ⬇️
profiling-ubuntu 40.19% <ø> (-0.02%) ⬇️
profiling-windows 41.45% <ø> (-0.12%) ⬇️
serverless-azure-functions-client 23.75% <ø> (+1.37%) ⬆️
serverless-azure-functions-eventhubs 23.75% <ø> (+1.37%) ⬆️
serverless-azure-functions-servicebus 23.75% <ø> (+1.37%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@pr-commenter
Copy link
Copy Markdown

pr-commenter bot commented Feb 5, 2026

Benchmarks

Benchmark execution time: 2026-02-10 18:49:29

Comparing candidate commit b4f3039 in PR branch joey/fix-lambda-authorizer-context-extraction with baseline commit d5e899b in branch master.

Found 0 performance improvements and 0 performance regressions! Performance is the same for 231 metrics, 29 unstable metrics.

purple4reina
purple4reina previously approved these changes Feb 6, 2026
@datadog-datadog-prod-us1

This comment has been minimized.

@purple4reina purple4reina marked this pull request as ready for review February 6, 2026 21:01
@purple4reina purple4reina requested a review from a team as a code owner February 6, 2026 21:01
}
let context = args.length > 1 ? args[1] : null
if (context === null || context.getRemainingTimeInMillis === undefined) {
context = args.length > 2 ? args[2] : null
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.

I think we missed the second check where we ensure that the second context has the things we care about? Does it matter?

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.

I believe you are correct. Means there's a hole in our testing too. I'll fix.

duncanista
duncanista previously approved these changes Feb 6, 2026
duncanista
duncanista previously approved these changes Feb 6, 2026
@purple4reina purple4reina changed the title fix(lambda): handle missing context for Lambda Authorizers fix(lambda): handle missing context for some lambda functions\ Feb 6, 2026
@purple4reina purple4reina changed the title fix(lambda): handle missing context for some lambda functions\ fix(lambda): handle missing context for some lambda functions Feb 6, 2026
@purple4reina purple4reina requested a review from a team as a code owner February 9, 2026 17:02
@purple4reina purple4reina force-pushed the joey/fix-lambda-authorizer-context-extraction branch from 7188456 to 77cfede Compare February 9, 2026 21:13
Copy link
Copy Markdown
Member

@BridgeAR BridgeAR left a comment

Choose a reason for hiding this comment

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

The logic change is LGTM. Our linter is just unhappy 😅

I would be nice to abstract the tests in index.spec.js further instead of adding the context.spec.js tests.

Comment on lines +320 to +326
try {
await datadog(app.authorizerErrorHandler)(_event)
assert.fail('Expected error to be thrown')
} catch (e) {
assert.strictEqual(e.name, 'AuthorizationError')
assert.strictEqual(e.message, 'Unauthorized')
}
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.

Suggested change
try {
await datadog(app.authorizerErrorHandler)(_event)
assert.fail('Expected error to be thrown')
} catch (e) {
assert.strictEqual(e.name, 'AuthorizationError')
assert.strictEqual(e.message, 'Unauthorized')
}
await assert.rejects(
datadog(app.authorizerErrorHandler)(_event),
{ name: 'AuthorizationError', message: 'Unauthorized' }
)

Comment on lines +329 to +336
const checkTraces = agent.assertSomeTraces((_traces) => {
const traces = _traces[0]
assert.strictEqual(traces.length, 1)
traces.forEach((trace) => {
assert.strictEqual(trace.error, 1)
})
})
await checkTraces
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.

Nit

Suggested change
const checkTraces = agent.assertSomeTraces((_traces) => {
const traces = _traces[0]
assert.strictEqual(traces.length, 1)
traces.forEach((trace) => {
assert.strictEqual(trace.error, 1)
})
})
await checkTraces
await agent.assertSomeTraces(([traces]) => {
assert.strictEqual(traces.length, 1)
assert.strictEqual(traces[0].error, 1)
})

@@ -0,0 +1,40 @@
const assert = require('node:assert/strict')
const { afterEach, beforeEach, describe, it } = require('mocha')
const { extractContext } = require('../../src/lambda/context')
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.

I understand that this creates a higher coverage for the particular internal method.

If I could choose, I would just rather always solely test public APIs or entry points as we do with the other tests. That way it is easier to refactor internals without having to change tests as well as having a stronger safe guard how the user would ever reach such state. Testing internal methods could at some point not be used anymore while still showing full coverage by being tested directly.

Comment on lines +304 to +317
// Set the desired handler to patch
process.env.DD_LAMBDA_HANDLER = 'handler.authorizerErrorHandler'
// Load the agent and re-register hook for patching.
await loadAgent()

const _event = {
type: 'REQUEST',
methodArn: 'arn:aws:execute-api:us-east-1:123456789012:api-id/stage/GET/resource',
}

// Mock `datadog-lambda` handler resolve and import.
const _handlerPath = path.resolve(__dirname, './fixtures/handler.js')
const app = require(_handlerPath)
datadog = require('./fixtures/datadog-lambda')
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.

These lines are identical in all tests new created tests here besides for the environment variable. What about abstracting the tests here to something like:

const tests = [{ name: 'should do foo', env: 'FOO', error: 1, fn() { ... } }, ...]

for (const test of tests) {
  it(test.name, async () => {
    process.env.DD_LAMBDA_HANDLER = test.env

    await loadAgent()
    ...
    const assertionPromise = agent.assertSomeTraces(([traces]) => {
      assert.strictEqual(traces.length, 1)
      assert.strictEqual(traces[0].error, test.error)
    })
    await Promise.all([fn(), assertionPromise])
  })
}

That way creating new test cases is not a lot of code and we could likely add enough test cases here instead of using the new context.spec.js tests.

@BridgeAR BridgeAR marked this pull request as draft February 10, 2026 11:28
@purple4reina purple4reina marked this pull request as ready for review February 10, 2026 17:51
@purple4reina purple4reina merged commit 48c7ce4 into master Feb 10, 2026
791 checks passed
@purple4reina purple4reina deleted the joey/fix-lambda-authorizer-context-extraction branch February 10, 2026 19:30
@dd-octo-sts dd-octo-sts bot mentioned this pull request Feb 10, 2026
dd-octo-sts bot pushed a commit that referenced this pull request Feb 10, 2026
* fix(lambda): handle missing context for Lambda Authorizers

Lambda Authorizers and some other Lambda handler types do not receive
a context object - they only receive an event parameter. Previously,
the extractContext() function would throw "Could not extract context"
when it couldn't find a context object with getRemainingTimeInMillis.

This change makes extractContext() return undefined instead of throwing,
and updates the datadog() wrapper to skip timeout checking when context
is not available. This allows Lambda Authorizers to be instrumented
without crashing.

Fixes: DataDog/datadog-lambda-js#721

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* Undefined cleanup.

* Add getRemainingTimeInMillis check back.

* Update packages/dd-trace/src/lambda/handler.js

Co-authored-by: Ruben Bridgewater <[email protected]>

* Move extractContext to separate file and add more tesets.

* Linting.

---------

Co-authored-by: Claude Opus 4.5 <[email protected]>
Co-authored-by: Rey Abolofia <[email protected]>
Co-authored-by: Rey Abolofia <[email protected]>
Co-authored-by: Ruben Bridgewater <[email protected]>
juan-fernandez pushed a commit that referenced this pull request Feb 12, 2026
* fix(lambda): handle missing context for Lambda Authorizers

Lambda Authorizers and some other Lambda handler types do not receive
a context object - they only receive an event parameter. Previously,
the extractContext() function would throw "Could not extract context"
when it couldn't find a context object with getRemainingTimeInMillis.

This change makes extractContext() return undefined instead of throwing,
and updates the datadog() wrapper to skip timeout checking when context
is not available. This allows Lambda Authorizers to be instrumented
without crashing.

Fixes: DataDog/datadog-lambda-js#721

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* Undefined cleanup.

* Add getRemainingTimeInMillis check back.

* Update packages/dd-trace/src/lambda/handler.js

Co-authored-by: Ruben Bridgewater <[email protected]>

* Move extractContext to separate file and add more tesets.

* Linting.

---------

Co-authored-by: Claude Opus 4.5 <[email protected]>
Co-authored-by: Rey Abolofia <[email protected]>
Co-authored-by: Rey Abolofia <[email protected]>
Co-authored-by: Ruben Bridgewater <[email protected]>
BridgeAR added a commit that referenced this pull request Feb 22, 2026
* fix(lambda): handle missing context for Lambda Authorizers

Lambda Authorizers and some other Lambda handler types do not receive
a context object - they only receive an event parameter. Previously,
the extractContext() function would throw "Could not extract context"
when it couldn't find a context object with getRemainingTimeInMillis.

This change makes extractContext() return undefined instead of throwing,
and updates the datadog() wrapper to skip timeout checking when context
is not available. This allows Lambda Authorizers to be instrumented
without crashing.

Fixes: DataDog/datadog-lambda-js#721

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* Undefined cleanup.

* Add getRemainingTimeInMillis check back.

* Update packages/dd-trace/src/lambda/handler.js

Co-authored-by: Ruben Bridgewater <[email protected]>

* Move extractContext to separate file and add more tesets.

* Linting.

---------

Co-authored-by: Claude Opus 4.5 <[email protected]>
Co-authored-by: Rey Abolofia <[email protected]>
Co-authored-by: Rey Abolofia <[email protected]>
Co-authored-by: Ruben Bridgewater <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG]: Instrumented Lambda Authorizer throws "Error: Could not extract context"

4 participants