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-textract): connect AWS Textract with an IAM Role instead of access keys (#16555)

Bartosz Majewski7423f95f4fb7
diff --git a/bun.lock b/bun.lock
index 6b62b128ce2..73b5fd4e648 100644
--- a/bun.lock
+++ b/bun.lock
@@ -631,16 +631,18 @@
},
"packages/pieces/community/amazon-textract": {
"name": "@activepieces/piece-amazon-textract",
- "version": "0.3.10",
+ "version": "0.4.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
+ "@aws-sdk/client-sts": "3.974.0",
"@aws-sdk/client-textract": "^3.0.0",
},
"devDependencies": {
"tslib": "^2.3.0",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/aminos": {
diff --git a/packages/pieces/community/amazon-textract/package.json b/packages/pieces/community/amazon-textract/package.json
index ea03e9bccca..6db5c96bd20 100644
--- a/packages/pieces/community/amazon-textract/package.json
+++ b/packages/pieces/community/amazon-textract/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/piece-amazon-textract",
- "version": "0.3.10",
+ "version": "0.4.0",
"type": "commonjs",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
@@ -9,14 +9,17 @@
"@activepieces/pieces-framework": "workspace:*",
"@aws-sdk/client-textract": "^3.0.0",
"@activepieces/core-piece-types": "workspace:*",
- "@activepieces/core-utils": "workspace:*"
+ "@activepieces/core-utils": "workspace:*",
+ "@aws-sdk/client-sts": "3.974.0"
},
"devDependencies": {
- "tslib": "^2.3.0"
+ "tslib": "^2.3.0",
+ "vitest": "3.2.6"
},
"scripts": {
"build": "tsc -p tsconfig.lib.json && cp package.json dist/",
"bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",
- "lint": "eslint 'src/**/*.ts'"
+ "lint": "eslint 'src/**/*.ts'",
+ "test": "vitest run"
}
}
diff --git a/packages/pieces/community/amazon-textract/src/index.ts b/packages/pieces/community/amazon-textract/src/index.ts
index 04ebad9b09b..ebace0054fe 100644
--- a/packages/pieces/community/amazon-textract/src/index.ts
+++ b/packages/pieces/community/amazon-textract/src/index.ts
@@ -12,7 +12,7 @@ export const amazonTextract = createPiece({
description:
'Extract text, forms, tables, signatures, and structured data from documents using AWS Textract.',
logoUrl: 'https://cdn.activepieces.com/pieces/amazon-textract.png',
- minimumSupportedRelease: '0.30.0',
+ minimumSupportedRelease: '0.90.1',
authors: ["AhmadTash"],
categories: [PieceCategory.DEVELOPER_TOOLS],
auth: amazonTextractAuth,
diff --git a/packages/pieces/community/amazon-textract/src/lib/actions/analyze-document-async.ts b/packages/pieces/community/amazon-textract/src/lib/actions/analyze-document-async.ts
index 6ff4b311d34..b3472c6bbdf 100644
--- a/packages/pieces/community/amazon-textract/src/lib/actions/analyze-document-async.ts
+++ b/packages/pieces/community/amazon-textract/src/lib/actions/analyze-document-async.ts
@@ -62,7 +62,7 @@ export const analyzeDocumentAsync = createAction({
const { s3Bucket, s3Key, featureTypes, queries, clientRequestToken } = context.propsValue;
try {
- const client = createTextractClient(context.auth.props);
+ const client = await createTextractClient({ auth: context.auth.props, server: context.server });
const resolvedFeatureTypes: FeatureType[] = [...(featureTypes as FeatureType[])];
const startInput: ConstructorParameters<typeof StartDocumentAnalysisCommand>[0] = {
diff --git a/packages/pieces/community/amazon-textract/src/lib/actions/analyze-document.ts b/packages/pieces/community/amazon-textract/src/lib/actions/analyze-document.ts
index d5510681388..88354d535f3 100644
--- a/packages/pieces/community/amazon-textract/src/lib/actions/analyze-document.ts
+++ b/packages/pieces/community/amazon-textract/src/lib/actions/analyze-document.ts
@@ -90,7 +90,7 @@ export const analyzeDocument = createAction({
const s3Key = source === 's3' ? (document['s3Key'] as string) : undefined;
try {
- const client = createTextractClient(context.auth.props);
+ const client = await createTextractClient({ auth: context.auth.props, server: context.server });
const documentInput = buildDocumentInput(file, s3Bucket, s3Key);
// Always strip QUERIES from dropdown value — it requires QueriesConfig
diff --git a/packages/pieces/community/amazon-textract/src/lib/actions/analyze-expense.ts b/packages/pieces/community/amazon-textract/src/lib/actions/analyze-expense.ts
index 52ab80547e4..8b5fd5e608d 100644
--- a/packages/pieces/community/amazon-textract/src/lib/actions/analyze-expense.ts
+++ b/packages/pieces/community/amazon-textract/src/lib/actions/analyze-expense.ts
@@ -68,7 +68,7 @@ export const analyzeExpense = createAction({
const s3Key = source === 's3' ? (document['s3Key'] as string) : undefined;
try {
- const client = createTextractClient(context.auth.props);
+ const client = await createTextractClient({ auth: context.auth.props, server: context.server });
const documentInput = buildDocumentInput(file, s3Bucket, s3Key);
const response = await client.send(new AnalyzeExpenseCommand({ Document: documentInput }));
return parseExpenseDocuments(response.ExpenseDocuments ?? []);
diff --git a/packages/pieces/community/amazon-textract/src/lib/actions/analyze-id.ts b/packages/pieces/community/amazon-textract/src/lib/actions/analyze-id.ts
index a3fc62c56a1..806ac93dadb 100644
--- a/packages/pieces/community/amazon-textract/src/lib/actions/analyze-id.ts
+++ b/packages/pieces/community/amazon-textract/src/lib/actions/analyze-id.ts
@@ -68,7 +68,7 @@ export const analyzeId = createAction({
const s3Key = source === 's3' ? (document['s3Key'] as string) : undefined;
try {
- const client = createTextractClient(context.auth.props);
+ const client = await createTextractClient({ auth: context.auth.props, server: context.server });
const documentInput = buildDocumentInput(file, s3Bucket, s3Key);
const response = await client.send(new AnalyzeIDCommand({ DocumentPages: [documentInput] }));
return parseIdentityDocuments(response.IdentityDocuments ?? []);
diff --git a/packages/pieces/community/amazon-textract/src/lib/actions/detect-document-text.ts b/packages/pieces/community/amazon-textract/src/lib/actions/detect-document-text.ts
index bd38d88c6f4..9c6dea059ce 100644
--- a/packages/pieces/community/amazon-textract/src/lib/actions/detect-document-text.ts
+++ b/packages/pieces/community/amazon-textract/src/lib/actions/detect-document-text.ts
@@ -70,7 +70,7 @@ export const detectDocumentText = createAction({
const s3Key = source === 's3' ? (document['s3Key'] as string) : undefined;
try {
- const client = createTextractClient(context.auth.props);
+ const client = await createTextractClient({ auth: context.auth.props, server: context.server });
const documentInput = buildDocumentInput(file, s3Bucket, s3Key);
const response = await client.send(
diff --git a/packages/pieces/community/amazon-textract/src/lib/actions/get-document-analysis.ts b/packages/pieces/community/amazon-textract/src/lib/actions/get-document-analysis.ts
index 445f9ede506..1d8d8794c82 100644
--- a/packages/pieces/community/amazon-textract/src/lib/actions/get-document-analysis.ts
+++ b/packages/pieces/community/amazon-textract/src/lib/actions/get-document-analysis.ts
@@ -38,7 +38,7 @@ export const getDocumentAnalysis = createAction({
const { jobId, nextToken, maxResults } = context.propsValue;
try {
- const client = createTextractClient(context.auth.props);
+ const client = await createTextractClient({ auth: context.auth.props, server: context.server });
const response = await client.send(
new GetDocumentAnalysisCommand({
diff --git a/packages/pieces/community/amazon-textract/src/lib/actions/start-document-analysis.ts b/packages/pieces/community/amazon-textract/src/lib/actions/start-document-analysis.ts
index dcb21463129..1883f9d1b47 100644
--- a/packages/pieces/community/amazon-textract/src/lib/actions/start-document-analysis.ts
+++ b/packages/pieces/community/amazon-textract/src/lib/actions/start-document-analysis.ts
@@ -65,7 +65,7 @@ export const startDocumentAnalysis = createAction({
} = context.propsValue;
try {
- const client = createTextractClient(context.auth.props);
+ const client = await createTextractClient({ auth: context.auth.props, server: context.server });
const response = await client.send(
new StartDocumentAnalysisCommand({
diff --git a/packages/pieces/community/amazon-textract/src/lib/auth.test.ts b/packages/pieces/community/amazon-textract/src/lib/auth.test.ts
new file mode 100644
index 00000000000..4b8db181902
--- /dev/null
+++ b/packages/pieces/community/amazon-textract/src/lib/auth.test.ts
@@ -0,0 +1,236 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const { sendMock } = vi.hoisted(() => ({ sendMock: vi.fn() }));
+
+vi.mock('@aws-sdk/client-sts', () => ({
+ STSClient: vi.fn(() => ({ send: sendMock })),
+ AssumeRoleWithWebIdentityCommand: vi.fn((input: unknown) => ({ input })),
+}));
+
+import { PieceServerContextError } from '@activepieces/pieces-framework';
+import { amazonTextractOidcAuth } from './auth';
+import { createTextractClient } from './common';
+
+const mintOidcToken = vi.fn();
+
+const validationServer = {
+ apiUrl: 'http://127.0.0.1:4200/api/',
+ publicUrl: 'http://127.0.0.1:4200/api/',
+ mintOidcToken,
+};
+
+const runtimeServer = {
+ apiUrl: 'http://127.0.0.1:3000/',
+ publicUrl: 'http://127.0.0.1:4200/api/',
+ token: 'engine-token',
+};
+
+const stsCredentials = {
+ Credentials: {
+ AccessKeyId: 'ASIATEMP',
+ SecretAccessKey: 'temp-secret',
+ SessionToken: 'temp-session',
+ Expiration: new Date(Date.now() + 3_600_000),
+ },
+};
+
+describe('amazonTextractOidcAuth.validate', () => {
+ beforeEach(() => {
+ sendMock.mockReset();
+ mintOidcToken.mockReset();
+ mintOidcToken.mockResolvedValue('signed-oidc-token');
+ });
+
+ it('rejects a malformed role ARN without calling AWS', async () => {
+ const result = await amazonTextractOidcAuth.validate?.({
+ auth: { roleArn: 'not-an-arn', region: 'us-east-1' },
+ server: validationServer,
+ });
+
+ expect(result).toEqual({
+ valid: false,
+ error: 'Invalid IAM Role ARN format. Expected: arn:aws:iam::123456789012:role/RoleName',
+ });
+ expect(mintOidcToken).not.toHaveBeenCalled();
+ expect(sendMock).not.toHaveBeenCalled();
+ });
+
+ it('rejects a region that is not an AWS region before reaching AWS', async () => {
+ const result = await amazonTextractOidcAuth.validate?.({
+ auth: { roleArn: 'arn:aws:iam::123456789012:role/valid-shape', region: 'us-east-1.evil.com' },
+ server: validationServer,
+ });
+
+ expect(result).toEqual({ valid: false, error: 'Invalid AWS region: us-east-1.evil.com' });
+ expect(mintOidcToken).not.toHaveBeenCalled();
+ expect(sendMock).not.toHaveBeenCalled();
+ });
+
+ it('returns the STS error when the role cannot be assumed', async () => {
+ const stsError = new Error('Not authorized to perform sts:AssumeRoleWithWebIdentity');
+ stsError.name = 'AccessDenied';
+ sendMock.mockRejectedValue(stsError);
+
+ const result = await amazonTextractOidcAuth.validate?.({
+ auth: { roleArn: 'arn:aws:iam::123456789012:role/untrusted', region: 'us-east-1' },
+ server: validationServer,
+ });
+
+ expect(result).toEqual({
+ valid: false,
+ error: 'AccessDenied: Not authorized to perform sts:AssumeRoleWithWebIdentity',
+ });
+ expect(mintOidcToken).toHaveBeenCalledWith({ audience: 'sts.amazonaws.com' });
+ expect(sendMock.mock.calls[0][0].input).toMatchObject({
+ RoleArn: 'arn:aws:iam::123456789012:role/untrusted',
+ WebIdentityToken: 'signed-oidc-token',
+ });
+ });
+
+ it('re-throws PieceServerContextError so an engine failure is not reported as an invalid connection', async () => {
+ mintOidcToken.mockRejectedValue(new PieceServerContextError('Failed to get OIDC token: Forbidden'));
+
+ await expect(
+ amazonTextractOidcAuth.validate?.({
+ auth: { roleArn: 'arn:aws:iam::123456789012:role/token-endpoint-down', region: 'us-east-1' },
+ server: validationServer,
+ }),
+ ).rejects.toBeInstanceOf(PieceServerContextError);
+ expect(sendMock).not.toHaveBeenCalled();
+ });
+
+ it('accepts when the role assumption succeeds', async () => {
+ sendMock.mockResolvedValue(stsCredentials);
+
+ const result = await amazonTextractOidcAuth.validate?.({
+ auth: { roleArn: 'arn:aws:iam::123456789012:role/assumable-role', region: 'us-east-1' },
+ server: validationServer,
+ });
+
+ expect(result).toEqual({ valid: true });
+ });
+});
+
+describe('createTextractClient', () => {
+ const fetchMock = vi.fn();
+
+ beforeEach(() => {
+ sendMock.mockReset();
+ fetchMock.mockReset();
+ vi.stubGlobal('fetch', fetchMock);
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('uses temporary credentials from the assumed role for an OIDC connection', async () => {
+ fetchMock.mockResolvedValue({ ok: true, json: async () => ({ token: 'engine-oidc-token' }) });
+ sendMock.mockResolvedValue(stsCredentials);
+
+ const client = await createTextractClient({
+ auth: { roleArn: 'arn:aws:iam::123456789012:role/textract', region: 'eu-west-1' },
+ server: runtimeServer,
+ });
+
+ expect(fetchMock).toHaveBeenCalledWith('http://127.0.0.1:3000/v1/worker/oidc-token', expect.objectContaining({ method: 'POST' }));
+ expect(sendMock.mock.calls[0][0].input).toMatchObject({
+ RoleArn: 'arn:aws:iam::123456789012:role/textract',
+ WebIdentityToken: 'engine-oidc-token',
+ });
+ await expect(client.config.credentials()).resolves.toMatchObject({
+ accessKeyId: 'ASIATEMP',
+ secretAccessKey: 'temp-secret',
+ sessionToken: 'temp-session',
+ });
+ await expect(client.config.region()).resolves.toBe('eu-west-1');
+ });
+
+ it('uses the static keys for an access key connection without calling STS', async () => {
+ const client = await createTextractClient({
+ auth: { accessKeyId: 'AKIASTATIC', secretAccessKey: 'static-secret', region: 'us-east-2' },
+ server: runtimeServer,
+ });
+
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(sendMock).not.toHaveBeenCalled();
+ await expect(client.config.credentials()).resolves.toMatchObject({
+ accessKeyId: 'AKIASTATIC',
+ secretAccessKey: 'static-secret',
+ });
+ });
+
+ it('reuses cached credentials for the same run instead of assuming the role again', async () => {
+ fetchMock.mockResolvedValue({ ok: true, json: async () => ({ token: 'engine-oidc-token' }) });
+ sendMock.mockResolvedValue(stsCredentials);
+ const params = {
+ auth: { roleArn: 'arn:aws:iam::123456789012:role/cached', region: 'us-east-1' },
+ server: runtimeServer,
+ };
+
+ await createTextractClient(params);
+ const client = await createTextractClient(params);
+ await client.config.credentials();
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(sendMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('never shares cached credentials between runs that assume the same role', async () => {
+ fetchMock.mockResolvedValue({ ok: true, json: async () => ({ token: 'engine-oidc-token' }) });
+ sendMock
+ .mockResolvedValueOnce({ Credentials: { ...stsCredentials.Credentials, AccessKeyId: 'ASIARUNA' } })
+ .mockResolvedValueOnce({ Credentials: { ...stsCredentials.Credentials, AccessKeyId: 'ASIARUNB' } });
+ const auth = { roleArn: 'arn:aws:iam::123456789012:role/shared-role', region: 'us-east-1' };
+
+ const clientA = await createTextractClient({ auth, server: { ...runtimeServer, token: 'engine-token-run-a' } });
+ const clientB = await createTextractClient({ auth, server: { ...runtimeServer, token: 'engine-token-run-b' } });
+
+ await expect(clientA.config.credentials()).resolves.toMatchObject({ accessKeyId: 'ASIARUNA' });
+ await expect(clientB.config.credentials()).resolves.toMatchObject({ accessKeyId: 'ASIARUNB' });
+ expect(sendMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('refreshes credentials that are close to expiry so long-running actions keep working', async () => {
+ fetchMock.mockResolvedValue({ ok: true, json: async () => ({ token: 'engine-oidc-token' }) });
+ sendMock
+ .mockResolvedValueOnce({
+ Credentials: { ...stsCredentials.Credentials, AccessKeyId: 'ASIASTALE', Expiration: new Date(Date.now() + 60_000) },
+ })
+ .mockResolvedValueOnce({
+ Credentials: { ...stsCredentials.Credentials, AccessKeyId: 'ASIAFRESH', Expiration: new Date(Date.now() + 3_600_000) },
+ });
+
+ const client = await createTextractClient({
+ auth: { roleArn: 'arn:aws:iam::123456789012:role/refreshing', region: 'us-east-1' },
+ server: runtimeServer,
+ });
+
+ await expect(client.config.credentials()).resolves.toMatchObject({ accessKeyId: 'ASIAFRESH' });
+ expect(sendMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('reports the HTTP status when the engine cannot mint an OIDC token', async () => {
+ fetchMock.mockResolvedValue({ ok: false, status: 403, statusText: 'Forbidden' });
+
+ await expect(
+ createTextractClient({
+ auth: { roleArn: 'arn:aws:iam::123456789012:role/token-denied', region: 'us-east-1' },
+ server: runtimeServer,
+ }),
+ ).rejects.toThrow('Failed to get OIDC token: 403 Forbidden');
+ expect(sendMock).not.toHaveBeenCalled();
+ });
+
+ it('does not call STS when the token response has no token', async () => {
+ fetchMock.mockResolvedValue({ ok: true, json: async () => ({}) });
+
+ await expect(
+ createTextractClient({
+ auth: { roleArn: 'arn:aws:iam::123456789012:role/token-missing', region: 'us-east-1' },
+ server: runtimeServer,
+ }),
+ ).rejects.toThrow('Failed to get OIDC token: the response did not include a token');
+ expect(sendMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/pieces/community/amazon-textract/src/lib/auth.ts b/packages/pieces/community/amazon-textract/src/lib/auth.ts
index 4fe9ddbe7d5..b601947fcd5 100644
--- a/packages/pieces/community/amazon-textract/src/lib/auth.ts
+++ b/packages/pieces/community/amazon-textract/src/lib/auth.ts
@@ -1,8 +1,87 @@
-import { PieceAuth, Property } from '@activepieces/pieces-framework';
+import { isPieceServerContextError, PieceAuth, Property } from '@activepieces/pieces-framework';
import { GetDocumentAnalysisCommand } from '@aws-sdk/client-textract';
-import { createTextractClient } from './common';
+import { createTextractClient, getTemporaryCredentials } from './common';
-export const amazonTextractAuth = PieceAuth.CustomAuth({
+const oidcDescription = `
+Connect AWS Textract using an IAM Role via OIDC. No permanent keys required.
+
+Activepieces acts as an OIDC identity provider. AWS trusts this provider and issues temporary credentials via \`AssumeRoleWithWebIdentity\`.
+
+**Setup steps:**
+1. In AWS IAM → Identity Providers → Create Provider:
+ - Provider type: **OpenID Connect**
+ - Provider URL: \`{{frontendUrl}}\`
+ - Audience: \`sts.amazonaws.com\`
+
+ > AWS fetches \`{{frontendUrl}}/.well-known/openid-configuration\` to discover the OIDC metadata. If your frontend and API run on different domains, make sure the API server is reachable at \`{{frontendUrl}}\` (or that your frontend proxies \`/.well-known/*\` to the API), otherwise \`AssumeRoleWithWebIdentity\` will fail.
+2. Create an IAM Role with this trust policy:
+\`\`\`json
+{
+ "Version": "2012-10-17",
+ "Statement": [{
+ "Effect": "Allow",
+ "Principal": { "Federated": "arn:aws:iam::YOUR_ACCOUNT_ID:oidc-provider/{{frontendHost}}" },
+ "Action": "sts:AssumeRoleWithWebIdentity",
+ "Condition": {
+ "StringEquals": {
+ "{{frontendHost}}:aud": "sts.amazonaws.com"
+ },
+ "StringLike": {
+ "{{frontendHost}}:sub": "platform:{{platformId}}:project:{{projectId}}"
+ }
+ }
+ }]
+}
+\`\`\`
+ For an AWS GovCloud (US) region, use \`arn:aws-us-gov:iam::\` instead of \`arn:aws:iam::\` in the \`Federated\` principal.
+3. Attach Textract permissions to the role (e.g. the \`AmazonTextractFullAccess\` policy), plus \`s3:GetObject\` on any bucket you read documents from, and paste the **Role ARN** below.
+`;
+
+const TEXTRACT_AWS_REGIONS = [
+ { label: 'US East (N. Virginia) [us-east-1]', value: 'us-east-1' },
+ { label: 'US East (Ohio) [us-east-2]', value: 'us-east-2' },
+ { label: 'US West (N. California) [us-west-1]', value: 'us-west-1' },
+ { label: 'US West (Oregon) [us-west-2]', value: 'us-west-2' },
+ {
+ label: 'Asia Pacific (Mumbai) [ap-south-1]',
+ value: 'ap-south-1',
+ },
+ {
+ label: 'Asia Pacific (Seoul) [ap-northeast-2]',
+ value: 'ap-northeast-2',
+ },
+ {
+ label: 'Asia Pacific (Singapore) [ap-southeast-1]',
+ value: 'ap-southeast-1',
+ },
+ {
+ label: 'Asia Pacific (Sydney) [ap-southeast-2]',
+ value: 'ap-southeast-2',
+ },
+ {
+ label: 'Canada (Central) [ca-central-1]',
+ value: 'ca-central-1',
+ },
+ {
+ label: 'Europe (Frankfurt) [eu-central-1]',
+ value: 'eu-central-1',
+ },
+ { label: 'Europe (Ireland) [eu-west-1]', value: 'eu-west-1' },
+ { label: 'Europe (London) [eu-west-2]', value: 'eu-west-2' },
+ { label: 'Europe (Paris) [eu-west-3]', value: 'eu-west-3' },
+ { label: 'Europe (Spain) [eu-south-2]', value: 'eu-south-2' },
+ {
+ label: 'AWS GovCloud (US-East) [us-gov-east-1]',
+ value: 'us-gov-east-1',
+ },
+ {
+ label: 'AWS GovCloud (US-West) [us-gov-west-1]',
+ value: 'us-gov-west-1',
+ },
+];
+
+export const amazonTextractAccessKeyAuth = PieceAuth.CustomAuth({
+ displayName: 'AWS Textract (Access Key)',
description:
'Authenticate with AWS using your Access Key ID and Secret Access Key. The IAM user or role must have permissions for AWS Textract (e.g., the `AmazonTextractFullAccess` managed policy).',
props: {
@@ -20,54 +99,13 @@ export const amazonTextractAuth = PieceAuth.CustomAuth({
displayName: 'Region',
required: true,
options: {
- options: [
- { label: 'US East (N. Virginia) [us-east-1]', value: 'us-east-1' },
- { label: 'US East (Ohio) [us-east-2]', value: 'us-east-2' },
- { label: 'US West (N. California) [us-west-1]', value: 'us-west-1' },
- { label: 'US West (Oregon) [us-west-2]', value: 'us-west-2' },
- {
- label: 'Asia Pacific (Mumbai) [ap-south-1]',
- value: 'ap-south-1',
- },
- {
- label: 'Asia Pacific (Seoul) [ap-northeast-2]',
- value: 'ap-northeast-2',
- },
- {
- label: 'Asia Pacific (Singapore) [ap-southeast-1]',
- value: 'ap-southeast-1',
- },
- {
- label: 'Asia Pacific (Sydney) [ap-southeast-2]',
- value: 'ap-southeast-2',
- },
- {
- label: 'Canada (Central) [ca-central-1]',
- value: 'ca-central-1',
- },
- {
- label: 'Europe (Frankfurt) [eu-central-1]',
- value: 'eu-central-1',
- },
- { label: 'Europe (Ireland) [eu-west-1]', value: 'eu-west-1' },
- { label: 'Europe (London) [eu-west-2]', value: 'eu-west-2' },
- { label: 'Europe (Paris) [eu-west-3]', value: 'eu-west-3' },
- { label: 'Europe (Spain) [eu-south-2]', value: 'eu-south-2' },
- {
- label: 'AWS GovCloud (US-East) [us-gov-east-1]',
- value: 'us-gov-east-1',
- },
- {
- label: 'AWS GovCloud (US-West) [us-gov-west-1]',
- value: 'us-gov-west-1',
- },
- ],
+ options: TEXTRACT_AWS_REGIONS,
},
}),
},
- validate: async ({ auth }) => {
+ validate: async ({ auth, server }) => {
try {
- const client = createTextractClient(auth);
+ const client = await createTextractClient({ auth, server });
await client.send(
new GetDocumentAnalysisCommand({ JobId: 'validate-credentials' })
);
@@ -85,3 +123,60 @@ export const amazonTextractAuth = PieceAuth.CustomAuth({
},
required: true,
});
+
+export const amazonTextractOidcAuth = PieceAuth.OIDC({
+ displayName: 'AWS Textract (IAM Role / OIDC)',
+ description: oidcDescription,
+ props: {
+ roleArn: Property.ShortText({
+ displayName: 'Role ARN',
+ description: 'The ARN of the IAM role to assume (e.g. arn:aws:iam::123456789012:role/MyRole).',
+ required: true,
+ }),
+ region: Property.StaticDropdown({
+ displayName: 'Region',
+ required: true,
+ options: {
+ options: TEXTRACT_AWS_REGIONS,
+ },
+ }),
+ },
+ validate: async ({ auth, server }) => {
+ const arnRegex = /^arn:(?:aws|aws-us-gov|aws-cn):iam::\d{12}:role\/[\w+=,.@\-/]{1,512}$/;
+ if (!arnRegex.test(auth.roleArn)) {
+ return { valid: false, error: 'Invalid IAM Role ARN format. Expected: arn:aws:iam::123456789012:role/RoleName' };
+ }
+ try {
+ await getTemporaryCredentials({ auth, server });
+ return { valid: true };
+ } catch (error) {
+ if (isPieceServerContextError(error)) throw error;
+ return { valid: false, error: formatAssumeRoleError(error) };
+ }
+ },
+ required: true,
+});
+
+export const amazonTextractAuth = [amazonTextractAccessKeyAuth, amazonTextractOidcAuth];
+
+function formatAssumeRoleError(error: unknown): string {
+ const fallback = 'Failed to assume the IAM role. Check the role ARN and trust policy.';
+ if (error instanceof Error) {
+ if (error.name && error.name !== 'Error') return `${error.name}: ${error.message}`;
+ return error.message || fallback;
+ }
+ return fallback;
+}
+
+export type TextractAccessKeyAuth = {
+ accessKeyId: string;
+ secretAccessKey: string;
+ region: string;
+};
+
+export type TextractOidcAuth = {
+ roleArn: string;
+ region: string;
+};
+
+export type TextractAuth = TextractAccessKeyAuth | TextractOidcAuth;
diff --git a/packages/pieces/community/amazon-textract/src/lib/common.ts b/packages/pieces/community/amazon-textract/src/lib/common.ts
index bc788081580..ef546dd6ba6 100644
--- a/packages/pieces/community/amazon-textract/src/lib/common.ts
+++ b/packages/pieces/community/amazon-textract/src/lib/common.ts
@@ -1,4 +1,5 @@
-import { ApFile } from '@activepieces/pieces-framework';
+import { ApFile, AuthValidationServerContext, ServerContext } from '@activepieces/pieces-framework';
+import { AssumeRoleWithWebIdentityCommand, STSClient } from '@aws-sdk/client-sts';
import {
TextractClient,
Block,
@@ -8,12 +9,7 @@ import {
ExpenseDocument,
IdentityDocument,
} from '@aws-sdk/client-textract';
-
-export interface TextractAuth {
- accessKeyId: string;
- secretAccessKey: string;
- region: string;
-}
+import type { TextractAuth, TextractOidcAuth } from './auth';
// ─── Output Types ────────────────────────────────────────────────────────────
@@ -111,7 +107,20 @@ export interface AnalyzeIDResult {
// ─── Client Factory ───────────────────────────────────────────────────────────
-export function createTextractClient(auth: TextractAuth): TextractClient {
+export async function createTextractClient({
+ auth,
+ server,
+}: {
+ auth: TextractAuth;
+ server: ServerContext | AuthValidationServerContext;
+}): Promise<TextractClient> {
+ if ('roleArn' in auth) {
+ await getTemporaryCredentials({ auth, server });
+ return new TextractClient({
+ credentials: () => getTemporaryCredentials({ auth, server }),
+ region: auth.region,
+ });
+ }
return new TextractClient({
credentials: {
accessKeyId: auth.accessKeyId,
@@ -121,6 +130,60 @@ export function createTextractClient(auth: TextractAuth): TextractClient {
});
}
+export async function getTemporaryCredentials({
+ auth,
+ server,
+}: {
+ auth: TextractOidcAuth;
+ server: ServerContext | AuthValidationServerContext;
+}): Promise<TemporaryCredentials> {
+ if (!auth.roleArn) {
+ throw new Error('Role ARN is required for IAM Role authentication');
+ }
+ if (!AWS_REGION_REGEX.test(auth.region ?? '')) {
+ throw new Error(`Invalid AWS region: ${auth.region}`);
+ }
+
+ const cacheKey = 'token' in server ? `${server.token}:${auth.roleArn}:${auth.region}` : undefined;
+ if (cacheKey) {
+ const cached = credentialsCache.get(cacheKey);
+ if (cached && cached.expiresAtMS - Date.now() > CREDENTIALS_EXPIRY_MARGIN_MS) {
+ return cached.credentials;
+ }
+ }
+
+ const token = await resolveOidcToken({ server });
+
+ const sts = new STSClient({
+ region: auth.region,
+ maxAttempts: 2,
+ requestHandler: { requestTimeout: STS_REQUEST_TIMEOUT_MS, connectionTimeout: STS_CONNECT_TIMEOUT_MS },
+ });
+ const { Credentials } = await sts.send(
+ new AssumeRoleWithWebIdentityCommand({
+ RoleArn: auth.roleArn,
+ RoleSessionName: 'activepieces-execution',
+ WebIdentityToken: token,
+ DurationSeconds: STS_DURATION_SECONDS,
+ }),
+ );
+ if (!Credentials?.AccessKeyId || !Credentials.SecretAccessKey) {
+ throw new Error('Failed to assume role: no credentials returned');
+ }
+ const expiresAtMS = Credentials.Expiration?.getTime() ?? Date.now() + STS_DURATION_SECONDS * 1000;
+ const credentials = {
+ accessKeyId: Credentials.AccessKeyId,
+ secretAccessKey: Credentials.SecretAccessKey,
+ sessionToken: Credentials.SessionToken,
+ expiration: new Date(expiresAtMS),
+ };
+ if (cacheKey) {
+ sweepExpiredCredentials();
+ credentialsCache.set(cacheKey, { credentials, expiresAtMS });
+ }
+ return credentials;
+}
+
// ─── Document Input Builder ───────────────────────────────────────────────────
export function buildDocumentInput(
@@ -522,3 +585,60 @@ export function formatTextractError(error: unknown): string {
return err.message ?? 'An unexpected error occurred.';
}
}
+
+async function resolveOidcToken({ server }: { server: ServerContext | AuthValidationServerContext }): Promise<string> {
+ if ('mintOidcToken' in server) {
+ return server.mintOidcToken({ audience: AWS_STS_AUDIENCE });
+ }
+ const response = await fetch(`${server.apiUrl}v1/worker/oidc-token`, {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${server.token}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({ audience: AWS_STS_AUDIENCE }),
+ signal: AbortSignal.timeout(OIDC_TOKEN_REQUEST_TIMEOUT_MS),
+ });
+ if (!response.ok) {
+ throw new Error(`Failed to get OIDC token: ${response.status} ${response.statusText}`.trim());
+ }
+ const body: unknown = await response.json();
+ if (!isOidcTokenResponse(body)) {
+ throw new Error('Failed to get OIDC token: the response did not include a token');
+ }
+ return body.token;
+}
+
+function isOidcTokenResponse(body: unknown): body is { token: string } {
+ return typeof body === 'object' && body !== null && 'token' in body && typeof body.token === 'string' && body.token.length > 0;
+}
+
+function sweepExpiredCredentials() {
+ const now = Date.now();
+ for (const [key, value] of credentialsCache) {
+ if (value.expiresAtMS <= now) {
+ credentialsCache.delete(key);
+ }
+ }
+}
+
+const AWS_STS_AUDIENCE = 'sts.amazonaws.com';
+const AWS_REGION_REGEX = /^[a-z]{2}(-[a-z]+)+-\d$/;
+const STS_DURATION_SECONDS = 3600;
+const STS_REQUEST_TIMEOUT_MS = 10_000;
+const STS_CONNECT_TIMEOUT_MS = 5_000;
+const OIDC_TOKEN_REQUEST_TIMEOUT_MS = 10_000;
+const CREDENTIALS_EXPIRY_MARGIN_MS = 5 * 60 * 1000;
+const credentialsCache = new Map<string, CachedCredentials>();
+
+type TemporaryCredentials = {
+ accessKeyId: string;
+ secretAccessKey: string;
+ sessionToken: string | undefined;
+ expiration: Date;
+};
+
+type CachedCredentials = {
+ credentials: TemporaryCredentials;
+ expiresAtMS: number;
+};
diff --git a/packages/pieces/community/amazon-textract/tsconfig.lib.json b/packages/pieces/community/amazon-textract/tsconfig.lib.json
index 812842bd452..742e666355e 100644
--- a/packages/pieces/community/amazon-textract/tsconfig.lib.json
+++ b/packages/pieces/community/amazon-textract/tsconfig.lib.json
@@ -9,5 +9,6 @@
"declarationMap": true,
"types": ["node"]
},
- "include": ["src/**/*.ts"]
+ "include": ["src/**/*.ts"],
+ "exclude": ["src/**/*.spec.ts", "src/**/*.test.ts"]
}
diff --git a/packages/pieces/community/amazon-textract/vitest.config.ts b/packages/pieces/community/amazon-textract/vitest.config.ts
new file mode 100644
index 00000000000..ba8ade4a178
--- /dev/null
+++ b/packages/pieces/community/amazon-textract/vitest.config.ts
@@ -0,0 +1,17 @@
+import path from 'path'
+import { defineConfig } from 'vitest/config'
+
+const repoRoot = path.resolve(__dirname, '../../../..')
+
+export default defineConfig({
+ test: {
+ globals: true,
+ environment: 'node',
+ },
+ resolve: {
+ alias: {
+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),
+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),
+ },
+ },
+})