Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

feat(amazon-bedrock): connect with temporary credentials from SSO or STS (#15746)

Hazem Adelb4fae529baf3
diff --git a/brain/knowledge/pieces-engine/building-pieces.md b/brain/knowledge/pieces-engine/building-pieces.md
index 08a842fedd4..bf63daa45b0 100644
--- a/brain/knowledge/pieces-engine/building-pieces.md
+++ b/brain/knowledge/pieces-engine/building-pieces.md
@@ -45,6 +45,8 @@ Authentication, triggers (polling/webhook), properties + validation, flow contro
- **`formatPieceError` runs *inside* the engine's error handler, so anything it throws replaces a real user error with an engine crash.** Two inputs used to do exactly that, both verified: a **cyclic** error body blew `collectMessage`'s recursion with `RangeError: Maximum call stack size exceeded` (a cycle through any of `message`/`detail`/`description`/`reason`/`error`, or a self-referencing array — and a 100-wide cycle made it exponential), and a cyclic `responseBody`/`requestBody` survived extraction only to die at the `JSON.stringify(formatPieceError(...))` every call site wraps it in, with `TypeError: Converting circular structure to JSON`. The second needs no deep cycle at all — a `self` key the extractor never walks is enough. Where that lands is the nasty part: `operations/index.ts` is the outermost handler, so a throw there escapes with no response and the worker just sees an RPC timeout. Both are now bounded — `collectMessageFrom` and `rebuildSerializable` each carry a depth cap plus a visited `WeakSet`. **Sanitize by probing with `JSON.stringify`, never by hand-rolling a walk over every body.** The first attempt here deep-copied unconditionally and silently downgraded exactly the values `JSON.stringify` gets right: `Date` became `{}` instead of an ISO string, `Buffer` became `{"0":104}` instead of `{type,data}`, a custom `toJSON` was ignored, and an own `function` property was promoted to **its source text** where stringify had correctly dropped it. `toSerializable` now tries `JSON.stringify` first and returns the original reference **untouched** when it succeeds, so the common path is byte-identical and uncopied; only a value that actually throws gets the bounded rebuild (cycles become `[Circular]`), and that rebuild is itself wrapped in a `tryCatchSync` that falls back to `[Unserializable]`, because `Object.entries` runs getters and a body with a throwing getter would otherwise escape the guard entirely. Worth knowing that `formatPieceError` output shares references with the caller's error object, and that `ai-provider-health.ts` reads `responseBody` and stringifies it itself — so a copy there is not free. Two consequences to know: a **shared** (non-cyclic) reference is collected once rather than twice, which is free for `JSON.parse`-derived bodies since they never share refs but is a real fidelity loss for live SDK error objects; and the `isFriendlyPieceError` passthrough is *not* re-sanitized, on the contract that such a payload already came from a JSON string. Rule of thumb: this file may return a worse message, never throw.
+- **A piece's `build` compiles its `src/**/*.test.ts`, so a type error in a test breaks the piece build while `vitest` stays green.** `npm run build` is `tsc -p tsconfig.lib.json`, whose `include` is `src/**/*.ts` with no test exclusion, while vitest runs through esbuild and strips types without checking them. So a test that passes locally can still fail CI at `<piece>#build`, and it takes `validate-publishable-packages` down with it. Run the piece's own `npm run build`, not just its tests, after adding one. Two shapes that bite: `ServerContext` (`{apiUrl, publicUrl, token}`) and `AuthValidationServerContext` (the same minus `token`, plus `mintOidcToken`) are not interchangeable, and `StaticPropsValue` requires *every* prop key to be present, including optional ones — pass `sessionToken: undefined` rather than omitting it.
+
## Sharing & misc
- **Sharing** — contribute to community, publish a community piece, or keep it private.
- **Misc** — build/bundle/publish piece, pieces CI/CD, migrate nx→turbo, migrate pieces to bundles, private fork, testing pieces, dev container, Codespaces, create a new AI provider.
diff --git a/bun.lock b/bun.lock
index a1b5c651dda..66ce7146216 100644
--- a/bun.lock
+++ b/bun.lock
@@ -518,7 +518,7 @@
},
"packages/pieces/community/amazon-bedrock": {
"name": "@activepieces/piece-amazon-bedrock",
- "version": "0.3.0",
+ "version": "0.4.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
@@ -10390,6 +10390,7 @@
},
"devDependencies": {
"tslib": "2.6.2",
+ "vitest": "3.2.6",
},
},
"packages/pieces/core/file-helper": {
diff --git a/packages/pieces/community/amazon-bedrock/package.json b/packages/pieces/community/amazon-bedrock/package.json
index fa8f5ab88ba..1ae663f3892 100644
--- a/packages/pieces/community/amazon-bedrock/package.json
+++ b/packages/pieces/community/amazon-bedrock/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/piece-amazon-bedrock",
- "version": "0.3.0",
+ "version": "0.4.0",
"type": "commonjs",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
diff --git a/packages/pieces/community/amazon-bedrock/src/lib/access-key-auth.test.ts b/packages/pieces/community/amazon-bedrock/src/lib/access-key-auth.test.ts
new file mode 100644
index 00000000000..82351638684
--- /dev/null
+++ b/packages/pieces/community/amazon-bedrock/src/lib/access-key-auth.test.ts
@@ -0,0 +1,92 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const { bedrockClientMock, runtimeClientMock, sendMock } = vi.hoisted(() => ({
+ bedrockClientMock: vi.fn(),
+ runtimeClientMock: vi.fn(),
+ sendMock: vi.fn(),
+}));
+
+vi.mock('@aws-sdk/client-bedrock', () => ({
+ BedrockClient: bedrockClientMock.mockImplementation(() => ({ send: sendMock })),
+ ListFoundationModelsCommand: vi.fn((input: unknown) => ({ input })),
+ ListInferenceProfilesCommand: vi.fn((input: unknown) => ({ input })),
+ ModelModality: { TEXT: 'TEXT', IMAGE: 'IMAGE' },
+}));
+
+vi.mock('@aws-sdk/client-bedrock-runtime', () => ({
+ BedrockRuntimeClient: runtimeClientMock.mockImplementation(() => ({ send: sendMock })),
+ AudioFormat: {},
+ DocumentFormat: {},
+ ImageFormat: {},
+ VideoFormat: {},
+}));
+
+import { awsBedrockAuth } from './auth';
+import { createBedrockRuntimeClient } from './common';
+
+const accessKeyAuth = {
+ accessKeyId: 'ASIAEXAMPLE',
+ secretAccessKey: 'secret',
+ region: 'us-east-1',
+};
+
+const validationServer = {
+ apiUrl: 'http://127.0.0.1:4200/api/',
+ publicUrl: 'http://127.0.0.1:4200/api/',
+ mintOidcToken: vi.fn(),
+};
+
+const runtimeServer = {
+ apiUrl: 'http://127.0.0.1:4200/api/',
+ publicUrl: 'http://127.0.0.1:4200/api/',
+ token: 'token',
+};
+
+function credentialsOf(mock: typeof bedrockClientMock) {
+ return mock.mock.calls[0][0].credentials;
+}
+
+describe('aws bedrock access key auth', () => {
+ beforeEach(() => {
+ bedrockClientMock.mockClear();
+ runtimeClientMock.mockClear();
+ sendMock.mockReset();
+ sendMock.mockResolvedValue({ modelSummaries: [] });
+ });
+
+ it('signs validation with the session token, so temporary credentials are accepted', async () => {
+ const result = await awsBedrockAuth.validate?.({
+ auth: { ...accessKeyAuth, sessionToken: 'temporary' },
+ server: validationServer,
+ });
+
+ expect(result).toEqual({ valid: true });
+ expect(credentialsOf(bedrockClientMock)).toEqual({
+ accessKeyId: 'ASIAEXAMPLE',
+ secretAccessKey: 'secret',
+ sessionToken: 'temporary',
+ });
+ });
+
+ it('leaves the session token unset for a long-term access key', async () => {
+ await awsBedrockAuth.validate?.({
+ auth: { ...accessKeyAuth, sessionToken: undefined },
+ server: validationServer,
+ });
+
+ expect(credentialsOf(bedrockClientMock).sessionToken).toBeUndefined();
+ });
+
+ it('carries the session token into the runtime client that actions call', async () => {
+ await createBedrockRuntimeClient({
+ auth: { ...accessKeyAuth, sessionToken: 'temporary' },
+ server: runtimeServer,
+ });
+
+ expect(credentialsOf(runtimeClientMock)).toEqual({
+ accessKeyId: 'ASIAEXAMPLE',
+ secretAccessKey: 'secret',
+ sessionToken: 'temporary',
+ });
+ });
+});
diff --git a/packages/pieces/community/amazon-bedrock/src/lib/actions/custom-api-call.ts b/packages/pieces/community/amazon-bedrock/src/lib/actions/custom-api-call.ts
index 0513ffcf6ce..ea05d85caf2 100644
--- a/packages/pieces/community/amazon-bedrock/src/lib/actions/custom-api-call.ts
+++ b/packages/pieces/community/amazon-bedrock/src/lib/actions/custom-api-call.ts
@@ -148,7 +148,7 @@ export const customApiCall = createAction({
if (isOidcAuth(authProps)) {
creds = await getTemporaryCredentials({ auth: authProps, server: context.server });
} else {
- creds = { accessKeyId: authProps.accessKeyId, secretAccessKey: authProps.secretAccessKey };
+ creds = { accessKeyId: authProps.accessKeyId, secretAccessKey: authProps.secretAccessKey, sessionToken: authProps.sessionToken };
}
const baseUrl = `https://${service}.${region}.amazonaws.com`;
diff --git a/packages/pieces/community/amazon-bedrock/src/lib/auth.ts b/packages/pieces/community/amazon-bedrock/src/lib/auth.ts
index 732db27144b..03b63be01e1 100644
--- a/packages/pieces/community/amazon-bedrock/src/lib/auth.ts
+++ b/packages/pieces/community/amazon-bedrock/src/lib/auth.ts
@@ -80,6 +80,11 @@ export const awsBedrockAuth = PieceAuth.CustomAuth({
description: 'Your AWS secret access key. Only shown once when you create the access key — store it safely.',
required: true,
}),
+ sessionToken: PieceAuth.SecretText({
+ displayName: 'Session Token',
+ description: 'Only for temporary credentials from AWS SSO or STS. They expire.',
+ required: false,
+ }),
region: Property.StaticDropdown({
displayName: 'Region',
required: true,
@@ -91,7 +96,7 @@ export const awsBedrockAuth = PieceAuth.CustomAuth({
validate: async ({ auth }) => {
try {
const client = new BedrockClient({
- credentials: { accessKeyId: auth.accessKeyId, secretAccessKey: auth.secretAccessKey },
+ credentials: { accessKeyId: auth.accessKeyId, secretAccessKey: auth.secretAccessKey, sessionToken: auth.sessionToken },
region: auth.region,
});
await client.send(new ListFoundationModelsCommand({}));
@@ -154,6 +159,7 @@ export const awsBedrockCombinedAuth = [awsBedrockAuth, awsBedrockOidcAuth];
export type BedrockAccessKeyAuthProps = {
accessKeyId: string;
secretAccessKey: string;
+ sessionToken?: string;
region: string;
};
diff --git a/packages/pieces/community/amazon-bedrock/src/lib/common.ts b/packages/pieces/community/amazon-bedrock/src/lib/common.ts
index 0f9363931cf..a6890965771 100644
--- a/packages/pieces/community/amazon-bedrock/src/lib/common.ts
+++ b/packages/pieces/community/amazon-bedrock/src/lib/common.ts
@@ -31,7 +31,7 @@ export async function createBedrockRuntimeClient({
return new BedrockRuntimeClient({ credentials, region: auth.region, ...BEDROCK_CLIENT_TIMEOUTS });
}
return new BedrockRuntimeClient({
- credentials: { accessKeyId: auth.accessKeyId, secretAccessKey: auth.secretAccessKey },
+ credentials: { accessKeyId: auth.accessKeyId, secretAccessKey: auth.secretAccessKey, sessionToken: auth.sessionToken },
region: auth.region,
...BEDROCK_CLIENT_TIMEOUTS,
});
@@ -65,7 +65,7 @@ export async function getBedrockModelOptions(
client = new BedrockClient({ credentials, region: auth.region, ...BEDROCK_CLIENT_TIMEOUTS });
} else {
client = new BedrockClient({
- credentials: { accessKeyId: auth.accessKeyId, secretAccessKey: auth.secretAccessKey },
+ credentials: { accessKeyId: auth.accessKeyId, secretAccessKey: auth.secretAccessKey, sessionToken: auth.sessionToken },
region: auth.region,
...BEDROCK_CLIENT_TIMEOUTS,
});