Skip to content

feat(lambda-worker): Support Temporal creds config via Secrets Manager - #2715

Open
johanngan wants to merge 5 commits into
mainfrom
johanngan/aws-secrets-manager
Open

johanngan wants to merge 5 commits into
mainfrom
johanngan/aws-secrets-manager

Conversation

@johanngan

@johanngan johanngan commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

What was changed

The new @temporalio/aws-secrets-manager package defines a new envconfig extension to support Temporal client credentials stored in AWS Secrets Manager. The user specifies a secret ARN or friendly name via envconfig (TOML or environment variables), and the client will automatically fetch the secret material from Secrets Manager. Periodic refreshes are only supported for API keys for now, with TLS cert rotation support deferred to later since there's no easy way to do it right now.

The AWS Parameters and Secrets Lambda Extension is used if detected in the environment. Otherwise, secrets are retrieved directly from Secrets Manager.

See the README or package documentation for usage details.

The Lambda worker contrib package now uses the secretsmanager envconfig extension to support Temporal credentials in AWS Secrets Manager within Lambda workers.

Also see the Go reference implementation:

Why?

The aws-secrets-manager extension is intended to be used with the Lambda worker contrib package (and in the future other serverless providers), to make it more convenient to store worker secrets in a secrets manager when using serverless. This makes it more convenient to store worker secrets in a secrets manager when using serverless.

Checklist

  1. How was this tested:
    Added new unit tests. Also did Claude-assisted E2E verification with a serverless Lambda worker setup configured to read credentials from Secrets Manager (under multiple configurations, including with/without the Lambda extension fetcher, with/without TLS client cert bundling, and using TOML/env vars).

  2. Any docs updates needed?
    The associated in-repo docs are updated. This specific module is primarily an implementation detail for the Lambda worker integration with Secrets Manager. We'll probably want to update our public docs for Lambda workers, but that can be done later. We may also want to update the associated sample code in samples-typescript to at least mention this integration as an option.

@johanngan
johanngan added this pull request to stack #2716 November 18, 2026 23:21
@johanngan
johanngan requested a review from a team as a code owner November 18, 2026 23:21
@johanngan johanngan changed the title Johanngan/aws secrets manager feat(lambdaworker): Support Temporal creds config via Secrets Manager Nov 18, 2026
@johanngan johanngan changed the title feat(lambdaworker): Support Temporal creds config via Secrets Manager feat(lambda-worker): Support Temporal creds config via Secrets Manager Nov 18, 2026
Base automatically changed from johanngan/plugin-connect-hooks to main November 19, 2026 13:58
johanngan and others added 2 commits November 19, 2026 07:58
Add the experimental @temporalio/aws-secrets-manager package, an envconfig
extension that loads the client API key and mTLS material from AWS Secrets
Manager secret IDs, configured in TOML or with TEMPORAL_EXT_AWS_SECRETS_MANAGER_*
env vars. It ports the Go and Python implementations, with the same config,
validation, metric names and log messages.

Secrets are fetched through the AWS Parameters and Secrets Lambda Extension when
it's detected, and otherwise with @aws-sdk/client-secrets-manager, an optional
peer dependency that's only loaded when needed. Fetched secrets are cached by
the plugin, refreshed every refresh interval (SECRETS_MANAGER_TTL, default 5
minutes), and fall back to the previous value for up to 24 hours if a refresh
fails.

The plugin uses the new connect and connectNative hooks to fetch secrets before
connecting, so Connection.lazy isn't supported. A NativeConnection's API key is
refreshed in the background until the connection is closed, and a Connection's
API key callback refreshes it when it's due. A client cert and key that don't
match are treated as a failed fetch, like in Go.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The Lambda worker now always loads its client config with the AWS Secrets
Manager extension, so credentials can be configured as secret IDs with
TEMPORAL_EXT_AWS_SECRETS_MANAGER_* env vars or in temporal.toml. The extension
only adds a plugin when secret IDs are configured. The AWS SDK it uses when the
Lambda extension isn't present is included in the Lambda Node.js runtimes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@johanngan
johanngan force-pushed the johanngan/aws-secrets-manager branch from cf26e69 to 98fa976 Compare November 19, 2026 13:58
@johanngan

johanngan commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor Author

Note to maintainers: this will require publishing the new @temporalio/aws-secrets-manager package to npm on the next release. It should be built automatically by the release scripts, but AFAICT the publication itself is a manual step

Comment on lines +264 to +270
const entry = this.cache.apiKey;
if (entry !== undefined) {
// Connection calls this before each request. It returns the cached key right away, and starts
// fetching it again in the background when due, so a rotated key is picked up without
// reconnecting, and requests never wait on Secrets Manager.
resolved.apiKey = () => this.cache.getNow(entry, this.minRefreshIntervalMs, tel);
}

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.

getNow() does not check staleness, which means it can return a stale key.

import assert from 'node:assert/strict';
import { GetSecretValueCommand } from '@aws-sdk/client-secrets-manager';
import { EXTENSION_NAME, SecretsManagerExtension } from './src/extension';

const INITIAL_KEY = 'initial-key';
const MAX_STALENESS_MS = 100;

class FakeSecretsManager {
  calls = 0;
  failure?: Error;

  readonly client = {
    send: async (command: unknown) => {
      assert.ok(command instanceof GetSecretValueCommand);
      this.calls++;
      if (this.failure) throw this.failure;
      return { SecretString: INITIAL_KEY, VersionId: 'v1' };
    },
  };
}

async function waitUntil(condition: () => boolean): Promise<void> {
  for (let i = 0; i < 100; i++) {
    if (condition()) return;
    await new Promise((resolve) => setTimeout(resolve, 1));
  }
  throw new Error('background refresh did not finish');
}

async function main(): Promise<void> {
  const secrets = new FakeSecretsManager();
  const extension = new SecretsManagerExtension({
    secretsClient: secrets.client as any,
    refreshInterval: 0,
    maxStaleness: MAX_STALENESS_MS,
  });
  const plugin = extension.clientPlugin({
    profile: { ext: { [EXTENSION_NAME]: { api_key_id: 'api-key-id' } } },
    env: {},
  } as any) as any;
  plugin.minRefreshIntervalMs = 1;

  const cache = plugin.cache;
  let now = 1_000;
  cache.now = () => now;
  let connectedOptions: any;
  await plugin.connect({}, async (options: any) => {
    connectedOptions = options;
    return {};
  });

  const apiKey = connectedOptions.apiKey as () => string;
  assert.equal(apiKey(), INITIAL_KEY, 'the plugin must initially install the successfully fetched key');
  assert.equal(secrets.calls, 1);

  secrets.failure = new Error('simulated Secrets Manager outage');
  now += MAX_STALENESS_MS + 1;
  assert.ok(
    now - cache.apiKey.fetchedAt > cache.maxStalenessMs,
    'the cached key must be older than maxStaleness'
  );

  apiKey(); // starts the supplier's nonblocking refresh
  await waitUntil(() => cache.apiKey.inFlight === undefined);
  assert.equal(secrets.calls, 2, 'the supplier must attempt a refresh');
  assert.ok(cache.apiKey.failedAt !== undefined, 'the refresh must have failed');

  console.log({
    path: 'Connection API-key supplier',
    initiallyValid: INITIAL_KEY,
    ageMs: now - cache.apiKey.fetchedAt,
    maxStalenessMs: cache.maxStalenessMs,
    fetchCalls: secrets.calls,
    refreshFailed: cache.apiKey.failedAt !== undefined,
    suppliedAfterFailure: apiKey(),
  });
  assert.notEqual(
    apiKey(),
    INITIAL_KEY,
    'Connection must stop supplying an API key after maxStaleness when refresh fails'
  );
}

void main();

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This one has a subtlety if we haven't tried to refresh since expiration, since the callback itself triggers refreshes and we can't easily wait for the next refresh within the callback. So even in a healthy environment, strictly refusing to return a stale value could mean returning an empty value on the first request after a long idle period.

I changed it so that it'll still return a stale value if no refresh has actually failed yet. That way if an idle connection wakes up it at least has the stale value as a bridge while the next refresh gets kicked off.

- Stop using an API key once no value has been fetched within the max
  staleness, instead of using the stale key indefinitely. Connection
  sends no Authorization header until a refresh succeeds, and
  NativeConnection's key is set to an empty one, since it can't be unset.
  The removal is logged with the fetch error that caused it.
- Connection's per-request key lookup can't wait for a fetch, so it keeps
  returning an expired key until a refresh attempted after it expired
  fails. Otherwise requests would go without a key while a healthy
  refresh is in progress, e.g. the first request after being idle for
  longer than the max staleness.
- Treat unexpected errors refreshing a NativeConnection's API key the same
  way, logging them, and never let the refresh loop stop or reject
  unhandled.
- Record a non-SecretFetchError fetch failure as a failed fetch, rather
  than caching it as the value.
- Reject a non-finite refreshInterval, which made every lookup fetch.
- Raise the Lambda extension probe timeout, since the timeout runs on the
  event loop, which may be busy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
johanngan and others added 2 commits November 20, 2026 17:31
The READMEs said the Lambda Node.js runtime's copy of the AWS SDK is used
if @aws-sdk/client-secrets-manager isn't installed. The runtime provides it
through NODE_PATH, which the dynamic import used to load the SDK doesn't
search, so this may not work. Its version isn't pinned either, so just
require installing the package.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…fault

Only an unset max staleness uses the 24 hour default. Previously 0 also
did, as in Go, where a zero duration means unset. Here unset is already
distinct, so 0 now means no tolerance for stale values beyond the refresh
interval, rather than the most permissive setting, and a negative value is
rejected like a negative refresh interval.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants