diff --git a/doc/connections/AWS.md b/doc/connections/AWS.md new file mode 100644 index 00000000000..40adf2285d3 --- /dev/null +++ b/doc/connections/AWS.md @@ -0,0 +1,166 @@ +# AWS + +The AWS connection lets agents work in an AWS account through AWS's hosted MCP +server (`https://aws-mcp..api.aws/mcp`). Paperclip stores no long-lived +AWS key for the role method. For each connection, the control plane mints a +one-hour bearer token at call time. Agents see the AWS tools like any other +connector's tools and never receive AWS credentials. + +It is behind the `enableAwsConnector` experimental setting (off by default). +The design and the spike that proved it are in +[the AWS connector plan](../plans/2026-11-17-aws-connector-and-minted-credentials.md) +and [the workload identity issuer](../plans/2026-11-17-workload-identity-issuer.md). + +## Vendor + +- App key: `aws` +- App name: AWS +- Reuse classification: MCP-direct (AWS-hosted MCP server), with credentials + minted by Paperclip. +- Security tier: S4 +- Plugin needed? No + +## Transport and auth + +- Transport: `mcp_remote`. The endpoint is chosen from AWS's eight published + regions. Tool calls need an initialized MCP session (`mcpSessionRequired`). +- Auth: the method declares `credentialMinter: "aws_mcp"`. Stored credential + fields are inputs to the minter and are never sent as headers. The gateway and + connection health checks resolve the `Authorization` header in + `server/src/services/connectors/aws/mcp-credentials.ts`. +- **Role method (`aws-role`, recommended):** no stored keys. + 1. The connection proves itself with a 5-minute token signed by the company's + workload identity issuer (`sub = connection:`, + `aud = sts.amazonaws.com`). + 2. STS `AssumeRoleWithWebIdentity` returns role credentials. + 3. AWS Sign-in `CreateOAuth2TokenWithIAM` (`client_credentials`, resource + `aws-mcp.amazonaws.com`) returns the bearer token. + + This method needs a public HTTPS address that AWS can reach. +- **Access-key method (`aws-access-key`):** a dedicated IAM user's key, stored + as this connection's vault secrets (`credentials.accessKeyId`, + `credentials.secretAccessKey`). Read only uses `GetFederationToken`. Full + access uses the key directly. With a role ARN, the minter uses `AssumeRole`. + This method works on any instance, including local ones. +- **Access level** is set per connection: + - `read_only` (the default) adds `ReadOnlyAccess` and + `AWSMCPSignInOAuthAccessPolicy` as session policies, so AWS refuses changes + even when the role allows them. Without the second policy, the token + exchange fails. + - `full` uses everything the role or key allows. +- **Caching:** the token is cached in memory for each connection and grant until + about 55 minutes in. It is minted again when these change: + - the saved settings; + - the stored key references; + - connection or grant status. + + When AWS answers 401, the gateway mints a fresh token and does not replay the + call. The caller retries. Catalog discovery lists again automatically. +- **Revocation:** delete the connection, or remove the role's trust or the IAM + user's key in AWS. Tokens already issued expire within the hour. + +## Connection flow + +```mermaid +sequenceDiagram + participant Agent + participant Gateway as Paperclip control plane + participant STS as AWS STS + participant Signin as AWS Sign-in + participant MCP as AWS MCP server + Agent->>Gateway: tools/call aws___run_script + Gateway->>Gateway: sign connection token (cached bearer skips the next three steps) + Gateway->>STS: AssumeRoleWithWebIdentity (role, token, read-only policies) + STS->>Gateway: fetches issuer JWKS, returns role credentials + Gateway->>Signin: CreateOAuth2TokenWithIAM (SigV4 with role credentials) + Signin->>Gateway: bearer token (1 hour) + Gateway->>MCP: tools/call with Authorization Bearer + MCP->>Gateway: result (AWS ran the script in its sandbox) + Gateway->>Agent: result +``` + +- Issuer discovery: `GET /oidc/companies//.well-known/openid-configuration` +- Issuer keys: `GET /oidc/companies//jwks.json` +- Paperclip callback: none. +- Paperclip ID / Paperclip Connect involvement: none. The instance is its own + OIDC issuer. + +## Administrator setup + +The role method uses three steps, because the role must trust a connection +that already exists: + +1. Turn on **AWS connector** in Instance Settings, Experimental. +2. **Save a draft.** Call `connectGalleryApp` with `saveDraft: true`, the role + ARN to be created, the endpoint region and the access level. Paperclip + creates the connection without contacting AWS. It also publishes the + company's issuer, so AWS can validate it in the next step. +3. In the AWS account: + - Register the issuer `https:///oidc/companies/` as an + IAM OIDC identity provider with audience `sts.amazonaws.com`. + - Create the role. Its trust policy allows + `sts:AssumeRoleWithWebIdentity` only when `:sub` equals + `connection:` and `:aud` equals `sts.amazonaws.com`. + - Attach `AWSMCPSignInOAuthAccessPolicy` and the permissions agents need. +4. **Resume** with `resumeConnectionId`. Paperclip mints a token, lists the + tools, and the connection becomes active. + +For the access-key method, create a dedicated IAM user with +`AWSMCPSignInOAuthAccessPolicy`, `sts:GetFederationToken` and the agents' +permissions. Then connect with the key. Setup lists the tools immediately. + +A guided setup screen and a CloudFormation template are planned next. Until +then, the generic setup form and these steps apply. + +**Verify:** the connection lists 8 tools. A test call of `aws___run_script` that +runs `ListBuckets` succeeds. With read-only access, a `CreateBucket` call is +refused by AWS with "no session policy allows". + +## Tools and risk + +Reviewed tool risk is declared in the app definition: + +- **Writes:** `aws___run_script` (the only tool that calls AWS APIs) and + `aws___get_presigned_url`. +- **Reads:** documentation search and read, skills, regions, regional + availability and task status. +- **Unlisted tools:** treated as writes. + +Read-only connections are enforced by AWS through the session policy, not by +hiding `run_script`. + +## Failure codes + +Each code appears on the connection's health with a plain message. AWS's own +error text is never shown, because it can contain account IDs and ARNs. + +| Code | Health | Meaning | +|---|---|---| +| `aws_mcp_settings_invalid` | error | Saved settings are incomplete, or the URL is not AWS's endpoint for the saved region. | +| `aws_identity_unavailable` | error | The role method needs a stable public HTTPS address. | +| `aws_issuer_changed` | error | The instance's address changed since setup. Register the new issuer in AWS (and update the role's trust), then reconnect: reconnecting records the current address. | +| `aws_role_access_denied` | error | AWS refused the role: it is missing, or its trust does not match this connection. | +| `aws_access_key_invalid` | error | The access key is invalid or inactive, or the user cannot call `GetFederationToken`. | +| `aws_mcp_signin_denied` | error | The token exchange was refused. Attach `AWSMCPSignInOAuthAccessPolicy`. | +| `aws_unavailable` | degraded | AWS did not respond, or throttled the request. | + +## Verification record + +On 2026-11-18, the integrated path ran against the Paperclip dev AWS account. +It used Paperclip's own setup, catalog and gateway code, real STS and Sign-in, +and AWS's MCP server. The issuer was behind a temporary public tunnel. + +- **Access key, read only:** 8 tools listed. `run_script` `ListBuckets` + succeeded in 8.9 s (cold sandbox). `CreateBucket` was refused by the session + policy. +- **Role:** the draft was saved without contacting AWS, and the issuer was + published. After the IAM provider and a role trusting only that connection + were created, resuming setup listed 8 tools. `ListBuckets` succeeded in + 12.8 s (cold sandbox). `CreateBucket` was refused by the role's own + permissions. + +All IAM users, keys, roles, providers and buckets were deleted afterwards. + +Not live-tested yet: Paperclip Cloud staging, the CloudFormation template (not +built yet), and `AssumeRole` from an access key with a role ARN (covered by unit +tests only). diff --git a/doc/connections/README.md b/doc/connections/README.md index d66cb81371d..3b2c5f225e6 100644 --- a/doc/connections/README.md +++ b/doc/connections/README.md @@ -31,7 +31,7 @@ organization connections where no person signs in). Long-term memory: [Experimental memory connectors](./MEMORY.md). -Provider notes: [Google Workspace](./GOOGLE-WORKSPACE.md), +Provider notes: [AWS](./AWS.md), [Google Workspace](./GOOGLE-WORKSPACE.md), [Gmail](./GMAIL.md), [Asana](./ASANA.md), [Sentry](./SENTRY.md), [PostHog](./POSTHOG.md), [Braintrust](./BRAINTRUST.md), [Neon](./NEON.md), [Superagent](./SUPERAGENT.md), [Gauge](./GAUGE.md), [Ditto](./DITTO.md), [Circleback](./CIRCLEBACK.md), [1Password](./1PASSWORD.md), [Unikraft](./UNIKRAFT.md), [AgentMail](./AGENTMAIL.md), [Telem.AI](./TELEM.md), [iMessage Photon](./IMESSAGE-PHOTON.md), [Enterpret](./ENTERPRET.md), [Supabase](./SUPABASE.md), and diff --git a/doc/connections/tool-method-permission-reviews.json b/doc/connections/tool-method-permission-reviews.json index 75b94d1e025..f7a2ebcccac 100644 --- a/doc/connections/tool-method-permission-reviews.json +++ b/doc/connections/tool-method-permission-reviews.json @@ -2978,6 +2978,39 @@ "reviewedAt": "2026-10-22", "liveProof": "read-write-verified", "evidenceLimit": "2026-10-23: a replacement token passed all eight actions through a real run-scoped gateway for personal and shared credentials, including create/list/read/update/secret resolution/archive/delete on synthetic items. Both test items were deleted and absent from subsequent listings. Catalog refresh, reconnect preserving identity, removal, retained-session denial and credential absence passed. The 2026-10-22 token denied creation; the first 2026-10-23 attempt stopped before provider calls due to host PostgreSQL semaphore exhaustion. A temporary ten-connection test profile allowed the complete live retry to pass without changing shared services." + }, + { + "app": "aws", + "method": "aws-role", + "auth": "api_key", + "policy": "provider-key", + "requestedScopes": [], + "capability": "provider-controlled", + "supportedActions": "Any AWS API the connection's IAM role allows, through run_script. The read-only access level adds AWS ReadOnlyAccess as a session policy.", + "evidence": [ + "https://docs.aws.amazon.com/agent-toolkit/latest/userguide/getting-started-aws-mcp-server.html", + "https://docs.aws.amazon.com/agent-toolkit/latest/userguide/oauth-authentication.html", + "https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html" + ], + "reviewedAt": "2026-11-18", + "liveProof": "2026-11-18 spike in the Paperclip dev AWS account (doc/plans/2026-11-17-aws-connector-and-minted-credentials.md, Spike findings): a Paperclip-signed connection token assumed its role, another connection's token was denied, the bearer exchange and tools/list passed, and run_script read and wrote. A read-only session read and AWS refused its write. Both access-key paths obtained a bearer. The production connector path itself is not yet live-tested." + }, + { + "app": "aws", + "method": "aws-access-key", + "auth": "api_key", + "policy": "provider-key", + "requestedScopes": [], + "capability": "provider-controlled", + "supportedActions": "Any AWS API the IAM user (or its optional role) allows, through run_script. The read-only access level adds AWS ReadOnlyAccess as a session policy.", + "evidence": [ + "https://docs.aws.amazon.com/agent-toolkit/latest/userguide/getting-started-aws-mcp-server.html", + "https://docs.aws.amazon.com/agent-toolkit/latest/userguide/oauth-authentication.html", + "https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html" + ], + "reviewedAt": "2026-11-18", + "liveProof": "2026-11-18 spike in the Paperclip dev AWS account (doc/plans/2026-11-17-aws-connector-and-minted-credentials.md, Spike findings): a Paperclip-signed connection token assumed its role, another connection's token was denied, the bearer exchange and tools/list passed, and run_script read and wrote. A read-only session read and AWS refused its write. Both access-key paths obtained a bearer. The production connector path itself is not yet live-tested.", + "keyPermissions": "Use a dedicated IAM user for this connection. It needs AWSMCPSignInOAuthAccessPolicy, sts:GetFederationToken, and the permissions agents should have; Paperclip cannot raise them." } ] } diff --git a/doc/plans/2026-11-17-aws-connector-and-minted-credentials.md b/doc/plans/2026-11-17-aws-connector-and-minted-credentials.md index df03a2d89e9..959e7525ae7 100644 --- a/doc/plans/2026-11-17-aws-connector-and-minted-credentials.md +++ b/doc/plans/2026-11-17-aws-connector-and-minted-credentials.md @@ -254,9 +254,9 @@ test it. Verify it when the personal-grant method is built. | # | Deliverable | Proof | |---|---|---| | 0 | **Done 2026-11-18. Results are in "Spike findings".** Verified: AWS accepts a JWT from a tunnelled Paperclip issuer; connection isolation; the token exchange; tool listing; reads and writes through `aws___run_script`; read-only session policies through `AssumeRoleWithWebIdentity` and `GetFederationToken`; the region is passed per call; timings. Resolved: the server offers no `aws___call_aws`. **Not tested, deferred:** DCR OAuth sign-in as a person, and `AssumeRole` from an access key. | Findings recorded in this doc | -| 1 | Minted-credential source in the gateway: minter interface, cache, single retry on 401, health reasons. | Red/green tests: cache hit and expiry, a 401 leads to one re-mint, mint failure sets health, nothing persisted or logged | -| 1b | Per-company workload-identity issuer (`/oidc/companies/`): signing key stored in the database, encrypted with the vault master key; discovery and JWKS routes, key rotation, JWT signing for a connection. Built in [the issuer PR](./2026-11-17-workload-identity-issuer.md). Built generically, because GCP and Azure accept the same kind of federation. | Red/green tests; AWS accepts a token from a staging instance | -| 2 | AWS minter (role via OIDC, and access key), app definition, setup screen, CloudFormation template, reviewed tools, and `doc/connections/AWS.md` following the connector playbook. | Real-provider proof: a read-only agent's write is refused by AWS; a write agent's write succeeds after approval | +| 1 | **Built.** Methods can declare `credentialMinter`. The gateway and health checks mint the `Authorization` header at call time and share one in-memory cache per connection and grant. A 401 mints again without replaying the call. AWS errors map to plain health reasons. See `doc/connections/AWS.md`. | Red/green unit and integration tests; a real-AWS run of the integrated path | +| 1b | **Built** (paperclipai/paperclip#22083). Per-company workload-identity issuer (`/oidc/companies/`): signing key stored in the database, encrypted with the vault master key; discovery and JWKS routes, key rotation, JWT signing for a connection. | Red/green tests; AWS accepted its tokens in the spike and in the integrated run | +| 2 | **Partly built.** Done: the AWS minter (role and access key), the app definition behind `enableAwsConnector`, reviewed tools, artwork, and `doc/connections/AWS.md`. Setup uses save-as-draft, then resume, because the role must trust an existing connection. Saving the draft publishes the issuer. **Next:** a guided setup screen showing the issuer and subject, and the CloudFormation template. | Real-AWS run: both methods listed 8 tools; a read succeeded and AWS refused a write | | 3 | Paperclip Cloud staging verification. | An AWS task completed on a staging stack | | Later | Option D (sandbox credentials for Terraform/CDK). Further minters as connectors need them, such as GCP service-account impersonation or Azure client credentials. Each needs its own check of what the provider supports. | Separate plans | diff --git a/docs/api/workload-identity.md b/docs/api/workload-identity.md index b975ed4cf33..69fa57f6c10 100644 --- a/docs/api/workload-identity.md +++ b/docs/api/workload-identity.md @@ -26,8 +26,9 @@ Responses are cacheable for five minutes. The issuer is `https://{instance}/oidc/companies/{companyId}`. Tokens have `sub` set to `connection:{connectionId}`, an `aud` chosen by the connection -type, and a lifetime of five minutes. Only an enabled, active connection can get a token, -so disabling a connection stops new tokens at once. +type, and a lifetime of five minutes. A disabled, archived or switched-off connection gets no token, so +turning a connection off stops new tokens at once. A draft can get one, so +setup can test it before it goes live; agents cannot use a draft. ## Board endpoints diff --git a/packages/shared/src/app-definitions.generated.ts b/packages/shared/src/app-definitions.generated.ts index e314e97d3b5..854539d487e 100644 --- a/packages/shared/src/app-definitions.generated.ts +++ b/packages/shared/src/app-definitions.generated.ts @@ -104,10 +104,11 @@ import a102 from "./app-definitions/messages-api.json" with { type: "json" }; import a103 from "./app-definitions/chat-completions-api.json" with { type: "json" }; import a104 from "./app-definitions/local.json" with { type: "json" }; import a105 from "./app-definitions/1password.json" with { type: "json" }; -import a106 from "./app-definitions/daytona.json" with { type: "json" }; -import a107 from "./app-definitions/monday.json" with { type: "json" }; -import a108 from "./app-definitions/paperclip-notebook.json" with { type: "json" }; -import a109 from "./app-definitions/unikraft.json" with { type: "json" }; -import a110 from "./app-definitions/speko.json" with { type: "json" }; +import a106 from "./app-definitions/aws.json" with { type: "json" }; +import a107 from "./app-definitions/daytona.json" with { type: "json" }; +import a108 from "./app-definitions/monday.json" with { type: "json" }; +import a109 from "./app-definitions/paperclip-notebook.json" with { type: "json" }; +import a110 from "./app-definitions/unikraft.json" with { type: "json" }; +import a111 from "./app-definitions/speko.json" with { type: "json" }; import type { AppDefinition } from "./types/app-definition.js"; -export const APP_DEFINITIONS=[a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,a19,a20,a21,a22,a23,a24,a25,a26,a27,a28,a29,a30,a31,a32,a33,a34,a35,a36,a37,a38,a39,a40,a41,a42,a43,a44,a45,a46,a47,a48,a49,a50,a51,a52,a53,a54,a55,a56,a57,a58,a59,a60,a61,a62,a63,a64,a65,a66,a67,a68,a69,a70,a71,a72,a73,a74,a75,a76,a77,a78,a79,a80,a81,a82,a83,a84,a85,a86,a87,a88,a89,a90,a91,a92,a93,a94,a95,a96,a97,a98,a99,a100,a101,a102,a103,a104,a105,a106,a107,a108,a109,a110] as AppDefinition[]; +export const APP_DEFINITIONS=[a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,a19,a20,a21,a22,a23,a24,a25,a26,a27,a28,a29,a30,a31,a32,a33,a34,a35,a36,a37,a38,a39,a40,a41,a42,a43,a44,a45,a46,a47,a48,a49,a50,a51,a52,a53,a54,a55,a56,a57,a58,a59,a60,a61,a62,a63,a64,a65,a66,a67,a68,a69,a70,a71,a72,a73,a74,a75,a76,a77,a78,a79,a80,a81,a82,a83,a84,a85,a86,a87,a88,a89,a90,a91,a92,a93,a94,a95,a96,a97,a98,a99,a100,a101,a102,a103,a104,a105,a106,a107,a108,a109,a110,a111] as AppDefinition[]; diff --git a/packages/shared/src/app-definitions.test.ts b/packages/shared/src/app-definitions.test.ts index 54cf668cf97..20b31d44848 100644 --- a/packages/shared/src/app-definitions.test.ts +++ b/packages/shared/src/app-definitions.test.ts @@ -3,6 +3,7 @@ import fs from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { APP_DEFINITIONS } from "./app-definitions.generated.js"; +import { connectionMethodDefSchema } from "./validators/app-definition.js"; import { APP_STORE_DEFINITIONS, APP_STORE_HIDDEN_SLUGS, @@ -905,7 +906,7 @@ describe("AppDefinition catalog", () => { "ticktick", "xero", ]); - expect(APP_STORE_DEFINITIONS).toHaveLength(89); + expect(APP_STORE_DEFINITIONS).toHaveLength(90); const connectableSlugs = new Set( CONNECTABLE_APP_DEFINITIONS.map((entry) => entry.slug), ); @@ -1471,6 +1472,21 @@ describe("AppDefinition catalog", () => { expect.stringContaining("consume organization credits"), ]); }); + it("mints AWS credentials instead of placing stored keys in headers", () => { + const aws = APP_DEFINITIONS.find((app) => app.slug === "aws")!; + expect(aws.experimentalFeatureKey).toBe("enableAwsConnector"); + for (const method of aws.methods) { + expect(method).toMatchObject({ transport: "mcp_remote", auth: "api_key", credentialMinter: "aws_mcp" }); + expect(method.keyPlacement).toBeUndefined(); + } + const base = aws.methods[1]!; + expect(connectionMethodDefSchema.safeParse(base).success).toBe(true); + expect(connectionMethodDefSchema.safeParse({ ...base, keyPlacement: { location: "header", name: "Authorization" } }).success).toBe(false); + expect(connectionMethodDefSchema.safeParse({ ...base, auth: "oauth" }).success).toBe(false); + expect(connectionMethodDefSchema.safeParse({ ...base, transport: "local_stdio" }).success).toBe(false); + const { credentialMinter: _minter, ...withoutMinter } = base; + expect(connectionMethodDefSchema.safeParse(withoutMinter).success).toBe(false); + }); it("requires only reviewed provider or safety-boundary configuration on the default path", () => { const required = APP_DEFINITIONS.flatMap((app) => app.methods.flatMap((method) => @@ -1483,6 +1499,11 @@ describe("AppDefinition catalog", () => { ), ).sort(); expect(required).toEqual([ + "aws:aws-access-key:accessLevel", + "aws:aws-access-key:endpointRegion", + "aws:aws-role:accessLevel", + "aws:aws-role:endpointRegion", + "aws:aws-role:roleArn", "clickhouse:mcp-oauth:serviceId", "honcho:mcp-api-key:workspaceId", "make:mcp-api-token:zone", diff --git a/packages/shared/src/app-definitions.ts b/packages/shared/src/app-definitions.ts index 6175eedde39..de39d817de0 100644 --- a/packages/shared/src/app-definitions.ts +++ b/packages/shared/src/app-definitions.ts @@ -23,6 +23,7 @@ export const CONNECTABLE_APP_SLUGS = new Set([ "notion", "paperclip-notebook", "railway", + "aws", "posthog", "linear", "google-sheets", diff --git a/packages/shared/src/app-definitions/aws.json b/packages/shared/src/app-definitions/aws.json new file mode 100644 index 00000000000..34f4845777a --- /dev/null +++ b/packages/shared/src/app-definitions/aws.json @@ -0,0 +1,254 @@ +{ + "experimentalFeatureKey": "enableAwsConnector", + "schemaVersion": 1, + "slug": "aws", + "name": "AWS", + "description": "Let agents work in an AWS account through AWS's hosted MCP server, with short-lived credentials made for each connection.", + "categories": [ + "developer" + ], + "featured": false, + "urlPatterns": [ + "https://aws-mcp.*.api.aws/*" + ], + "docsUrl": "https://docs.aws.amazon.com/agent-toolkit/latest/userguide/getting-started-aws-mcp-server.html", + "reviewedTools": { + "reviewedAt": "2026-11-18", + "sourceUrl": "https://docs.aws.amazon.com/aws-mcp/latest/userguide/understanding-mcp-server-tools.html", + "read": [ + "aws___search_documentation", + "aws___read_documentation", + "aws___retrieve_skill", + "aws___list_regions", + "aws___get_regional_availability", + "aws___get_tasks" + ], + "write": [ + "aws___run_script", + "aws___get_presigned_url" + ], + "unlisted": "write" + }, + "methods": [ + { + "key": "aws-role", + "label": "AWS role (no stored keys)", + "transport": "mcp_remote", + "auth": "api_key", + "credentialMinter": "aws_mcp", + "ownershipModes": [ + "customer" + ], + "whenToUse": "Use when this Paperclip instance has a public HTTPS address. AWS trusts this connection directly, so Paperclip stores no AWS keys.", + "defaults": { + "serverUrlTemplate": "https://aws-mcp.{endpointRegion}.api.aws/mcp", + "mcpSessionRequired": true + }, + "tenantFields": [ + { + "key": "roleArn", + "label": "Role ARN", + "type": "text", + "required": true, + "placeholder": "arn:aws:iam::123456789012:role/paperclip-agents", + "helperMd": "The role must trust this company's Paperclip identity provider for this connection only. Its permissions decide what agents can do.", + "validation": { + "pattern": "^arn:aws[a-z-]*:iam::[0-9]{12}:role/[A-Za-z0-9+=,.@_/-]{1,512}$", + "maxLength": 600 + } + }, + { + "key": "endpointRegion", + "label": "AWS MCP endpoint region", + "type": "select", + "required": true, + "defaultValue": "us-east-1", + "options": [ + { + "value": "us-east-1", + "label": "US East (N. Virginia)" + }, + { + "value": "us-west-2", + "label": "US West (Oregon)" + }, + { + "value": "eu-west-1", + "label": "Europe (Ireland)" + }, + { + "value": "eu-west-2", + "label": "Europe (London)" + }, + { + "value": "eu-central-1", + "label": "Europe (Frankfurt)" + }, + { + "value": "ap-southeast-1", + "label": "Asia Pacific (Singapore)" + }, + { + "value": "ap-southeast-2", + "label": "Asia Pacific (Sydney)" + }, + { + "value": "ap-northeast-1", + "label": "Asia Pacific (Tokyo)" + } + ], + "placeholder": "us-east-1" + }, + { + "key": "accessLevel", + "label": "Access level", + "type": "select", + "required": true, + "defaultValue": "read_only", + "options": [ + { + "value": "read_only", + "label": "Read only" + }, + { + "value": "full", + "label": "Everything the role allows" + } + ], + "helperMd": "Read only adds AWS's ReadOnlyAccess limit to every session, so AWS refuses changes even when the role allows them.", + "placeholder": "Read only" + } + ], + "guidanceMd": "Create an IAM role that trusts this company's Paperclip identity provider, limited to this connection. Attach `AWSMCPSignInOAuthAccessPolicy` and the permissions agents should have.", + "riskTier": "S4", + "consoleLinks": { + "docs": "https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html" + } + }, + { + "key": "aws-access-key", + "label": "Access key", + "transport": "mcp_remote", + "auth": "api_key", + "credentialMinter": "aws_mcp", + "ownershipModes": [ + "customer" + ], + "whenToUse": "Use when AWS cannot reach this Paperclip instance over public HTTPS, such as a local or private-network instance.", + "defaults": { + "serverUrlTemplate": "https://aws-mcp.{endpointRegion}.api.aws/mcp", + "mcpSessionRequired": true + }, + "credentialFields": [ + { + "key": "accessKeyId", + "label": "Access key ID", + "type": "text", + "required": true, + "secret": true, + "placeholder": "AKIA…", + "validation": { + "pattern": "^A[A-Z0-9]{15,127}$", + "maxLength": 128 + }, + "helperMd": "Use a dedicated IAM user for this connection. It needs AWSMCPSignInOAuthAccessPolicy, sts:GetFederationToken, and the permissions agents should have; Paperclip cannot raise them." + }, + { + "key": "secretAccessKey", + "label": "Secret access key", + "type": "password", + "required": true, + "secret": true, + "helperMd": "Use a dedicated IAM user for this connection. It needs AWSMCPSignInOAuthAccessPolicy, sts:GetFederationToken, and the permissions agents should have; Paperclip cannot raise them.", + "placeholder": "Paste the secret access key" + } + ], + "tenantFields": [ + { + "key": "roleArn", + "label": "Role ARN (optional)", + "type": "text", + "required": false, + "advanced": true, + "placeholder": "arn:aws:iam::123456789012:role/paperclip-agents", + "helperMd": "Paperclip switches into this role before each session when set.", + "validation": { + "pattern": "^arn:aws[a-z-]*:iam::[0-9]{12}:role/[A-Za-z0-9+=,.@_/-]{1,512}$", + "maxLength": 600 + } + }, + { + "key": "endpointRegion", + "label": "AWS MCP endpoint region", + "type": "select", + "required": true, + "defaultValue": "us-east-1", + "options": [ + { + "value": "us-east-1", + "label": "US East (N. Virginia)" + }, + { + "value": "us-west-2", + "label": "US West (Oregon)" + }, + { + "value": "eu-west-1", + "label": "Europe (Ireland)" + }, + { + "value": "eu-west-2", + "label": "Europe (London)" + }, + { + "value": "eu-central-1", + "label": "Europe (Frankfurt)" + }, + { + "value": "ap-southeast-1", + "label": "Asia Pacific (Singapore)" + }, + { + "value": "ap-southeast-2", + "label": "Asia Pacific (Sydney)" + }, + { + "value": "ap-northeast-1", + "label": "Asia Pacific (Tokyo)" + } + ], + "placeholder": "us-east-1" + }, + { + "key": "accessLevel", + "label": "Access level", + "type": "select", + "required": true, + "defaultValue": "read_only", + "options": [ + { + "value": "read_only", + "label": "Read only" + }, + { + "value": "full", + "label": "Everything the key allows" + } + ], + "helperMd": "Read only adds AWS's ReadOnlyAccess limit to every session, so AWS refuses changes even when the key allows them.", + "placeholder": "Read only" + } + ], + "guidanceMd": "Create a dedicated IAM user for this connection, attach `AWSMCPSignInOAuthAccessPolicy`, allow `sts:GetFederationToken`, and add the permissions agents should have.", + "riskTier": "S4", + "consoleLinks": { + "keys": "https://console.aws.amazon.com/iam/home#/users", + "docs": "https://docs.aws.amazon.com/agent-toolkit/latest/userguide/getting-started-aws-mcp-server.html" + } + } + ], + "branding": { + "logoUrl": "/brands/apps/aws.svg", + "darkLogoUrl": "/brands/apps/aws-dark.svg" + } +} diff --git a/packages/shared/src/feature-catalog.ts b/packages/shared/src/feature-catalog.ts index 37b81f802f8..35d8a9a5f5d 100644 --- a/packages/shared/src/feature-catalog.ts +++ b/packages/shared/src/feature-catalog.ts @@ -183,6 +183,13 @@ export const INSTANCE_FEATURE_CATALOG: Record; transport?:{location:"query"|"header";name:string;format?:"string"|"csv"|"boolean";omitFalse?:boolean} } /** One tool a plugin worker serves for a `transport: "plugin"` method. */ export interface PluginConnectorToolDef { name:string; displayName?:string; description?:string; risk:"read"|"write"|"destructive"; parametersSchema:Record } export type PluginConnectorTools = { kind:"static"; list:PluginConnectorToolDef[] } | { kind:"dynamic" }; -export interface ConnectionMethodDef { ai?: import("../ai-connections.js").AiConnectionMetadata; key:string; label?:string; purpose?:ToolConnectionPurpose; provider?:"slack"|"github"|"discord"|"microsoft-teams"|"telegram"|"agentmail"|"imessage-photon"|"speko"; transport:ToolConnectionTransport; settingsSchema?:Record; tools?:PluginConnectorTools; auth:"oauth"|"api_key"|"none"; oauthStrategy?:"paperclip_cloud_connector"|"paperclip_id_connector"; connectorProfile?:string; oauthClientSecretRequired?:boolean; oauthClientRegistration?:"dcr"; capabilityProfile?:{key:string;label:string;description?:string}; grantKinds?:ConnectionGrantKind[]; ownershipModes:ToolConnectionOwnership[]; whenToUse:string; defaults?:{serverUrl?:string;serverUrlTemplate?:string;discoveryUrl?:string|null;serviceHost?:string;templateKey?:string;authorizationEndpoint?:string;tokenEndpoint?:string;metadataUrl?:string;scopesHint?:string[];oauthAuthorizationParams?:{access_type?:"offline";prompt?:"consent"};toolArgumentDefaults?:Record;mcpSessionRequired?:boolean}; tenantFields?:FieldDef[]; extensionFields?:FieldDef[]; configRequirements?:{atLeastOneOf?:string[]}; credentialFields?:FieldDef[]; keyPlacement?:{location:"header"|"query"|"body_json"|"env";name:string;prefix?:string|null}; credentialSources?:{vercelConnect?:{services:string[];principalModes:VercelConnectPrincipalMode[];scopes:string[];header:{name:string;prefix?:string|null}}}; guidanceMd:string; consoleLinks?:{register?:string;keys?:string;settings?:string;docs?:string}; warnings?:string[]; variants?:Array<{key:string;label:string;whenToUse:string;tenantFields?:FieldDef[]}>; riskTier:"S1"|"S2"|"S3"|"S4"; requiredResourceFilters?:string[] } +export interface ConnectionMethodDef { ai?: import("../ai-connections.js").AiConnectionMetadata; key:string; label?:string; purpose?:ToolConnectionPurpose; provider?:"slack"|"github"|"discord"|"microsoft-teams"|"telegram"|"agentmail"|"imessage-photon"|"speko"; transport:ToolConnectionTransport; settingsSchema?:Record; tools?:PluginConnectorTools; auth:"oauth"|"api_key"|"none"; oauthStrategy?:"paperclip_cloud_connector"|"paperclip_id_connector"; connectorProfile?:string; oauthClientSecretRequired?:boolean; oauthClientRegistration?:"dcr"; capabilityProfile?:{key:string;label:string;description?:string}; grantKinds?:ConnectionGrantKind[]; ownershipModes:ToolConnectionOwnership[]; whenToUse:string; defaults?:{serverUrl?:string;serverUrlTemplate?:string;discoveryUrl?:string|null;serviceHost?:string;templateKey?:string;authorizationEndpoint?:string;tokenEndpoint?:string;metadataUrl?:string;scopesHint?:string[];oauthAuthorizationParams?:{access_type?:"offline";prompt?:"consent"};toolArgumentDefaults?:Record;mcpSessionRequired?:boolean}; tenantFields?:FieldDef[]; extensionFields?:FieldDef[]; configRequirements?:{atLeastOneOf?:string[]}; credentialFields?:FieldDef[]; keyPlacement?:{location:"header"|"query"|"body_json"|"env";name:string;prefix?:string|null}; /** The control plane mints this method's Authorization header at call time; stored credential fields are minter inputs, never headers. */ credentialMinter?:ConnectionCredentialMinter; credentialSources?:{vercelConnect?:{services:string[];principalModes:VercelConnectPrincipalMode[];scopes:string[];header:{name:string;prefix?:string|null}}}; guidanceMd:string; consoleLinks?:{register?:string;keys?:string;settings?:string;docs?:string}; warnings?:string[]; variants?:Array<{key:string;label:string;whenToUse:string;tenantFields?:FieldDef[]}>; riskTier:"S1"|"S2"|"S3"|"S4"; requiredResourceFilters?:string[] } export interface AppReviewedTools { reviewedAt:string; sourceUrl?:string; read?:string[]; write?:string[]; destructive?:string[]; unlisted?:"read"|"write"|"destructive"; quarantineNewEntries?:boolean } /** Present only on connectors a plugin provides; `slug` is then namespaced by plugin key. */ export interface AppPluginSource { pluginKey:string; appSlug:string; /** The implicit connector of legacy top-level manifest `tools`. */ legacyTools?:true } diff --git a/packages/shared/src/types/instance.ts b/packages/shared/src/types/instance.ts index 4aa67dcaadd..77b0052be0f 100644 --- a/packages/shared/src/types/instance.ts +++ b/packages/shared/src/types/instance.ts @@ -89,6 +89,8 @@ export interface InstanceExperimentalSettings { enablePaperclipNotebook: boolean; /** Show and allow the built-in Google Workspace connector while its Google verification is pending. */ enableGoogleWorkspaceConnector: boolean; + /** Show and allow the AWS connector (minted per-connection AWS credentials). */ + enableAwsConnector: boolean; enableCases: boolean; enableAgentChat: boolean; /** Reorganized left nav, Inbox-as-Tasks-views, and the chat agent rail + task cards. */ diff --git a/packages/shared/src/validators/app-definition.ts b/packages/shared/src/validators/app-definition.ts index c3f686a39ad..c97907a348e 100644 --- a/packages/shared/src/validators/app-definition.ts +++ b/packages/shared/src/validators/app-definition.ts @@ -1,5 +1,6 @@ import { z } from "zod"; import { jsonSchemaSchema } from "./json-schema.js"; +import { CONNECTION_CREDENTIAL_MINTERS } from "../types/app-definition.js"; import { INSTANCE_FEATURE_KEYS } from "../feature-catalog.js"; import { connectionInstructionTemplateSchema } from "../connection-instructions.js"; import { AI_CONNECTION_CAPABILITIES, aiConnectionMetadataSchema } from "../ai-connections.js"; @@ -59,7 +60,7 @@ export function isSupportedPluginSettingsSchema(schema:Record):b return typeof record.type==="string"&&SETTINGS_FIELD_TYPES.has(record.type)&&Object.keys(record).every((key)=>SETTINGS_FIELD_KEYS.has(key)); }); } -export const connectionMethodDefSchema=z.object({key:z.string().min(1),label:z.string().min(1).optional(),purpose:z.union([toolConnectionPurposeSchema,z.literal("ai")]).optional(),provider:z.enum(["slack","github","discord","microsoft-teams","telegram","speko","agentmail","imessage-photon"]).optional(),transport:z.union([toolConnectionTransportSchema,z.literal("runtime_auth"),z.literal("plugin")]),settingsSchema:jsonSchemaSchema.optional(),tools:pluginMethodToolsSchema.optional(),ai:aiConnectionMetadataSchema.optional(),auth:z.enum(["oauth","api_key","none"]),oauthStrategy:z.enum(["paperclip_cloud_connector","paperclip_id_connector"]).optional(),connectorProfile:z.string().regex(/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/).optional(),oauthClientSecretRequired:z.boolean().optional(),oauthClientRegistration:z.literal("dcr").optional(),capabilityProfile:z.object({key:z.string().min(1),label:z.string().min(1),description:z.string().min(1).optional()}).optional(),grantKinds:z.array(connectionGrantKindSchema).min(1).optional(),ownershipModes:z.array(toolConnectionOwnershipSchema).min(1),whenToUse:z.string().min(1),defaults:z.object({serverUrl:z.string().url().optional(),serverUrlTemplate:z.string().regex(/^https:\/\//).optional(),discoveryUrl:z.string().url().nullable().optional(),serviceHost:z.string().optional(),templateKey:z.string().optional(),authorizationEndpoint:z.string().url().optional(),tokenEndpoint:z.string().url().optional(),metadataUrl:z.string().url().optional(),scopesHint:z.array(z.string()).optional(),oauthAuthorizationParams:z.object({access_type:z.literal("offline").optional(),prompt:z.literal("consent").optional()}).optional(),toolArgumentDefaults:z.record(z.string(),z.unknown()).optional(),mcpSessionRequired:z.boolean().optional()}).optional(),tenantFields:z.array(field).optional(),extensionFields:z.array(field).optional(),configRequirements:z.object({atLeastOneOf:z.array(z.string().min(1)).min(1).optional()}).optional(),credentialFields:z.array(field).optional(),keyPlacement:z.object({location:z.enum(["header","query","body_json","env"]),name:z.string().min(1),prefix:z.string().nullable().optional()}).optional(),credentialSources:z.object({vercelConnect:z.object({services:z.array(z.string().min(1)).min(1),principalModes:z.array(z.enum(["app","user"])).min(1),scopes:z.array(z.string().min(1)).min(1),header:z.object({name:z.string().min(1),prefix:z.string().nullable().optional()})}).optional()}).optional(),guidanceMd:z.string().min(1),consoleLinks:z.object({register:z.string().url().optional(),keys:z.string().url().optional(),settings:z.string().url().optional(),docs:z.string().url().optional()}).optional(),warnings:z.array(z.string()).optional(),variants:z.array(z.object({key:z.string(),label:z.string(),whenToUse:z.string(),tenantFields:z.array(field).optional()})).optional(),riskTier:z.enum(["S1","S2","S3","S4"]),requiredResourceFilters:z.array(z.string()).optional()}).superRefine((v,c)=>{if((v.transport==="runtime_auth")!==Boolean(v.ai))c.addIssue({code:"custom",message:"Runtime authentication requires AI metadata and AI metadata requires runtime_auth",path:["ai"]});if(v.ai&&!AI_CONNECTION_CAPABILITIES[v.ai.provider].methods[v.ai.method])c.addIssue({code:"custom",message:"Unsupported AI sign-in method",path:["ai","method"]});if(v.ai&&v.auth!==(v.ai.method==="subscription"?"oauth":"api_key"))c.addIssue({code:"custom",message:"AI sign-in method must match authentication",path:["auth"]});if(v.oauthClientRegistration&&(v.auth!=="oauth"||v.transport!=="mcp_remote"||!v.ownershipModes.includes("dcr")))c.addIssue({code:"custom",message:"DCR client registration requires a remote MCP OAuth method with DCR ownership",path:["oauthClientRegistration"]});if(v.defaults?.mcpSessionRequired&&v.transport!=="mcp_remote")c.addIssue({code:"custom",message:"MCP session initialization preferences require remote MCP transport",path:["defaults","mcpSessionRequired"]});const purpose=v.purpose??"tool";if((purpose==="ai")!==(v.transport==="runtime_auth"))c.addIssue({code:"custom",message:"AI methods require runtime_auth and runtime_auth requires AI purpose",path:["purpose"]});if(["chat_sdk","voice"].includes(v.transport)&&purpose!=="channel")c.addIssue({code:"custom",message:"Chat SDK methods must be channel connections",path:["purpose"]});if(purpose==="channel"&&!["chat_sdk","voice"].includes(v.transport)&&!(v.provider==="agentmail"&&v.transport==="rest_api"))c.addIssue({code:"custom",message:"Channel connections must use the Chat SDK transport",path:["transport"]});if(purpose==="channel"&&((v.provider==="speko")!==(v.transport==="voice")))c.addIssue({code:"custom",message:"Speko channels require the voice transport",path:["transport"]});if(purpose==="channel"&&!v.provider)c.addIssue({code:"custom",message:"Channel connections require a chat provider",path:["provider"]});if((v.transport==="plugin")!==Boolean(v.tools))c.addIssue({code:"custom",message:"Plugin-served methods declare tools, and only plugin-served methods may",path:["tools"]});if(v.settingsSchema&&!isSupportedPluginSettingsSchema(v.settingsSchema))c.addIssue({code:"custom",message:"settingsSchema must be an object of simple fields (string, number, integer or boolean)",path:["settingsSchema"]});if(v.settingsSchema&&v.transport!=="plugin")c.addIssue({code:"custom",message:"settingsSchema applies only to plugin-served methods",path:["settingsSchema"]});if(v.transport==="plugin"&&(purpose!=="tool"||v.auth==="oauth"||v.oauthStrategy))c.addIssue({code:"custom",message:"Plugin-served methods provide tools with no authentication or an API key",path:["auth"]});if(v.auth==="api_key"&&!v.keyPlacement&&purpose!=="channel"&&v.transport!=="plugin")c.addIssue({code:"custom",message:"API-key tool methods require keyPlacement",path:["keyPlacement"]});if(v.oauthStrategy&&v.auth!=="oauth")c.addIssue({code:"custom",message:"OAuth strategies require OAuth auth",path:["oauthStrategy"]});if(v.oauthStrategy&&!v.connectorProfile)c.addIssue({code:"custom",message:"Paperclip Cloud connector methods require connectorProfile",path:["connectorProfile"]});if(v.connectorProfile&&!v.oauthStrategy)c.addIssue({code:"custom",message:"connectorProfile requires a Paperclip Cloud OAuth strategy",path:["connectorProfile"]});if(v.credentialSources?.vercelConnect&&(v.transport!=="mcp_remote"||v.auth==="none"))c.addIssue({code:"custom",message:"Vercel Connect requires an authenticated remote MCP method",path:["credentialSources","vercelConnect"]});const keys=new Set([...(v.tenantFields??[]),...(v.extensionFields??[])].map((entry)=>entry.key));for(const key of v.configRequirements?.atLeastOneOf??[])if(!keys.has(key))c.addIssue({code:"custom",message:"Config requirement references an unknown field",path:["configRequirements","atLeastOneOf"]});if(v.defaults?.serverUrl&&v.defaults.serverUrlTemplate)c.addIssue({code:"custom",message:"Use either serverUrl or serverUrlTemplate",path:["defaults"]});for(const placeholder of v.defaults?.serverUrlTemplate?.matchAll(/\{([a-zA-Z0-9_-]+)\}/g)??[])if(!keys.has(placeholder[1]))c.addIssue({code:"custom",message:"Server URL template references an unknown field",path:["defaults","serverUrlTemplate"]})}); +export const connectionMethodDefSchema=z.object({key:z.string().min(1),label:z.string().min(1).optional(),purpose:z.union([toolConnectionPurposeSchema,z.literal("ai")]).optional(),provider:z.enum(["slack","github","discord","microsoft-teams","telegram","speko","agentmail","imessage-photon"]).optional(),transport:z.union([toolConnectionTransportSchema,z.literal("runtime_auth"),z.literal("plugin")]),settingsSchema:jsonSchemaSchema.optional(),tools:pluginMethodToolsSchema.optional(),ai:aiConnectionMetadataSchema.optional(),auth:z.enum(["oauth","api_key","none"]),oauthStrategy:z.enum(["paperclip_cloud_connector","paperclip_id_connector"]).optional(),connectorProfile:z.string().regex(/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/).optional(),oauthClientSecretRequired:z.boolean().optional(),oauthClientRegistration:z.literal("dcr").optional(),capabilityProfile:z.object({key:z.string().min(1),label:z.string().min(1),description:z.string().min(1).optional()}).optional(),grantKinds:z.array(connectionGrantKindSchema).min(1).optional(),ownershipModes:z.array(toolConnectionOwnershipSchema).min(1),whenToUse:z.string().min(1),defaults:z.object({serverUrl:z.string().url().optional(),serverUrlTemplate:z.string().regex(/^https:\/\//).optional(),discoveryUrl:z.string().url().nullable().optional(),serviceHost:z.string().optional(),templateKey:z.string().optional(),authorizationEndpoint:z.string().url().optional(),tokenEndpoint:z.string().url().optional(),metadataUrl:z.string().url().optional(),scopesHint:z.array(z.string()).optional(),oauthAuthorizationParams:z.object({access_type:z.literal("offline").optional(),prompt:z.literal("consent").optional()}).optional(),toolArgumentDefaults:z.record(z.string(),z.unknown()).optional(),mcpSessionRequired:z.boolean().optional()}).optional(),tenantFields:z.array(field).optional(),extensionFields:z.array(field).optional(),configRequirements:z.object({atLeastOneOf:z.array(z.string().min(1)).min(1).optional()}).optional(),credentialFields:z.array(field).optional(),keyPlacement:z.object({location:z.enum(["header","query","body_json","env"]),name:z.string().min(1),prefix:z.string().nullable().optional()}).optional(),credentialMinter:z.enum(CONNECTION_CREDENTIAL_MINTERS).optional(),credentialSources:z.object({vercelConnect:z.object({services:z.array(z.string().min(1)).min(1),principalModes:z.array(z.enum(["app","user"])).min(1),scopes:z.array(z.string().min(1)).min(1),header:z.object({name:z.string().min(1),prefix:z.string().nullable().optional()})}).optional()}).optional(),guidanceMd:z.string().min(1),consoleLinks:z.object({register:z.string().url().optional(),keys:z.string().url().optional(),settings:z.string().url().optional(),docs:z.string().url().optional()}).optional(),warnings:z.array(z.string()).optional(),variants:z.array(z.object({key:z.string(),label:z.string(),whenToUse:z.string(),tenantFields:z.array(field).optional()})).optional(),riskTier:z.enum(["S1","S2","S3","S4"]),requiredResourceFilters:z.array(z.string()).optional()}).superRefine((v,c)=>{if((v.transport==="runtime_auth")!==Boolean(v.ai))c.addIssue({code:"custom",message:"Runtime authentication requires AI metadata and AI metadata requires runtime_auth",path:["ai"]});if(v.ai&&!AI_CONNECTION_CAPABILITIES[v.ai.provider].methods[v.ai.method])c.addIssue({code:"custom",message:"Unsupported AI sign-in method",path:["ai","method"]});if(v.ai&&v.auth!==(v.ai.method==="subscription"?"oauth":"api_key"))c.addIssue({code:"custom",message:"AI sign-in method must match authentication",path:["auth"]});if(v.oauthClientRegistration&&(v.auth!=="oauth"||v.transport!=="mcp_remote"||!v.ownershipModes.includes("dcr")))c.addIssue({code:"custom",message:"DCR client registration requires a remote MCP OAuth method with DCR ownership",path:["oauthClientRegistration"]});if(v.defaults?.mcpSessionRequired&&v.transport!=="mcp_remote")c.addIssue({code:"custom",message:"MCP session initialization preferences require remote MCP transport",path:["defaults","mcpSessionRequired"]});const purpose=v.purpose??"tool";if((purpose==="ai")!==(v.transport==="runtime_auth"))c.addIssue({code:"custom",message:"AI methods require runtime_auth and runtime_auth requires AI purpose",path:["purpose"]});if(["chat_sdk","voice"].includes(v.transport)&&purpose!=="channel")c.addIssue({code:"custom",message:"Chat SDK methods must be channel connections",path:["purpose"]});if(purpose==="channel"&&!["chat_sdk","voice"].includes(v.transport)&&!(v.provider==="agentmail"&&v.transport==="rest_api"))c.addIssue({code:"custom",message:"Channel connections must use the Chat SDK transport",path:["transport"]});if(purpose==="channel"&&((v.provider==="speko")!==(v.transport==="voice")))c.addIssue({code:"custom",message:"Speko channels require the voice transport",path:["transport"]});if(purpose==="channel"&&!v.provider)c.addIssue({code:"custom",message:"Channel connections require a chat provider",path:["provider"]});if((v.transport==="plugin")!==Boolean(v.tools))c.addIssue({code:"custom",message:"Plugin-served methods declare tools, and only plugin-served methods may",path:["tools"]});if(v.settingsSchema&&!isSupportedPluginSettingsSchema(v.settingsSchema))c.addIssue({code:"custom",message:"settingsSchema must be an object of simple fields (string, number, integer or boolean)",path:["settingsSchema"]});if(v.settingsSchema&&v.transport!=="plugin")c.addIssue({code:"custom",message:"settingsSchema applies only to plugin-served methods",path:["settingsSchema"]});if(v.transport==="plugin"&&(purpose!=="tool"||v.auth==="oauth"||v.oauthStrategy))c.addIssue({code:"custom",message:"Plugin-served methods provide tools with no authentication or an API key",path:["auth"]});if(v.credentialMinter&&(v.transport!=="mcp_remote"||v.auth!=="api_key"||v.keyPlacement||v.credentialSources))c.addIssue({code:"custom",message:"Minted credentials require an API-key remote MCP method without keyPlacement or another credential source",path:["credentialMinter"]});if(v.auth==="api_key"&&!v.keyPlacement&&!v.credentialMinter&&purpose!=="channel"&&v.transport!=="plugin")c.addIssue({code:"custom",message:"API-key tool methods require keyPlacement",path:["keyPlacement"]});if(v.oauthStrategy&&v.auth!=="oauth")c.addIssue({code:"custom",message:"OAuth strategies require OAuth auth",path:["oauthStrategy"]});if(v.oauthStrategy&&!v.connectorProfile)c.addIssue({code:"custom",message:"Paperclip Cloud connector methods require connectorProfile",path:["connectorProfile"]});if(v.connectorProfile&&!v.oauthStrategy)c.addIssue({code:"custom",message:"connectorProfile requires a Paperclip Cloud OAuth strategy",path:["connectorProfile"]});if(v.credentialSources?.vercelConnect&&(v.transport!=="mcp_remote"||v.auth==="none"))c.addIssue({code:"custom",message:"Vercel Connect requires an authenticated remote MCP method",path:["credentialSources","vercelConnect"]});const keys=new Set([...(v.tenantFields??[]),...(v.extensionFields??[])].map((entry)=>entry.key));for(const key of v.configRequirements?.atLeastOneOf??[])if(!keys.has(key))c.addIssue({code:"custom",message:"Config requirement references an unknown field",path:["configRequirements","atLeastOneOf"]});if(v.defaults?.serverUrl&&v.defaults.serverUrlTemplate)c.addIssue({code:"custom",message:"Use either serverUrl or serverUrlTemplate",path:["defaults"]});for(const placeholder of v.defaults?.serverUrlTemplate?.matchAll(/\{([a-zA-Z0-9_-]+)\}/g)??[])if(!keys.has(placeholder[1]))c.addIssue({code:"custom",message:"Server URL template references an unknown field",path:["defaults","serverUrlTemplate"]})}); const reviewedToolNameListSchema=z.array(z.string().min(1).max(200)).max(1000); /** * A connector's reviewed tool risk, declared as data so any connector (core or diff --git a/packages/shared/src/validators/instance.ts b/packages/shared/src/validators/instance.ts index 784b641f66b..9d09c2e2a8f 100644 --- a/packages/shared/src/validators/instance.ts +++ b/packages/shared/src/validators/instance.ts @@ -66,6 +66,7 @@ export const instanceExperimentalSettingsSchema = z.object({ enableMemoryConnectors: z.boolean().default(false), enablePaperclipNotebook: z.boolean().default(false), enableGoogleWorkspaceConnector: z.boolean().default(false), + enableAwsConnector: z.boolean().default(false), enableCases: z.boolean().default(false), enableAgentChat: z.boolean().default(true), enableCombinedInboxTasks: z.boolean().default(false), diff --git a/scripts/app-definition-overrides/aws.json b/scripts/app-definition-overrides/aws.json new file mode 100644 index 00000000000..0b108bf7e0c --- /dev/null +++ b/scripts/app-definition-overrides/aws.json @@ -0,0 +1,249 @@ +{ + "experimentalFeatureKey": "enableAwsConnector", + "schemaVersion": 1, + "slug": "aws", + "name": "AWS", + "description": "Let agents work in an AWS account through AWS's hosted MCP server, with short-lived credentials made for each connection.", + "categories": [ + "developer" + ], + "featured": false, + "urlPatterns": [ + "https://aws-mcp.*.api.aws/*" + ], + "docsUrl": "https://docs.aws.amazon.com/agent-toolkit/latest/userguide/getting-started-aws-mcp-server.html", + "reviewedTools": { + "reviewedAt": "2026-11-18", + "sourceUrl": "https://docs.aws.amazon.com/aws-mcp/latest/userguide/understanding-mcp-server-tools.html", + "read": [ + "aws___search_documentation", + "aws___read_documentation", + "aws___retrieve_skill", + "aws___list_regions", + "aws___get_regional_availability", + "aws___get_tasks" + ], + "write": [ + "aws___run_script", + "aws___get_presigned_url" + ], + "unlisted": "write" + }, + "methods": [ + { + "key": "aws-role", + "label": "AWS role (no stored keys)", + "transport": "mcp_remote", + "auth": "api_key", + "credentialMinter": "aws_mcp", + "ownershipModes": [ + "customer" + ], + "whenToUse": "Use when this Paperclip instance has a public HTTPS address. AWS trusts this connection directly, so Paperclip stores no AWS keys.", + "defaults": { + "serverUrlTemplate": "https://aws-mcp.{endpointRegion}.api.aws/mcp", + "mcpSessionRequired": true + }, + "tenantFields": [ + { + "key": "roleArn", + "label": "Role ARN", + "type": "text", + "required": true, + "placeholder": "arn:aws:iam::123456789012:role/paperclip-agents", + "helperMd": "The role must trust this company's Paperclip identity provider for this connection only. Its permissions decide what agents can do.", + "validation": { + "pattern": "^arn:aws[a-z-]*:iam::[0-9]{12}:role/[A-Za-z0-9+=,.@_/-]{1,512}$", + "maxLength": 600 + } + }, + { + "key": "endpointRegion", + "label": "AWS MCP endpoint region", + "type": "select", + "required": true, + "defaultValue": "us-east-1", + "options": [ + { + "value": "us-east-1", + "label": "US East (N. Virginia)" + }, + { + "value": "us-west-2", + "label": "US West (Oregon)" + }, + { + "value": "eu-west-1", + "label": "Europe (Ireland)" + }, + { + "value": "eu-west-2", + "label": "Europe (London)" + }, + { + "value": "eu-central-1", + "label": "Europe (Frankfurt)" + }, + { + "value": "ap-southeast-1", + "label": "Asia Pacific (Singapore)" + }, + { + "value": "ap-southeast-2", + "label": "Asia Pacific (Sydney)" + }, + { + "value": "ap-northeast-1", + "label": "Asia Pacific (Tokyo)" + } + ], + "placeholder": "us-east-1" + }, + { + "key": "accessLevel", + "label": "Access level", + "type": "select", + "required": true, + "defaultValue": "read_only", + "options": [ + { + "value": "read_only", + "label": "Read only" + }, + { + "value": "full", + "label": "Everything the role allows" + } + ], + "helperMd": "Read only adds AWS's ReadOnlyAccess limit to every session, so AWS refuses changes even when the role allows them.", + "placeholder": "Read only" + } + ], + "guidanceMd": "Create an IAM role that trusts this company's Paperclip identity provider, limited to this connection. Attach `AWSMCPSignInOAuthAccessPolicy` and the permissions agents should have.", + "riskTier": "S4", + "consoleLinks": { + "docs": "https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html" + } + }, + { + "key": "aws-access-key", + "label": "Access key", + "transport": "mcp_remote", + "auth": "api_key", + "credentialMinter": "aws_mcp", + "ownershipModes": [ + "customer" + ], + "whenToUse": "Use when AWS cannot reach this Paperclip instance over public HTTPS, such as a local or private-network instance.", + "defaults": { + "serverUrlTemplate": "https://aws-mcp.{endpointRegion}.api.aws/mcp", + "mcpSessionRequired": true + }, + "credentialFields": [ + { + "key": "accessKeyId", + "label": "Access key ID", + "type": "text", + "required": true, + "secret": true, + "placeholder": "AKIA…", + "validation": { + "pattern": "^A[A-Z0-9]{15,127}$", + "maxLength": 128 + } + }, + { + "key": "secretAccessKey", + "label": "Secret access key", + "type": "password", + "required": true, + "secret": true, + "helperMd": "Use a dedicated IAM user for this connection. It needs `AWSMCPSignInOAuthAccessPolicy`, `sts:GetFederationToken`, and the permissions agents should have.", + "placeholder": "Paste the secret access key" + } + ], + "tenantFields": [ + { + "key": "roleArn", + "label": "Role ARN (optional)", + "type": "text", + "required": false, + "advanced": true, + "placeholder": "arn:aws:iam::123456789012:role/paperclip-agents", + "helperMd": "Paperclip switches into this role before each session when set.", + "validation": { + "pattern": "^arn:aws[a-z-]*:iam::[0-9]{12}:role/[A-Za-z0-9+=,.@_/-]{1,512}$", + "maxLength": 600 + } + }, + { + "key": "endpointRegion", + "label": "AWS MCP endpoint region", + "type": "select", + "required": true, + "defaultValue": "us-east-1", + "options": [ + { + "value": "us-east-1", + "label": "US East (N. Virginia)" + }, + { + "value": "us-west-2", + "label": "US West (Oregon)" + }, + { + "value": "eu-west-1", + "label": "Europe (Ireland)" + }, + { + "value": "eu-west-2", + "label": "Europe (London)" + }, + { + "value": "eu-central-1", + "label": "Europe (Frankfurt)" + }, + { + "value": "ap-southeast-1", + "label": "Asia Pacific (Singapore)" + }, + { + "value": "ap-southeast-2", + "label": "Asia Pacific (Sydney)" + }, + { + "value": "ap-northeast-1", + "label": "Asia Pacific (Tokyo)" + } + ], + "placeholder": "us-east-1" + }, + { + "key": "accessLevel", + "label": "Access level", + "type": "select", + "required": true, + "defaultValue": "read_only", + "options": [ + { + "value": "read_only", + "label": "Read only" + }, + { + "value": "full", + "label": "Everything the key allows" + } + ], + "helperMd": "Read only adds AWS's ReadOnlyAccess limit to every session, so AWS refuses changes even when the key allows them.", + "placeholder": "Read only" + } + ], + "guidanceMd": "Create a dedicated IAM user for this connection, attach `AWSMCPSignInOAuthAccessPolicy`, allow `sts:GetFederationToken`, and add the permissions agents should have.", + "riskTier": "S4", + "consoleLinks": { + "keys": "https://console.aws.amazon.com/iam/home#/users", + "docs": "https://docs.aws.amazon.com/agent-toolkit/latest/userguide/getting-started-aws-mcp-server.html" + } + } + ] +} diff --git a/scripts/ingest-app-definitions.mjs b/scripts/ingest-app-definitions.mjs index 782ad7e03f6..2529060fadb 100644 --- a/scripts/ingest-app-definitions.mjs +++ b/scripts/ingest-app-definitions.mjs @@ -2096,6 +2096,7 @@ const validateApp = (app) => { if ( connectionMethod.auth === "api_key" && !connectionMethod.keyPlacement && + !connectionMethod.credentialMinter && (connectionMethod.purpose ?? "tool") !== "channel" ) throw new Error( diff --git a/server/package.json b/server/package.json index 8abf9dd4b86..cd8c75a7ad6 100644 --- a/server/package.json +++ b/server/package.json @@ -57,6 +57,8 @@ "@ai-sdk/openai": "4.0.86", "@ai-sdk/xai": "5.0.20", "@aws-sdk/client-s3": "^3.1141.0", + "@aws-sdk/client-signin": "^3.1171.0", + "@aws-sdk/client-sts": "^3.1171.0", "@chat-adapter/discord": "4.39.0", "@chat-adapter/github": "4.39.0", "@chat-adapter/slack": "4.39.0", @@ -68,6 +70,7 @@ "@openrouter/ai-sdk-provider": "3.1.0", "@opentelemetry/api": "^1.9.0", "@opentelemetry/otlp-transformer": "0.221.0", + "@opentelemetry/resources": "2.10.0", "@paperclipai/adapter-claude-local": "workspace:*", "@paperclipai/adapter-codex-local": "workspace:*", "@paperclipai/adapter-cursor-cloud": "workspace:*", @@ -119,8 +122,7 @@ "svix": "1.76.1", "tar-stream": "3.2.0", "ws": "^8.22.0", - "zod": "^4.6.6", - "@opentelemetry/resources": "2.10.0" + "zod": "^4.6.6" }, "bundleDependencies": [ "@agentclientprotocol/claude-agent-acp", @@ -148,12 +150,12 @@ "@types/tar-stream": "^3.1.5", "@types/ws": "^8.18.2", "cross-env": "^10.1.0", + "protobufjs": "7.6.6", "supertest": "^7.0.0", "tsx": "^4.23.15", "typescript": "^7.0.2", "vite": "^8.2.2", - "vitest": "^5.0.3", - "protobufjs": "7.6.6" + "vitest": "^5.0.3" }, "peerDependencies": { "@opentelemetry/auto-instrumentations-node": "0.79.0", diff --git a/server/src/__tests__/aws-mcp-connector.test.ts b/server/src/__tests__/aws-mcp-connector.test.ts new file mode 100644 index 00000000000..13769874d7d --- /dev/null +++ b/server/src/__tests__/aws-mcp-connector.test.ts @@ -0,0 +1,251 @@ +import { randomUUID } from "node:crypto"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { eq } from "drizzle-orm"; +import { agents, companies, companyMemberships, connectionGrants, createDb, toolConnections } from "@paperclipai/db"; +import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { toolAccessService } from "../services/tool-access.js"; +import { createToolGatewayService } from "../services/tool-gateway.js"; +import { instanceSettingsService } from "../services/instance-settings.js"; +import { AWS_MCP_READ_ONLY_SESSION_POLICIES, type AwsMcpClients } from "../services/connectors/aws/mcp-credentials.js"; +import { resetWorkloadIdentityKeyCacheForTests, workloadIdentityService } from "../services/workload-identity.js"; +import { forgetMcpHttpSessions } from "../services/mcp-http.js"; + +const actor = { actorType: "user" as const, actorId: "aws-test-user", actorSource: "local_implicit" as const }; +const ACCESS_KEY_ID = "AKIAEXAMPLE1234567"; +const SECRET_ACCESS_KEY = "fixture-secret-access-key"; +const awsTool = (name: string, readOnlyHint: boolean) => ({ name, description: name, inputSchema: { type: "object", properties: {} }, annotations: { readOnlyHint } }); + +describe("AWS connector with minted credentials", () => { + let fixture: Awaited>; + let db: ReturnType; + let keyDir: string; + + beforeAll(async () => { + keyDir = await mkdtemp(join(tmpdir(), "aws-mcp-connector-")); + vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY_FILE", join(keyDir, "key")); + vi.stubEnv("PAPERCLIP_PUBLIC_URL", "https://acme.paperclip.app"); + fixture = await startEmbeddedPostgresTestDatabase("aws-mcp-connector-"); + db = createDb(fixture.connectionString); + resetWorkloadIdentityKeyCacheForTests(); + }, 120_000); + afterAll(async () => { + await fixture?.cleanup(); + vi.unstubAllEnvs(); + if (keyDir) await rm(keyDir, { recursive: true, force: true }); + }); + + async function company() { + const [row] = await db.insert(companies).values({ name: `AWS ${randomUUID()}`, issuePrefix: `A${randomUUID().slice(0, 5)}` }).returning(); + await db.insert(companyMemberships).values({ companyId: row!.id, principalType: "user", principalId: actor.actorId, status: "active", membershipRole: "admin" }); + const [agent] = await db.insert(agents).values({ companyId: row!.id, name: "Ops agent", role: "engineer", adapterType: "process", adapterConfig: {}, runtimeConfig: {} }).returning(); + return { org: row!, agent: agent! }; + } + + function harness() { + let tokens = 0; + const session = (label: string) => ({ accessKeyId: `ASIA${label}`, secretAccessKey: "s", sessionToken: "t", expiration: new Date(Date.now() + 3_600_000) }); + const aws = { + assumeRoleWithWebIdentity: vi.fn(async (_input: Parameters[0]) => session("WEB")), + assumeRole: vi.fn(async () => session("ROLE")), + getFederationToken: vi.fn(async () => session("FED")), + createMcpToken: vi.fn(async () => ({ token: `mcp-${++tokens}`, expiresInSeconds: 3599 })), + } satisfies AwsMcpClients; + const requests: { url: string; method: string; headers: Headers }[] = []; + const rejected = new Set(); + const send = async (url: string, init: RequestInit) => { + const body = JSON.parse(String(init.body)); + const headers = new Headers(init.headers); + requests.push({ url, method: body.method, headers }); + const authorization = headers.get("authorization") ?? ""; + if (!authorization.startsWith("Bearer mcp-") || rejected.has(authorization)) { + return new Response(JSON.stringify({ error: "invalid_token" }), { status: 401 }); + } + if (body.method === "initialize") return Response.json({ id: body.id, jsonrpc: "2.0", result: { protocolVersion: "2025-06-18", capabilities: {} } }, { headers: { "Mcp-Session-Id": `s-${authorization}` } }); + if (body.method === "notifications/initialized") return new Response(null, { status: 202 }); + // Like AWS's server: tool calls only work inside an initialized MCP session. + if (body.method === "tools/call" && !headers.get("mcp-session-id")) { + return Response.json({ id: body.id, jsonrpc: "2.0", error: { code: -32600, message: "Session ID is required for this operation." } }); + } + if (body.method === "tools/list") return Response.json({ id: body.id, jsonrpc: "2.0", result: { tools: [awsTool("aws___run_script", false), awsTool("aws___list_regions", true)] } }); + return Response.json({ id: body.id, jsonrpc: "2.0", result: { content: [{ type: "text", text: "regions" }] } }); + }; + const common = { deploymentMode: "local_trusted" as const, deploymentExposure: "private" as const, remoteHttpEndpointLookup: async () => [{ address: "8.8.8.8", family: 4 as const }], remoteHttpRequest: send, awsMcpClients: aws }; + return { aws, requests, rejected, service: toolAccessService(db, common), gateway: createToolGatewayService(db, { ...common, toolActionSigningSecret: "fixture-signing-key" }) }; + } + + it("stays unavailable until the experimental setting is on", async () => { + const { org } = await company(); + const { service } = harness(); + await instanceSettingsService(db).updateExperimental({ enableAwsConnector: false }); + await expect(service.connectGalleryApp(org.id, { + galleryKey: "aws", connectionMethodKey: "aws-access-key", + configValues: { endpointRegion: "us-east-1", accessLevel: "read_only" }, + credentialValues: { "credentials.accessKeyId": ACCESS_KEY_ID, "credentials.secretAccessKey": SECRET_ACCESS_KEY }, + }, actor)).rejects.toThrow(); + }); + + it("access key: lists and calls tools with a minted token, never sending the stored key", async () => { + await instanceSettingsService(db).updateExperimental({ enableAwsConnector: true }); + const { org, agent } = await company(); + const { service, gateway, aws, requests, rejected } = harness(); + const connected = await service.connectGalleryApp(org.id, { + galleryKey: "aws", connectionMethodKey: "aws-access-key", + configValues: { endpointRegion: "eu-west-1", accessLevel: "read_only" }, + credentialValues: { "credentials.accessKeyId": ACCESS_KEY_ID, "credentials.secretAccessKey": SECRET_ACCESS_KEY }, + }, actor); + expect(connected.catalog.map((entry) => entry.toolName).sort()).toEqual(["aws___list_regions", "aws___run_script"]); + expect(requests[0]!.url).toBe("https://aws-mcp.eu-west-1.api.aws/mcp"); + expect(aws.getFederationToken).toHaveBeenCalledWith(expect.objectContaining({ + region: "eu-west-1", credentials: { accessKeyId: ACCESS_KEY_ID, secretAccessKey: SECRET_ACCESS_KEY }, + policyArns: AWS_MCP_READ_ONLY_SESSION_POLICIES, + })); + for (const request of requests) { + const sent = JSON.stringify([...request.headers.entries()]); + expect(sent).not.toContain(ACCESS_KEY_ID); + expect(sent).not.toContain(SECRET_ACCESS_KEY); + } + const [row] = await db.select().from(toolConnections).where(eq(toolConnections.id, connected.connectionId)); + expect(JSON.stringify(row!.config)).not.toContain(SECRET_ACCESS_KEY); + expect(row!.credentialRefs.filter((ref) => ref.placement === "header")).toEqual([]); + + await service.finishGalleryAppConnection(org.id, connected.connectionId, { + enabledCatalogEntryIds: connected.catalog.map((entry) => entry.id), askFirstCatalogEntryIds: [], access: "all_agents", + }, actor); + const call = () => gateway.executeTestCall({ companyId: org.id, connectionId: connected.connectionId, agentId: agent.id, userId: actor.actorId, toolName: "aws___list_regions", parameters: {} }); + const mintsAfterSetup = aws.createMcpToken.mock.calls.length; + expect(await call()).toMatchObject({ decision: "allowed", result: { data: { isError: false } } }); + // The first agent call reuses the token minted while setup listed the tools. + expect(aws.createMcpToken.mock.calls.length).toBe(mintsAfterSetup); + const mintsBefore = aws.createMcpToken.mock.calls.length; + expect(await call()).toMatchObject({ decision: "allowed" }); + expect(aws.createMcpToken.mock.calls.length).toBe(mintsBefore); + + // AWS refuses the cached token: Paperclip mints a fresh one, never replays the call, and the retry works. + const lastAuthorization = requests.at(-1)!.headers.get("authorization")!; + rejected.add(lastAuthorization); + const toolCalls = () => requests.filter((request) => request.method === "tools/call").length; + const callsBefore = toolCalls(); + expect(await call()).toMatchObject({ error: { reasonCode: "credentials_refreshed_retry_required", message: expect.stringContaining("AWS refused the saved credentials") } }); + expect(toolCalls()).toBe(callsBefore + 1); + expect(aws.createMcpToken.mock.calls.length).toBe(mintsBefore + 1); + expect(await call()).toMatchObject({ decision: "allowed", result: { data: { isError: false } } }); + expect(requests.at(-1)!.headers.get("authorization")).not.toBe(lastAuthorization); + }); + + it("a shared connection never reads a personal grant's keys", async () => { + await instanceSettingsService(db).updateExperimental({ enableAwsConnector: true }); + const { org } = await company(); + const { service, aws } = harness(); + const connected = await service.connectGalleryApp(org.id, { + galleryKey: "aws", connectionMethodKey: "aws-access-key", + configValues: { endpointRegion: "us-east-1", accessLevel: "full" }, + credentialValues: { "credentials.accessKeyId": ACCESS_KEY_ID, "credentials.secretAccessKey": SECRET_ACCESS_KEY }, + }, actor); + const [organization] = await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, connected.connectionId)); + // A leftover personal grant for the same person, with refs that are not the organization's keys. + await db.insert(connectionGrants).values({ + companyId: org.id, connectionId: connected.connectionId, kind: "user", subjectUserId: actor.actorId, status: "active", + credentialSecretRefs: [{ secretId: randomUUID(), versionSelector: "latest", configPath: "credentials.accessKeyId" }], + }); + await service.checkHealth(connected.connectionId, actor); + expect(aws.createMcpToken).toHaveBeenLastCalledWith(expect.objectContaining({ + credentials: { accessKeyId: ACCESS_KEY_ID, secretAccessKey: SECRET_ACCESS_KEY }, + })); + expect(organization!.kind).toBe("organization"); + }); + + it("access key: a personal connection reads its owner's keys", async () => { + await instanceSettingsService(db).updateExperimental({ enableAwsConnector: true }); + const { org } = await company(); + const { service, aws } = harness(); + const connected = await service.connectGalleryApp(org.id, { + galleryKey: "aws", connectionMethodKey: "aws-access-key", grantKind: "user", + configValues: { endpointRegion: "us-east-1", accessLevel: "full" }, + credentialValues: { "credentials.accessKeyId": ACCESS_KEY_ID, "credentials.secretAccessKey": SECRET_ACCESS_KEY }, + }, actor); + expect(connected.catalog).toHaveLength(2); + expect(aws.createMcpToken).toHaveBeenCalledWith(expect.objectContaining({ + credentials: { accessKeyId: ACCESS_KEY_ID, secretAccessKey: SECRET_ACCESS_KEY }, + })); + }); + + it("mints a fresh token when AWS refuses the cached one while opening an MCP session", async () => { + await instanceSettingsService(db).updateExperimental({ enableAwsConnector: true }); + const { org, agent } = await company(); + const { service, gateway, aws, requests, rejected } = harness(); + const connected = await service.connectGalleryApp(org.id, { + galleryKey: "aws", connectionMethodKey: "aws-access-key", + configValues: { endpointRegion: "us-east-1", accessLevel: "full" }, + credentialValues: { "credentials.accessKeyId": ACCESS_KEY_ID, "credentials.secretAccessKey": SECRET_ACCESS_KEY }, + }, actor); + await service.finishGalleryAppConnection(org.id, connected.connectionId, { + enabledCatalogEntryIds: connected.catalog.map((entry) => entry.id), askFirstCatalogEntryIds: [], access: "all_agents", + }, actor); + const call = () => gateway.executeTestCall({ companyId: org.id, connectionId: connected.connectionId, agentId: agent.id, userId: actor.actorId, toolName: "aws___list_regions", parameters: {} }); + expect(await call()).toMatchObject({ decision: "allowed" }); + // AWS stops accepting the cached token, and the MCP session is gone, so the next call starts by opening a session. + for (const request of requests) rejected.add(request.headers.get("authorization") ?? ""); + forgetMcpHttpSessions(connected.connectionId); + const mintsBefore = aws.createMcpToken.mock.calls.length; + const initializesBefore = requests.filter((request) => request.method === "initialize").length; + expect(await call()).toMatchObject({ decision: "allowed", result: { data: { isError: false } } }); + expect(aws.createMcpToken.mock.calls.length).toBe(mintsBefore + 1); + expect(requests.filter((request) => request.method === "initialize").length).toBe(initializesBefore + 2); + }); + + it("role: proves the connection with a Paperclip-signed token and reports AWS refusals plainly", async () => { + await instanceSettingsService(db).updateExperimental({ enableAwsConnector: true }); + const { org } = await company(); + const { service, aws, requests, rejected } = harness(); + const roleInput = { + galleryKey: "aws", connectionMethodKey: "aws-role", + configValues: { roleArn: "arn:aws:iam::123456789012:role/paperclip-agents", endpointRegion: "us-east-1", accessLevel: "full" }, + }; + // The role must trust a connection that already exists, so setup saves a draft first without contacting AWS, + // and publishes the company's issuer so AWS can validate it when the customer registers it. + const draft = await service.connectGalleryApp(org.id, { ...roleInput, saveDraft: true }, actor); + expect(draft.catalog).toEqual([]); + expect(aws.assumeRoleWithWebIdentity).not.toHaveBeenCalled(); + expect(await workloadIdentityService(db).publicKeySet(org.id)).not.toBeNull(); + const connected = await service.connectGalleryApp(org.id, { ...roleInput, resumeConnectionId: draft.connectionId }, actor); + expect(connected.connectionId).toBe(draft.connectionId); + expect(connected.catalog).toHaveLength(2); + const [recorded] = await db.select().from(toolConnections).where(eq(toolConnections.id, connected.connectionId)); + expect(recorded!.config.workloadIdentityIssuer).toBe(`https://acme.paperclip.app/oidc/companies/${org.id}`); + const call = aws.assumeRoleWithWebIdentity.mock.calls[0]![0]; + expect(call).toMatchObject({ region: "us-east-1", roleArn: "arn:aws:iam::123456789012:role/paperclip-agents", policyArns: undefined }); + const claims = JSON.parse(Buffer.from(call.webIdentityToken.split(".")[1]!, "base64url").toString("utf8")); + expect(claims).toMatchObject({ + iss: `https://acme.paperclip.app/oidc/companies/${org.id}`, + sub: `connection:${connected.connectionId}`, + aud: "sts.amazonaws.com", + }); + + // AWS stops accepting the cached token and the role no longer trusts this connection. + for (const request of requests) rejected.add(request.headers.get("authorization") ?? ""); + aws.assumeRoleWithWebIdentity.mockRejectedValueOnce(Object.assign(new Error("arn:aws:iam::123456789012:role/x is not authorized"), { name: "AccessDenied", $metadata: { httpStatusCode: 403 } })); + const health = await service.checkHealth(connected.connectionId, actor).catch((error: unknown) => error); + const [row] = await db.select().from(toolConnections).where(eq(toolConnections.id, connected.connectionId)); + expect(row!.healthMessage ?? JSON.stringify(health)).toContain("AWS refused this connection's role"); + expect(row!.healthMessage ?? "").not.toContain("123456789012"); + + // The instance's address changes: Paperclip stops with a clear message instead of a role refusal from AWS. + vi.stubEnv("PAPERCLIP_PUBLIC_URL", "https://renamed.paperclip.app"); + try { + for (const request of requests) rejected.add(request.headers.get("authorization") ?? ""); + await service.checkHealth(connected.connectionId, actor).catch(() => undefined); + const [moved] = await db.select().from(toolConnections).where(eq(toolConnections.id, connected.connectionId)); + expect(moved!.healthMessage).toContain("address changed"); + // After the administrator registers the new address in AWS, reconnecting records it and works again. + const reconnected = await service.connectGalleryApp(org.id, { ...roleInput, reconnectConnectionId: connected.connectionId }, actor); + expect(reconnected.catalog).toHaveLength(2); + const [restored] = await db.select().from(toolConnections).where(eq(toolConnections.id, connected.connectionId)); + expect(restored!.config.workloadIdentityIssuer).toBe(`https://renamed.paperclip.app/oidc/companies/${org.id}`); + } finally { + vi.stubEnv("PAPERCLIP_PUBLIC_URL", "https://acme.paperclip.app"); + } + }); +}); diff --git a/server/src/__tests__/instance-settings-service.test.ts b/server/src/__tests__/instance-settings-service.test.ts index cb06deb89b7..2b42f241364 100644 --- a/server/src/__tests__/instance-settings-service.test.ts +++ b/server/src/__tests__/instance-settings-service.test.ts @@ -140,6 +140,7 @@ describe("instance settings service", () => { enableMemoryConnectors: false, enablePaperclipNotebook: false, enableGoogleWorkspaceConnector: false, + enableAwsConnector: false, enableConferenceRoomChat: false, enableClassicTaskInterface: false, enableLegacyComposerSubmit: false, diff --git a/server/src/__tests__/workload-identity.test.ts b/server/src/__tests__/workload-identity.test.ts index baa94d00e9c..70db716529c 100644 --- a/server/src/__tests__/workload-identity.test.ts +++ b/server/src/__tests__/workload-identity.test.ts @@ -74,7 +74,7 @@ describe("company workload identity issuer", () => { return id; } - async function connection(companyId: string, state: { status?: "draft" | "active" | "disabled"; enabled?: boolean } = {}) { + async function connection(companyId: string, state: { status?: "draft" | "active" | "disabled" | "archived"; enabled?: boolean } = {}) { const [application] = await db.insert(toolApplications).values({ companyId, applicationKey: `aws-${randomUUID()}`, name: `AWS ${randomUUID().slice(0, 8)}`, type: "mcp_http", status: "active", }).returning(); @@ -273,13 +273,16 @@ describe("company workload identity issuer", () => { ))).toHaveLength(0); }); - it("stops issuing tokens for a disabled, draft or switched-off connection", async () => { + it("stops issuing tokens for a disabled, archived or switched-off connection, but lets setup test a draft", async () => { const companyId = await company(); - for (const state of [{ status: "disabled" as const }, { status: "draft" as const }, { enabled: false }]) { + for (const state of [{ status: "disabled" as const }, { status: "archived" as const }, { enabled: false }]) { const connectionId = await connection(companyId, state); await expect(service().signConnectionToken({ companyId, connectionId, audience: "sts.amazonaws.com" })) .rejects.toMatchObject({ status: 422, details: { code: "workload_identity_connection_inactive" } }); } + const draft = await connection(companyId, { status: "draft", enabled: false }); + expect((await service().signConnectionToken({ companyId, connectionId: draft, audience: "sts.amazonaws.com" })).subject) + .toBe(`connection:${draft}`); }); it("writes a rotation's activity entry only when the key change commits", async () => { diff --git a/server/src/services/cloud-instance.ts b/server/src/services/cloud-instance.ts index ef5da0f11a8..36bb46c7466 100644 --- a/server/src/services/cloud-instance.ts +++ b/server/src/services/cloud-instance.ts @@ -20,6 +20,7 @@ const CLOUD_STAGING_EXPERIMENTAL_KEYS: ReadonlySet = new Set([ "enableFirstTaskPlanProposal", "enableGitHubReviewBots", "enableGoogleWorkspaceConnector", + "enableAwsConnector", "enableGoalsSidebarLink", "enableGrokBot", "enableIsolatedWorkspaces", diff --git a/server/src/services/connectors/aws/mcp-credentials.test.ts b/server/src/services/connectors/aws/mcp-credentials.test.ts new file mode 100644 index 00000000000..f0519b19a79 --- /dev/null +++ b/server/src/services/connectors/aws/mcp-credentials.test.ts @@ -0,0 +1,198 @@ +import { describe, expect, it, vi } from "vitest"; +import { + AWS_MCP_READ_ONLY_SESSION_POLICIES, + AwsMcpCredentialError, + awsMcpSettings, + awsSessionName, + classifyAwsMcpError, + createAwsMcpCredentialMinter, + isAwsMcpConnection, + type AwsMcpClients, + type AwsMcpMintInput, + type AwsMcpSettings, +} from "./mcp-credentials.js"; + +function fakeAws(overrides: Partial = {}) { + let tokens = 0; + const session = (label: string) => ({ accessKeyId: `ASIA${label}`, secretAccessKey: "secret", sessionToken: "session", expiration: new Date(Date.now() + 3600_000) }); + const clients = { + assumeRoleWithWebIdentity: vi.fn(async () => session("WEB")), + assumeRole: vi.fn(async () => session("ROLE")), + getFederationToken: vi.fn(async () => session("FED")), + createMcpToken: vi.fn(async () => ({ token: `mcp-token-${++tokens}`, expiresInSeconds: 3599 })), + ...overrides, + } satisfies AwsMcpClients; + return clients; +} + +const roleSettings: AwsMcpSettings = { method: "aws-role", roleArn: "arn:aws:iam::123456789012:role/agents", endpointRegion: "us-east-1", accessLevel: "read_only" }; +const keySettings: AwsMcpSettings = { method: "aws-access-key", roleArn: null, endpointRegion: "eu-west-1", accessLevel: "read_only" }; + +function input(settings: AwsMcpSettings, extra: Partial = {}): AwsMcpMintInput { + return { + companyId: "company-1", connectionId: "connection-1", connectionName: "AWS Prod", grantId: "grant-1", + revision: "r1", settings, + readSecret: async (path) => (path === "credentials.accessKeyId" ? "AKIAEXAMPLE" : "stored-secret"), + ...extra, + }; +} + +describe("AWS MCP credential minter", () => { + it("passes the issuer recorded at setup to the signer", async () => { + const sign = vi.fn(async () => ({ token: "jwt" })); + const minter = createAwsMcpCredentialMinter({ clients: fakeAws(), signConnectionToken: sign }); + await minter.authorizationHeader(input(roleSettings, { expectedIssuer: "https://a.example/oidc/companies/c" })); + expect(sign).toHaveBeenCalledWith(expect.objectContaining({ expectedIssuer: "https://a.example/oidc/companies/c" })); + }); + + it("role method: signs a connection token for STS and limits read-only sessions", async () => { + const clients = fakeAws(); + const sign = vi.fn(async () => ({ token: "paperclip-jwt" })); + const minter = createAwsMcpCredentialMinter({ clients, signConnectionToken: sign }); + expect(await minter.authorizationHeader(input(roleSettings))).toEqual({ Authorization: "Bearer mcp-token-1" }); + expect(sign).toHaveBeenCalledWith({ companyId: "company-1", connectionId: "connection-1", audience: "sts.amazonaws.com", expectedIssuer: undefined }); + expect(clients.assumeRoleWithWebIdentity).toHaveBeenCalledWith({ + region: "us-east-1", roleArn: roleSettings.roleArn, sessionName: "paperclip-aws-prod", + webIdentityToken: "paperclip-jwt", policyArns: AWS_MCP_READ_ONLY_SESSION_POLICIES, signal: expect.any(AbortSignal), + }); + expect(clients.createMcpToken).toHaveBeenCalledWith({ region: "us-east-1", credentials: expect.objectContaining({ accessKeyId: "ASIAWEB" }), signal: expect.any(AbortSignal) }); + + await minter.authorizationHeader(input({ ...roleSettings, accessLevel: "full" }, { connectionId: "connection-2" })); + expect(clients.assumeRoleWithWebIdentity).toHaveBeenLastCalledWith(expect.objectContaining({ policyArns: undefined })); + }); + + it("access-key method: federation token for read only, the key itself for full, AssumeRole with a role", async () => { + const clients = fakeAws(); + const sign = vi.fn(); + const minter = createAwsMcpCredentialMinter({ clients, signConnectionToken: sign }); + await minter.authorizationHeader(input(keySettings)); + expect(clients.getFederationToken).toHaveBeenCalledWith({ + region: "eu-west-1", credentials: { accessKeyId: "AKIAEXAMPLE", secretAccessKey: "stored-secret" }, + name: "paperclip-aws-prod", policyArns: AWS_MCP_READ_ONLY_SESSION_POLICIES, signal: expect.any(AbortSignal), + }); + expect(clients.createMcpToken).toHaveBeenLastCalledWith({ region: "eu-west-1", credentials: expect.objectContaining({ accessKeyId: "ASIAFED" }), signal: expect.any(AbortSignal) }); + + await minter.authorizationHeader(input({ ...keySettings, accessLevel: "full" }, { connectionId: "c-full" })); + expect(clients.createMcpToken).toHaveBeenLastCalledWith({ region: "eu-west-1", credentials: { accessKeyId: "AKIAEXAMPLE", secretAccessKey: "stored-secret" }, signal: expect.any(AbortSignal) }); + + await minter.authorizationHeader(input({ ...keySettings, roleArn: "arn:aws:iam::123456789012:role/x" }, { connectionId: "c-role" })); + expect(clients.assumeRole).toHaveBeenCalledWith(expect.objectContaining({ + roleArn: "arn:aws:iam::123456789012:role/x", policyArns: AWS_MCP_READ_ONLY_SESSION_POLICIES, + })); + expect(sign).not.toHaveBeenCalled(); + }); + + it("caches per connection and grant, and mints again on edit, forced refresh, expiry or eviction", async () => { + let clock = Date.now(); + const clients = fakeAws(); + const minter = createAwsMcpCredentialMinter({ clients, signConnectionToken: async () => ({ token: "jwt" }), now: () => clock }); + const header = () => minter.authorizationHeader(input(roleSettings)).then((h) => h.Authorization); + expect(await header()).toBe("Bearer mcp-token-1"); + expect(await header()).toBe("Bearer mcp-token-1"); + expect(clients.createMcpToken).toHaveBeenCalledTimes(1); + + expect((await minter.authorizationHeader(input(roleSettings, { revision: "r2" }))).Authorization).toBe("Bearer mcp-token-2"); + expect((await minter.authorizationHeader(input(roleSettings, { revision: "r2", forceRefresh: true }))).Authorization).toBe("Bearer mcp-token-3"); + + clock += 56 * 60 * 1000; // past the 55-minute refresh point + expect((await minter.authorizationHeader(input(roleSettings, { revision: "r2" }))).Authorization).toBe("Bearer mcp-token-4"); + + minter.evict("company-1", "connection-1"); + expect((await minter.authorizationHeader(input(roleSettings, { revision: "r2" }))).Authorization).toBe("Bearer mcp-token-5"); + expect((await minter.authorizationHeader(input(roleSettings, { grantId: "grant-2", revision: "r2" }))).Authorization).toBe("Bearer mcp-token-6"); + }); + + it("keeps only live tokens: an expired token is pruned when the next one is stored", async () => { + let clock = Date.now(); + const minter = createAwsMcpCredentialMinter({ clients: fakeAws(), signConnectionToken: async () => ({ token: "jwt" }), now: () => clock }); + await minter.authorizationHeader(input(roleSettings, { connectionId: "old" })); + expect(minter.cachedTokenCount()).toBe(1); + clock += 56 * 60 * 1000; + await minter.authorizationHeader(input(roleSettings, { connectionId: "new" })); + expect(minter.cachedTokenCount()).toBe(1); + }); + + it("shares one mint between concurrent callers", async () => { + let release!: () => void; + const gate = new Promise((resolve) => { release = resolve; }); + const clients = fakeAws({ createMcpToken: vi.fn(async () => { await gate; return { token: "only", expiresInSeconds: 3599 }; }) }); + const minter = createAwsMcpCredentialMinter({ clients, signConnectionToken: async () => ({ token: "jwt" }) }); + const calls = Array.from({ length: 5 }, () => minter.authorizationHeader(input(roleSettings))); + release(); + expect(new Set((await Promise.all(calls)).map((h) => h.Authorization))).toEqual(new Set(["Bearer only"])); + expect(clients.createMcpToken).toHaveBeenCalledTimes(1); + }); + + it("stops waiting for a stalled AWS request, aborts it, and lets the next call try again", async () => { + let aborted = false; + let stall = true; + const clients = fakeAws({ + assumeRoleWithWebIdentity: vi.fn((input: { signal?: AbortSignal }) => { + if (!stall) return Promise.resolve({ accessKeyId: "ASIAOK", secretAccessKey: "s", sessionToken: "t" }); + return new Promise(() => { input.signal?.addEventListener("abort", () => { aborted = true; }); }); + }), + }); + const minter = createAwsMcpCredentialMinter({ clients, signConnectionToken: async () => ({ token: "jwt" }), stepTimeoutMs: 50 }); + const callers = [minter.authorizationHeader(input(roleSettings)), minter.authorizationHeader(input(roleSettings))]; + for (const caller of callers) await expect(caller).rejects.toMatchObject({ code: "aws_unavailable", status: 503, health: "degraded" }); + expect(aborted).toBe(true); + stall = false; + expect(await minter.authorizationHeader(input(roleSettings))).toEqual({ Authorization: "Bearer mcp-token-1" }); + }); + + it("maps AWS failures to stable codes and messages without AWS's own text", async () => { + const awsError = (name: string, httpStatusCode: number) => + Object.assign(new Error(`AWS says arn:aws:iam::123456789012:role/secret-name ${name}`), { name, $metadata: { httpStatusCode } }); + const denied = createAwsMcpCredentialMinter({ + clients: fakeAws({ assumeRoleWithWebIdentity: vi.fn(async () => { throw awsError("AccessDenied", 403); }) }), + signConnectionToken: async () => ({ token: "jwt" }), + }); + const error = await denied.authorizationHeader(input(roleSettings)).catch((e) => e); + expect(error).toMatchObject({ code: "aws_role_access_denied", status: 403, health: "error", awsErrorName: "AccessDenied" }); + expect(error.message).not.toContain("123456789012"); + + expect(classifyAwsMcpError("signin", awsError("UnauthorizedException", 401))).toMatchObject({ code: "aws_mcp_signin_denied", status: 403 }); + expect(classifyAwsMcpError("access_key", awsError("InvalidClientTokenId", 403))).toMatchObject({ code: "aws_access_key_invalid" }); + expect(classifyAwsMcpError("federation", awsError("AccessDenied", 403)).message).toContain("sts:GetFederationToken"); + expect(classifyAwsMcpError("role", awsError("ServiceUnavailable", 503))).toMatchObject({ code: "aws_unavailable", status: 503, health: "degraded" }); + expect(classifyAwsMcpError("role", awsError("Throttling", 400))).toMatchObject({ code: "aws_unavailable" }); + expect(classifyAwsMcpError("identity", Object.assign(new Error("x"), { details: { code: "workload_identity_unavailable" } }))) + .toMatchObject({ code: "aws_identity_unavailable", status: 422 }); + expect(classifyAwsMcpError("identity", Object.assign(new Error("x"), { details: { code: "workload_identity_issuer_changed" } }))) + .toMatchObject({ code: "aws_issuer_changed", status: 409, message: expect.stringContaining("address changed") }); + + const failing = createAwsMcpCredentialMinter({ + clients: fakeAws({ createMcpToken: vi.fn(async () => { throw awsError("UnauthorizedException", 401); }) }), + signConnectionToken: async () => ({ token: "jwt" }), + }); + await expect(failing.authorizationHeader(input(roleSettings))).rejects.toBeInstanceOf(AwsMcpCredentialError); + // A failed mint is not cached: the next call tries AWS again. + await expect(failing.authorizationHeader(input(roleSettings))).rejects.toMatchObject({ code: "aws_mcp_signin_denied" }); + }); + + it("accepts only AWS's endpoint for the saved region and valid role ARNs", () => { + const connection = (config: Record) => ({ id: "c", transport: "mcp_remote", config: { + sourceTemplateKey: "aws", connectionMethodKey: "aws-role", url: "https://aws-mcp.us-east-1.api.aws/mcp", + methodConfig: { roleArn: "arn:aws:iam::123456789012:role/agents", endpointRegion: "us-east-1", accessLevel: "full" }, ...config, + } }); + expect(isAwsMcpConnection(connection({}))).toBe(true); + expect(isAwsMcpConnection(connection({ connectionMethodKey: "other" }))).toBe(false); + // Detection follows the method's credentialMinter declaration, not a hard-coded list. + expect(isAwsMcpConnection(connection({ sourceTemplateKey: "pagerduty", connectionMethodKey: "mcp-api-key-us" }))).toBe(false); + expect(isAwsMcpConnection({ ...connection({}), transport: "local_stdio" })).toBe(false); + expect(awsMcpSettings(connection({}))).toEqual({ method: "aws-role", roleArn: "arn:aws:iam::123456789012:role/agents", endpointRegion: "us-east-1", accessLevel: "full" }); + expect(() => awsMcpSettings(connection({ url: "https://evil.example.com/mcp" }))).toThrow(AwsMcpCredentialError); + expect(() => awsMcpSettings(connection({ url: "https://aws-mcp.eu-west-1.api.aws/mcp" }))).toThrow(AwsMcpCredentialError); + expect(() => awsMcpSettings(connection({ methodConfig: { roleArn: "not-an-arn", endpointRegion: "us-east-1" } }))).toThrow(AwsMcpCredentialError); + expect(() => awsMcpSettings(connection({ methodConfig: { endpointRegion: "us-east-1" } }))).toThrow(AwsMcpCredentialError); + // An unknown access level is treated as read only, never as full. + expect(awsMcpSettings(connection({ methodConfig: { roleArn: "arn:aws:iam::123456789012:role/agents", endpointRegion: "us-east-1", accessLevel: "admin" } })).accessLevel).toBe("read_only"); + }); + + it("builds session names STS accepts", () => { + expect(awsSessionName("AWS Prod (us)")).toBe("paperclip-aws-prod-us"); + expect(awsSessionName("!!!")).toBe("paperclip-connection"); + expect(awsSessionName("x".repeat(200))).toHaveLength(64); + expect(awsSessionName("x".repeat(200), 32)).toHaveLength(32); + }); +}); diff --git a/server/src/services/connectors/aws/mcp-credentials.ts b/server/src/services/connectors/aws/mcp-credentials.ts new file mode 100644 index 00000000000..1954e1a2ef4 --- /dev/null +++ b/server/src/services/connectors/aws/mcp-credentials.ts @@ -0,0 +1,489 @@ +import { createHash } from "node:crypto"; +import { + AssumeRoleCommand, + AssumeRoleWithWebIdentityCommand, + GetFederationTokenCommand, + STSClient, +} from "@aws-sdk/client-sts"; +import { CreateOAuth2TokenWithIAMCommand, SigninClient } from "@aws-sdk/client-signin"; +import { getConnectableAppDefinition } from "@paperclipai/shared"; + +/** + * Credentials for AWS's hosted MCP server, minted on the control plane for each + * connection. A connection proves who it is with a Paperclip-signed OIDC token + * (role method) or its own stored access key, gets short-lived AWS credentials, + * and exchanges them for a one-hour MCP bearer token. Agents never see any of it. + */ + +export const AWS_MCP_SOURCE_TEMPLATE_KEY = "aws"; +/** The `credentialMinter` value AWS methods declare in their app definition. */ +export const AWS_MCP_CREDENTIAL_MINTER = "aws_mcp"; +export const AWS_MCP_METHOD_KEYS = ["aws-role", "aws-access-key"] as const; +export type AwsMcpMethodKey = (typeof AWS_MCP_METHOD_KEYS)[number]; +export const AWS_MCP_ENDPOINT_REGIONS = [ + "us-east-1", "us-west-2", "eu-west-1", "eu-west-2", "eu-central-1", + "ap-southeast-1", "ap-southeast-2", "ap-northeast-1", +] as const; +export const AWS_MCP_STS_AUDIENCE = "sts.amazonaws.com"; +export const AWS_MCP_TOKEN_RESOURCE = "aws-mcp.amazonaws.com"; +/** Read-only sessions also need the sign-in policy, or AWS refuses the token exchange. */ +export const AWS_MCP_READ_ONLY_SESSION_POLICIES = [ + "arn:aws:iam::aws:policy/ReadOnlyAccess", + "arn:aws:iam::aws:policy/AWSMCPSignInOAuthAccessPolicy", +] as const; +export const AWS_MCP_ACCESS_KEY_ID_PATH = "credentials.accessKeyId"; +export const AWS_MCP_SECRET_ACCESS_KEY_PATH = "credentials.secretAccessKey"; +const SESSION_SECONDS = 3600; +/** Each AWS request in a mint must finish within this, so a stalled AWS never holds a tool call. */ +const DEFAULT_STEP_TIMEOUT_MS = 10_000; +/** Mint again this long before the token expires, so an in-flight call never carries an expiring token. */ +const REFRESH_MARGIN_MS = 5 * 60 * 1000; +const ROLE_ARN_PATTERN = /^arn:aws[a-z-]*:iam::[0-9]{12}:role\/[A-Za-z0-9+=,.@_/-]{1,512}$/; + +export type AwsMcpAccessLevel = "read_only" | "full"; + +export interface AwsMcpSettings { + method: AwsMcpMethodKey; + roleArn: string | null; + endpointRegion: (typeof AWS_MCP_ENDPOINT_REGIONS)[number]; + accessLevel: AwsMcpAccessLevel; +} + +export interface AwsSessionCredentials { + accessKeyId: string; + secretAccessKey: string; + sessionToken?: string; + expiration?: Date; +} + +export type AwsMcpCredentialErrorCode = + | "aws_mcp_settings_invalid" + | "aws_identity_unavailable" + | "aws_issuer_changed" + | "aws_role_access_denied" + | "aws_access_key_invalid" + | "aws_mcp_signin_denied" + | "aws_unavailable"; + +/** A failure with a plain-language message. AWS's own message is never shown, since it can carry account IDs and ARNs. */ +export class AwsMcpCredentialError extends Error { + constructor( + readonly code: AwsMcpCredentialErrorCode, + readonly status: number, + message: string, + readonly health: "degraded" | "error", + readonly awsErrorName?: string, + ) { + super(message); + this.name = "AwsMcpCredentialError"; + } +} + +interface ConnectionLike { + id: string; + transport: string; + config: Record; +} + +function asRecord(value: unknown): Record { + return value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; +} + +/** The credential minter the connection's method declares in its app definition, if any. */ +export function connectionCredentialMinter(connection: ConnectionLike): string | null { + if (connection.transport !== "mcp_remote") return null; + const slug = connection.config.sourceTemplateKey; + const methodKey = connection.config.connectionMethodKey; + if (typeof slug !== "string" || typeof methodKey !== "string") return null; + const method = getConnectableAppDefinition(slug)?.methods.find((candidate) => candidate.key === methodKey); + return method?.credentialMinter ?? null; +} + +/** The method's declaration decides: a connection whose method mints AWS MCP credentials. */ +export function isAwsMcpConnection(connection: ConnectionLike): boolean { + return connectionCredentialMinter(connection) === AWS_MCP_CREDENTIAL_MINTER; +} + +/** Saved settings, rechecked at call time: the URL must be AWS's endpoint for the saved region. */ +export function awsMcpSettings(connection: ConnectionLike & { config: Record }): AwsMcpSettings { + const invalid = () => new AwsMcpCredentialError( + "aws_mcp_settings_invalid", 422, + "This AWS connection's settings are incomplete. Reconnect AWS.", "error", + ); + const method = connection.config.connectionMethodKey; + if (!(AWS_MCP_METHOD_KEYS as readonly unknown[]).includes(method)) throw invalid(); + const values = asRecord(connection.config.methodConfig); + const endpointRegion = values.endpointRegion; + if (!(AWS_MCP_ENDPOINT_REGIONS as readonly unknown[]).includes(endpointRegion)) throw invalid(); + if (connection.config.url !== `https://aws-mcp.${endpointRegion}.api.aws/mcp`) throw invalid(); + const roleArn = typeof values.roleArn === "string" && values.roleArn.trim() ? values.roleArn.trim() : null; + if (roleArn !== null && !ROLE_ARN_PATTERN.test(roleArn)) throw invalid(); + if (method === "aws-role" && !roleArn) throw invalid(); + const accessLevel = values.accessLevel === "full" ? "full" : "read_only"; + return { + method: method as AwsMcpMethodKey, + roleArn, + endpointRegion: endpointRegion as AwsMcpSettings["endpointRegion"], + accessLevel, + }; +} + +/** `paperclip-` in the characters STS allows, so CloudTrail shows which connection acted. */ +export function awsSessionName(connectionName: string, maxLength = 64): string { + const cleaned = connectionName.toLowerCase().replace(/[^a-z0-9+=,.@-]+/g, "-").replace(/^-+|-+$/g, ""); + return `paperclip-${cleaned || "connection"}`.slice(0, maxLength); +} + +/** The four AWS calls the minter makes. Tests replace them with a fake AWS. */ +export interface AwsMcpClients { + assumeRoleWithWebIdentity(input: { + region: string; roleArn: string; sessionName: string; webIdentityToken: string; policyArns?: readonly string[]; signal?: AbortSignal; + }): Promise; + assumeRole(input: { + region: string; credentials: AwsSessionCredentials; roleArn: string; sessionName: string; policyArns?: readonly string[]; signal?: AbortSignal; + }): Promise; + getFederationToken(input: { + region: string; credentials: AwsSessionCredentials; name: string; policyArns: readonly string[]; signal?: AbortSignal; + }): Promise; + createMcpToken(input: { region: string; credentials: AwsSessionCredentials; signal?: AbortSignal }): Promise<{ token: string; expiresInSeconds: number }>; +} + +function stsCredentials(value: { AccessKeyId?: string; SecretAccessKey?: string; SessionToken?: string; Expiration?: Date } | undefined): AwsSessionCredentials { + if (!value?.AccessKeyId || !value.SecretAccessKey) throw new Error("AWS returned no credentials"); + return { + accessKeyId: value.AccessKeyId, + secretAccessKey: value.SecretAccessKey, + sessionToken: value.SessionToken, + expiration: value.Expiration, + }; +} + +const policyArnList = (arns?: readonly string[]) => arns?.length ? { PolicyArns: arns.map((arn) => ({ arn })) } : {}; + +export const sdkAwsMcpClients: AwsMcpClients = { + async assumeRoleWithWebIdentity(input) { + // No caller credentials: the signed web identity token is the proof. + const sts = new STSClient({ region: input.region, credentials: { accessKeyId: "none", secretAccessKey: "none" } }); + const out = await sts.send(new AssumeRoleWithWebIdentityCommand({ + RoleArn: input.roleArn, RoleSessionName: input.sessionName, WebIdentityToken: input.webIdentityToken, + DurationSeconds: SESSION_SECONDS, ...policyArnList(input.policyArns), + }), { abortSignal: input.signal }); + return stsCredentials(out.Credentials); + }, + async assumeRole(input) { + const sts = new STSClient({ region: input.region, credentials: input.credentials }); + const out = await sts.send(new AssumeRoleCommand({ + RoleArn: input.roleArn, RoleSessionName: input.sessionName, + DurationSeconds: SESSION_SECONDS, ...policyArnList(input.policyArns), + }), { abortSignal: input.signal }); + return stsCredentials(out.Credentials); + }, + async getFederationToken(input) { + const sts = new STSClient({ region: input.region, credentials: input.credentials }); + const out = await sts.send(new GetFederationTokenCommand({ + Name: input.name, DurationSeconds: SESSION_SECONDS, ...policyArnList(input.policyArns), + }), { abortSignal: input.signal }); + return stsCredentials(out.Credentials); + }, + async createMcpToken(input) { + const signin = new SigninClient({ region: input.region, credentials: input.credentials }); + const out = await signin.send(new CreateOAuth2TokenWithIAMCommand({ + grantType: "client_credentials", resource: AWS_MCP_TOKEN_RESOURCE, + } as ConstructorParameters[0]), { abortSignal: input.signal }); + const token = (out as { accessToken?: string }).accessToken; + const expiresInSeconds = (out as { expiresIn?: number }).expiresIn ?? SESSION_SECONDS; + if (!token) throw new Error("AWS returned no MCP token"); + return { token, expiresInSeconds }; + }, +}; + +type Step = "identity" | "role" | "access_key" | "federation" | "signin"; + +function awsErrorName(error: unknown): string | undefined { + const record = asRecord(error); + return typeof record.name === "string" ? record.name : undefined; +} + +function awsHttpStatus(error: unknown): number | undefined { + const status = asRecord(asRecord(error).$metadata).httpStatusCode; + return typeof status === "number" ? status : undefined; +} + +/** Maps an AWS failure to a stable code and a message that names the fix, never AWS's raw text. */ +export function classifyAwsMcpError(step: Step, error: unknown): AwsMcpCredentialError { + if (error instanceof AwsMcpCredentialError) return error; + const name = awsErrorName(error); + const status = awsHttpStatus(error); + const details = asRecord(asRecord(error).details); + if (step === "identity") { + if (details.code === "workload_identity_issuer_changed") { + return new AwsMcpCredentialError( + "aws_issuer_changed", 409, + "This Paperclip instance's address changed since AWS was connected. Register the new identity provider address in AWS, then reconnect AWS.", + "error", + ); + } + if (details.code === "workload_identity_unavailable") { + return new AwsMcpCredentialError( + "aws_identity_unavailable", 422, + "The AWS role method needs this Paperclip instance to have a stable public HTTPS address. Use an access key instead.", + "error", + ); + } + return new AwsMcpCredentialError("aws_unavailable", 503, "Paperclip could not prepare this AWS connection's identity. Try again.", "degraded"); + } + const transient = !status || status >= 500 || status === 429 + || ["ThrottlingException", "Throttling", "TimeoutError", "RequestTimeout", "IDPCommunicationError"].includes(name ?? ""); + if (transient) { + return new AwsMcpCredentialError("aws_unavailable", 503, "AWS did not respond. Try again shortly.", "degraded", name); + } + if (step === "signin") { + return new AwsMcpCredentialError( + "aws_mcp_signin_denied", 403, + "AWS refused the MCP sign-in. Attach the AWSMCPSignInOAuthAccessPolicy managed policy to this connection's role or user.", + "error", name, + ); + } + if (step === "role") { + return new AwsMcpCredentialError( + "aws_role_access_denied", 403, + "AWS refused this connection's role. Check that the role exists and trusts this connection.", + "error", name, + ); + } + return new AwsMcpCredentialError( + "aws_access_key_invalid", 403, + step === "federation" + ? "AWS refused a read-only session for this access key. Allow sts:GetFederationToken for this IAM user." + : "AWS did not accept this connection's access key. Check that the key is active, or reconnect AWS with a new key.", + "error", name, + ); +} + +export interface AwsMcpMintInput { + companyId: string; + connectionId: string; + connectionName: string; + /** Changes whenever the connection or its grant is edited, so any edit makes a fresh token. */ + revision: string; + grantId: string; + /** The issuer recorded at setup; signing stops with a clear message if the instance address changed. */ + expectedIssuer?: string | null; + settings: AwsMcpSettings; + /** Reads a stored credential field by config path (access-key method only). */ + readSecret(configPath: string): Promise; + forceRefresh?: boolean; +} + +export interface AwsMcpCredentialMinterOptions { + clients?: AwsMcpClients; + /** Signs a connection identity token (the workload identity issuer). */ + signConnectionToken(input: { companyId: string; connectionId: string; audience: string; expectedIssuer?: string | null }): Promise<{ token: string }>; + now?: () => number; + /** Deadline for each AWS request (default 10 s). */ + stepTimeoutMs?: number; +} + +interface CacheEntry { fingerprint: string; header: string; refreshAt: number } + +export function createAwsMcpCredentialMinter(options: AwsMcpCredentialMinterOptions) { + const clients = options.clients ?? sdkAwsMcpClients; + const now = options.now ?? (() => Date.now()); + const stepTimeoutMs = options.stepTimeoutMs ?? DEFAULT_STEP_TIMEOUT_MS; + const cache = new Map(); + const inFlight = new Map>(); + + async function step(name: Step, run: (signal: AbortSignal) => Promise): Promise { + const controller = new AbortController(); + let timer: ReturnType | undefined; + const deadline = new Promise((_, reject) => { + timer = setTimeout(() => { + controller.abort(); + reject(Object.assign(new Error("AWS request timed out"), { name: "TimeoutError" })); + }, stepTimeoutMs); + timer.unref?.(); + }); + try { + return await Promise.race([run(controller.signal), deadline]); + } catch (error) { + throw classifyAwsMcpError(name, error); + } finally { + clearTimeout(timer); + } + } + + async function sessionCredentials(input: AwsMcpMintInput): Promise { + const { settings } = input; + const region = settings.endpointRegion; + const sessionName = awsSessionName(input.connectionName); + const readOnlyPolicies = settings.accessLevel === "read_only" ? AWS_MCP_READ_ONLY_SESSION_POLICIES : undefined; + if (settings.method === "aws-role") { + const { token } = await step("identity", () => options.signConnectionToken({ + companyId: input.companyId, connectionId: input.connectionId, audience: AWS_MCP_STS_AUDIENCE, + expectedIssuer: input.expectedIssuer, + })); + return step("role", (signal) => clients.assumeRoleWithWebIdentity({ + region, roleArn: settings.roleArn!, sessionName, webIdentityToken: token, policyArns: readOnlyPolicies, signal, + })); + } + const base: AwsSessionCredentials = { + accessKeyId: await input.readSecret(AWS_MCP_ACCESS_KEY_ID_PATH), + secretAccessKey: await input.readSecret(AWS_MCP_SECRET_ACCESS_KEY_PATH), + }; + if (settings.roleArn) { + return step("role", (signal) => clients.assumeRole({ + region, credentials: base, roleArn: settings.roleArn!, sessionName, policyArns: readOnlyPolicies, signal, + })); + } + if (readOnlyPolicies) { + // Federation token names allow at most 32 characters. + return step("federation", (signal) => clients.getFederationToken({ + region, credentials: base, name: awsSessionName(input.connectionName, 32), policyArns: readOnlyPolicies, signal, + })); + } + return base; + } + + async function mintHeader(input: AwsMcpMintInput, fingerprint: string, key: string): Promise { + const credentials = await sessionCredentials(input); + const { token, expiresInSeconds } = await step("signin", (signal) => clients.createMcpToken({ + region: input.settings.endpointRegion, credentials, signal, + })); + const expiresAt = Math.min( + now() + expiresInSeconds * 1000, + credentials.expiration ? credentials.expiration.getTime() : Number.POSITIVE_INFINITY, + ); + const header = `Bearer ${token}`; + // Drop tokens past their refresh point, so the cache only ever holds live tokens (removed connections included). + for (const [cachedKey, entry] of cache) if (entry.refreshAt <= now()) cache.delete(cachedKey); + cache.set(key, { fingerprint, header, refreshAt: expiresAt - REFRESH_MARGIN_MS }); + return header; + } + + return { + /** The Authorization header for one connection and grant, cached until about 55 minutes in. */ + async authorizationHeader(input: AwsMcpMintInput): Promise> { + const key = `${input.companyId}:${input.connectionId}:${input.grantId}`; + const fingerprint = createHash("sha256") + .update(JSON.stringify([input.revision, input.settings])) + .digest("base64url"); + const cached = cache.get(key); + if (!input.forceRefresh && cached && cached.fingerprint === fingerprint && cached.refreshAt > now()) { + return { Authorization: cached.header }; + } + if (input.forceRefresh || (cached && cached.fingerprint !== fingerprint)) cache.delete(key); + const flightKey = `${key}:${fingerprint}`; + let flight = inFlight.get(flightKey); + if (!flight) { + flight = mintHeader(input, fingerprint, key).finally(() => inFlight.delete(flightKey)); + inFlight.set(flightKey, flight); + } + return { Authorization: await flight }; + }, + /** How many tokens are cached (observability and tests). */ + cachedTokenCount(): number { + return cache.size; + }, + /** Drops every cached token for a connection, for example after AWS answers 401. */ + evict(companyId: string, connectionId: string) { + const prefix = `${companyId}:${connectionId}:`; + for (const key of cache.keys()) if (key.startsWith(prefix)) cache.delete(key); + }, + }; +} + +export type AwsMcpCredentialMinter = ReturnType; + +const sharedMinters = new WeakMap(); + +/** + * One minter per database, shared by the gateway and connection health checks so + * a token minted for discovery is reused by the next call, and an eviction after a + * 401 applies everywhere. + */ +export function sharedAwsMcpCredentialMinter( + db: object, + signConnectionToken: AwsMcpCredentialMinterOptions["signConnectionToken"], + clients?: AwsMcpClients, +): AwsMcpCredentialMinter { + // Test fakes get one shared minter per fake, like production gets one per database. + const owner = clients ?? db; + let minter = sharedMinters.get(owner); + if (!minter) { + minter = createAwsMcpCredentialMinter({ signConnectionToken, clients }); + sharedMinters.set(owner, minter); + } + return minter; +} + +interface RevisionSource { + status: string; + enabled: boolean; + credentialSecretRefs: Array<{ secretId: string; versionSelector?: unknown; configPath: string }>; +} + +/** + * What a cached token depends on besides the saved settings: which stored key it + * came from and whether the grant is live. Health and last-used + * stamps change on every call, so update times are deliberately not part of it. + */ +export function awsMcpCredentialRevision( + connection: RevisionSource, + grant?: { id: string; status: string; credentialSecretRefs: RevisionSource["credentialSecretRefs"] } | null, +): string { + const refs = (grant?.credentialSecretRefs ?? connection.credentialSecretRefs) + .map((ref) => `${ref.configPath}=${ref.secretId}@${String(ref.versionSelector ?? "latest")}`) + .sort(); + // Connection status is deliberately absent: finishing setup must not discard the token setup minted, + // and the gateway refuses a disabled connection before it asks for credentials. + return JSON.stringify([grant?.id ?? null, grant?.status ?? null, refs]); +} + +/** The role method proves itself with the company's issuer, which must be published before the customer registers it in AWS. */ +export function awsMcpMethodUsesIssuer(appSlug: string | null | undefined, methodKey: string | null | undefined): boolean { + return appSlug === AWS_MCP_SOURCE_TEMPLATE_KEY && methodKey === "aws-role"; +} + + +/** Where setup records the issuer a role connection's AWS trust was created for. */ +export const AWS_MCP_ISSUER_CONFIG_KEY = "workloadIdentityIssuer"; + +type SecretRefLike = RevisionSource["credentialSecretRefs"][number]; + +/** + * The shared minting pipeline for the gateway and connection health checks: builds + * the minter input from the connection and grant and reads stored keys through the + * caller's resolver. Failures are AwsMcpCredentialError; errors from `readRef` + * (the caller's own secret resolution) pass through unchanged. + */ +export async function resolveAwsMcpAuthorization(input: { + minter: AwsMcpCredentialMinter; + connection: ConnectionLike & { companyId: string; name: string; status: string; enabled: boolean; credentialSecretRefs: Ref[] }; + grant: { id: string; status: string; credentialSecretRefs: Ref[] } | null; + forceRefresh?: boolean; + readRef(ref: Ref): Promise; +}): Promise> { + const { connection, grant } = input; + const refs = grant?.credentialSecretRefs ?? connection.credentialSecretRefs; + const recordedIssuer = connection.config[AWS_MCP_ISSUER_CONFIG_KEY]; + return input.minter.authorizationHeader({ + companyId: connection.companyId, + connectionId: connection.id, + connectionName: connection.name, + grantId: grant?.id ?? "shared", + revision: awsMcpCredentialRevision(connection, grant), + settings: awsMcpSettings(connection), + expectedIssuer: typeof recordedIssuer === "string" ? recordedIssuer : null, + forceRefresh: input.forceRefresh, + readSecret: async (configPath) => { + const ref = refs.find((candidate) => candidate.configPath === configPath); + if (!ref) { + throw new AwsMcpCredentialError( + "aws_access_key_invalid", 422, + "This AWS connection has no saved access key. Reconnect AWS.", "error", + ); + } + return input.readRef(ref); + }, + }); +} diff --git a/server/src/services/instance-settings.ts b/server/src/services/instance-settings.ts index c97a7ecd0bd..2fe5d05f781 100644 --- a/server/src/services/instance-settings.ts +++ b/server/src/services/instance-settings.ts @@ -268,6 +268,7 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimenta enableMemoryConnectors: parsed.data.enableMemoryConnectors ?? false, enablePaperclipNotebook: parsed.data.enablePaperclipNotebook ?? false, enableGoogleWorkspaceConnector: parsed.data.enableGoogleWorkspaceConnector ?? false, + enableAwsConnector: parsed.data.enableAwsConnector ?? false, enableCases: parsed.data.enableCases ?? false, enableAgentChat: true, enableCombinedInboxTasks: parsed.data.enableCombinedInboxTasks ?? false, @@ -329,6 +330,7 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimenta enableMemoryConnectors: false, enablePaperclipNotebook: false, enableGoogleWorkspaceConnector: false, + enableAwsConnector: false, enableCases: false, enableAgentChat: true, enableCombinedInboxTasks: false, diff --git a/server/src/services/tool-access.ts b/server/src/services/tool-access.ts index d4b5bbb56d0..ec23ea31a03 100644 --- a/server/src/services/tool-access.ts +++ b/server/src/services/tool-access.ts @@ -1,4 +1,6 @@ import { notifyGitHubCredentialChange } from "./github-connection-notifications.js"; +import { AWS_MCP_ISSUER_CONFIG_KEY, awsMcpMethodUsesIssuer, type AwsMcpClients } from "./connectors/aws/mcp-credentials.js"; +import { workloadIdentityIssuer, workloadIdentityIssuerOrigin, workloadIdentityService } from "./workload-identity.js"; import { RepositoryCatalogUnavailableError, findRepositoryCatalogUnavailableError } from "./repository-catalog-unavailable-error.js"; import { notifyVoiceChange } from "./voice/voice-recovery-notifications.js"; import { notifyToolConnectionHealth, writeToolConnectionHealthChange } from "./tool-connection-health-notifications.js"; @@ -173,6 +175,8 @@ type ToolAccessServiceOptions = { paperclipCloudConnector?: PaperclipCloudConnector | null; /** Test seam for Vercel Connect without live vendor traffic. */ vercelConnectClient?: VercelConnectClient | null; + /** Test seam for the AWS calls behind minted AWS MCP credentials. */ + awsMcpClients?: AwsMcpClients; }; const GOOGLE_SHEETS_SPREADSHEET_SCHEMA = { @@ -837,7 +841,7 @@ export function toolAccessService( const { refreshManagedGitHubGrantAccess, syncGitHubGrantBindings, sweepGitHubConnectionContinuity, nextGitHubConnectionContinuityAt, githubConnectionContinuitySchedule } = createGitHubGrantContinuity(db, { now, currentCloudConnector, refreshOAuthGrantCredentials, resolveOAuthGrantSecret }); const vercelCredentials = createVercelCredentialService(db, now, vercelConnect); const { resolveVercelCredentialHeaders, vercelGrantForConnection } = vercelCredentials; - const credentialAccess = createConnectionCredentialAccess(db, { secrets, audit, vercel: vercelCredentials, resolveOAuthGrantSecret, maybeRefreshOAuthCredentials, refreshOAuthGrantCredentials }); + const credentialAccess = createConnectionCredentialAccess(db, { secrets, audit, vercel: vercelCredentials, resolveOAuthGrantSecret, maybeRefreshOAuthCredentials, refreshOAuthGrantCredentials, awsMcpClients: options.awsMcpClients }); const { vaultGrantForConnection, resolveCredentialHeaders, resolvedRemoteEndpoint } = credentialAccess; const setupPolicy = createConnectionSetupPolicy(db); const { assertConnectorConnectionSetupEnabled, assertExperimentalConnectorSetupEnabled } = setupPolicy; @@ -2251,9 +2255,20 @@ export function toolAccessService( "", } : { templateId: method?.defaults?.templateKey }; + // The issuer an AWS role is asked to trust, recorded so a later change of this instance's address + // gets a clear message instead of a role refusal. A draft being resumed keeps the issuer recorded at + // the draft step; any other setup or reconnect records the current address (the one now in AWS). + const recordedAwsIssuer = !input.reconnectConnectionId && retainedConnection?.status === "draft" + ? asRecord(retainedConnection.config)[AWS_MCP_ISSUER_CONFIG_KEY] + : undefined; + const awsIssuerOrigin = workloadIdentityIssuerOrigin(); + const awsRoleIssuer = !awsMcpMethodUsesIssuer(galleryEntry?.slug, method?.key) ? null + : typeof recordedAwsIssuer === "string" ? recordedAwsIssuer + : awsIssuerOrigin.available ? workloadIdentityIssuer(awsIssuerOrigin.origin, companyId) : null; let config: Record = galleryEntry ? { ...baseConfig, + ...(awsRoleIssuer ? { [AWS_MCP_ISSUER_CONFIG_KEY]: awsRoleIssuer } : {}), sourceTemplateKey: galleryEntry.slug, connectionMethodKey: method?.key, methodConfig: normalizedMethodConfig?.values ?? {}, @@ -2921,7 +2936,13 @@ export function toolAccessService( ); await ensureRuntimeSlot(connectionRow); - if (input.saveDraft && remoteMcpConnector) { + // Minted-credential methods (AWS role) need the connection to exist before the + // provider can trust it, so they may also save a draft without contacting it. + // AWS validates the issuer's discovery document when the customer registers it, so publish the key now. + if (input.saveDraft && awsMcpMethodUsesIssuer(galleryEntry?.slug, method?.key)) { + await workloadIdentityService(db).ensureActiveKey(companyId); + } + if (input.saveDraft && (remoteMcpConnector || method?.credentialMinter)) { return { connectionId: connectionRow.id, application: toApplication(applicationRow), connection: toConnection(connectionRow), catalog: [], actions: { readOnly: [], canMakeChanges: [] }, suggestedDefaults: { access: "all_agents", askFirstRiskLevels: [] } }; } diff --git a/server/src/services/tool-access/catalog/discovery.ts b/server/src/services/tool-access/catalog/discovery.ts index 4b997040057..4d82efa010b 100644 --- a/server/src/services/tool-access/catalog/discovery.ts +++ b/server/src/services/tool-access/catalog/discovery.ts @@ -1,4 +1,5 @@ import { assertSupportedConnection } from "../connections/setup-policy.js"; +import { isAwsMcpConnection } from "../../connectors/aws/mcp-credentials.js"; import { usesClientCredentials } from "../oauth/client-credentials.js"; import { vercelCredentialFor, vercelConnectResourcesFor } from "../vercel-credentials.js"; import { connectionSetupUrl, connectionReconnectUrl } from "../identifiers.js"; @@ -345,6 +346,14 @@ export function createToolCatalogDiscovery(db: Db, { now, audit, secrets, creden await response.body?.cancel().catch(() => undefined); throw unprocessable(INSUFFICIENT_CONNECTION_SCOPE_MESSAGE, { code: "oauth_insufficient_scope", connectionId: connection.id }); } + if (response.status === 401 && isAwsMcpConnection(connection)) { + // A refused AWS token: mint a fresh one and list again (listing has no side effects). + headers = { + ...projectedConnectionHeaders(connection), + ...(await resolveCredentialHeaders(connection, actor, { forceRefresh: true })), + }; + response = await relistAfterCredentialRefresh(); + } if ( response.status === 401 && connection.credentialSource === "vercel_connect" diff --git a/server/src/services/tool-access/catalog/failures.ts b/server/src/services/tool-access/catalog/failures.ts index ee7d72bbb5a..3d3aec2f3b1 100644 --- a/server/src/services/tool-access/catalog/failures.ts +++ b/server/src/services/tool-access/catalog/failures.ts @@ -106,6 +106,10 @@ export function sanitizeHttpFailure(error: unknown): { code: "oauth_reauthorization_required", }; } + if (typeof code === "string" && code.startsWith("aws_") && code !== "aws_unavailable") { + return { status: "error", message: error.message, code }; + } + if (code === "aws_unavailable") return { status: "degraded", message: error.message, code }; if (typeof code === "string" && code.startsWith("vercel_connect_")) { return { status: diff --git a/server/src/services/tool-access/credential-access.ts b/server/src/services/tool-access/credential-access.ts index 5fdf4f70901..eb9c6709c11 100644 --- a/server/src/services/tool-access/credential-access.ts +++ b/server/src/services/tool-access/credential-access.ts @@ -1,4 +1,6 @@ import { connectionActorUserId } from "./actor.js"; +import { AwsMcpCredentialError, isAwsMcpConnection, resolveAwsMcpAuthorization, sharedAwsMcpCredentialMinter, type AwsMcpClients } from "../connectors/aws/mcp-credentials.js"; +import { workloadIdentityService } from "../workload-identity.js"; import type { ActorInfo } from "./types.js"; import { oauthConfig } from "./oauth/metadata.js"; import { remoteEndpoint } from "./connection-methods.js"; @@ -26,6 +28,8 @@ function asRecord(value: unknown): Record { type CredentialAccessDependencies = { secrets: ReturnType; + /** Test seam for the AWS calls behind minted AWS MCP credentials. */ + awsMcpClients?: AwsMcpClients; audit: ToolAccessAudit; vercel: VercelCredentialService; resolveOAuthGrantSecret: OAuthCredentialStore["resolveOAuthGrantSecret"]; @@ -33,7 +37,10 @@ type CredentialAccessDependencies = { refreshOAuthGrantCredentials: ReturnType; }; -export function createConnectionCredentialAccess(db: Db, { secrets, audit, vercel, resolveOAuthGrantSecret, maybeRefreshOAuthCredentials, refreshOAuthGrantCredentials }: CredentialAccessDependencies) { +export function createConnectionCredentialAccess(db: Db, { secrets, audit, vercel, resolveOAuthGrantSecret, maybeRefreshOAuthCredentials, refreshOAuthGrantCredentials, awsMcpClients }: CredentialAccessDependencies) { + const signAwsConnectionToken = (input: { companyId: string; connectionId: string; audience: string }) => + workloadIdentityService(db).signConnectionToken(input); + const awsMcpMinter = sharedAwsMcpCredentialMinter(db, signAwsConnectionToken, awsMcpClients); const { resolveVercelCredentialHeaders, vercelGrantForConnection } = vercel; async function vaultGrantForConnection( connection: typeof toolConnections.$inferSelect, @@ -137,6 +144,40 @@ export function createConnectionCredentialAccess(db: Db, { secrets, audit, verce return null; } + /** Minted at call time for AWS's hosted MCP server; shares the gateway's token cache. */ + async function resolveAwsMcpHeaders( + connection: typeof toolConnections.$inferSelect, + actor: ActorInfo | undefined, + options: { forceRefresh?: boolean }, + ): Promise> { + // The same grant the gateway uses, so both share one cached token and a shared connection never reads + // a personal key: a shared connection uses only its active default organization grant. + const grant = connection.credentialPolicy === "shared" + ? (await db.select().from(connectionGrants).where(and( + eq(connectionGrants.companyId, connection.companyId), + eq(connectionGrants.connectionId, connection.id), + eq(connectionGrants.kind, "organization"), + eq(connectionGrants.isDefault, true), + eq(connectionGrants.status, "active"), + )).limit(1))[0] ?? null + : await vaultGrantForConnection(connection, actor); + try { + return await resolveAwsMcpAuthorization({ + minter: awsMcpMinter, connection, grant, forceRefresh: options.forceRefresh, + // A grant's keys may be user-owned (personal connections); read them the way other grant credentials are read. + readRef: async (ref) => grant + ? (await resolveOAuthGrantSecret(connection, grant, ref, actor, undefined)).value + : secrets.resolveSecretValue(connection.companyId, ref.secretId, ref.versionSelector ?? "latest"), + }); + } catch (error) { + if (!(error instanceof AwsMcpCredentialError)) throw error; + throw new HttpError(error.status, error.message, { + code: error.code, connectionId: connection.id, + ...(error.awsErrorName ? { awsError: error.awsErrorName } : {}), + }); + } + } + async function resolveCredentialHeaders( connection: typeof toolConnections.$inferSelect, actor?: ActorInfo, @@ -146,6 +187,7 @@ export function createConnectionCredentialAccess(db: Db, { secrets, audit, verce const grant = await vercelGrantForConnection(connection, actor); return resolveVercelCredentialHeaders(connection, grant, options); } + if (isAwsMcpConnection(connection)) return resolveAwsMcpHeaders(connection, actor, options); let grant: typeof connectionGrants.$inferSelect | null = null; try { if ( diff --git a/server/src/services/tool-gateway.ts b/server/src/services/tool-gateway.ts index 8a89286857d..a418ea22076 100644 --- a/server/src/services/tool-gateway.ts +++ b/server/src/services/tool-gateway.ts @@ -1,4 +1,12 @@ import { assertAgentToolAssignmentInteractions } from "./connection-management.js"; +import { + AwsMcpCredentialError, + isAwsMcpConnection, + resolveAwsMcpAuthorization, + sharedAwsMcpCredentialMinter, + type AwsMcpClients, +} from "./connectors/aws/mcp-credentials.js"; +import { workloadIdentityService } from "./workload-identity.js"; import { isNewHumanIntentAfterToolRejection } from "./tool-action-replay-intent.js"; import { approvalSnapshotsMatch, approvalTargetChangeMessage, oauthApprovalConfig, approvalGrantTenantIdentity, externalCredentialApprovalIdentity } from "./tool-approval-target.js"; @@ -619,6 +627,7 @@ const REMOTE_TOOL_CALL_WORKFLOW_REASON_CODES = new Set([ "provider_retry_requested", "oauth_insufficient_scope", "oauth_refreshed_retry_required", + "credentials_refreshed_retry_required", "provider_task_pending", "provider_task_cancelled", "provider_task_expired", @@ -1400,6 +1409,8 @@ export function createToolGatewayService( }) => Promise; /** Test seam for resolving Vercel Connect credentials. */ vercelConnectClient?: VercelConnectClient | null; + /** Test seam for the AWS calls behind minted AWS MCP credentials. */ + awsMcpClients?: AwsMcpClients; /** Test seam for reproducing the managed-argument drift expiry race. */ beforeManagedArgumentDriftExpiry?: () => Promise; /** Test seam for pausing a legacy approved request before its execution claim. */ @@ -1655,6 +1666,9 @@ export function createToolGatewayService( options.vercelConnectClient === undefined ? createVercelConnectClient() : options.vercelConnectClient; + const signAwsConnectionToken = (input: { companyId: string; connectionId: string; audience: string }) => + workloadIdentityService(db).signConnectionToken(input); + const awsMcpMinter = sharedAwsMcpCredentialMinter(db, signAwsConnectionToken, options.awsMcpClients); const protocolLimits = mcpGatewayProtocolLimits( options.mcpGatewayProtocolLimits, ); @@ -4703,6 +4717,9 @@ export function createToolGatewayService( }); } } + if (isAwsMcpConnection(connection)) { + return resolveAwsMcpHeaders(session, connection, grant, resolveOptions); + } const oauth = asRecord(asRecord(connection.config)?.oauth); if ( isPaperclipCloudConnectorStrategy(oauth?.strategy) && @@ -4817,6 +4834,35 @@ export function createToolGatewayService( return headers; } + /** AWS's Authorization header is minted per connection at call time and never stored. */ + async function resolveAwsMcpHeaders( + session: ToolGatewaySession, + connection: typeof toolConnections.$inferSelect, + grant: typeof connectionGrants.$inferSelect, + resolveOptions: { forceRefresh?: boolean }, + ): Promise> { + try { + return await resolveAwsMcpAuthorization({ + minter: awsMcpMinter, connection, grant, forceRefresh: resolveOptions.forceRefresh, + readRef: (ref) => resolveGrantSecretValue(session, connection, grant, ref), + }); + } catch (error) { + if (error instanceof ToolGatewayHttpError) { + await markRemoteConnectionHealth(connection, "missing_secret", "A configured credential secret could not be resolved."); + throw error; + } + const known = error instanceof AwsMcpCredentialError + ? error + : new AwsMcpCredentialError("aws_unavailable", 503, "AWS credentials could not be prepared. Try again.", "degraded"); + await markRemoteConnectionHealth(connection, known.health, known.message); + throw new ToolGatewayHttpError(known.status, known.message, known.code, { + connectionId: connection.id, + grantId: grant.id, + ...(known.awsErrorName ? { awsError: known.awsErrorName } : {}), + }); + } + } + function credentialVersionRefHash(value: Record): string { return stableHash(value); } @@ -8094,6 +8140,15 @@ export function createToolGatewayService( responseTimeoutMs: ms, }); }; + // AWS refused the minted token: drop it everywhere and rebuild this call's headers with a fresh one. + const remintAwsCredentials = async () => { + awsMcpMinter.evict(connection.companyId, connection.id); + resolvedCredentials = await resolveCredentialHeaders(session, connection, grant, { forceRefresh: true }); + credentialHeaders = { ...projectedConnectionHeaders(connection), ...resolvedCredentials }; + builtHeaders = buildRemoteHeaders({ session, connection, credentialHeaders, callerHeaders }); + headers = builtHeaders.headers; + headerSummary = builtHeaders.summary; + }; const requireExplicitRetryAfterOAuthRefresh = async (refreshedResponse: Response): Promise => { // The provider rejected this dispatch, but automatic replay is unsafe: // a server can apply a request before returning 401. A caller retry @@ -8108,10 +8163,14 @@ export function createToolGatewayService( refreshedResponse.headers.get("x-request-id") ?? refreshedResponse.headers.get("traceparent"), }; + // AWS credentials are minted, not OAuth tokens: say what actually happened. + const minted = isAwsMcpConnection(connection); throw new ToolGatewayHttpError( 409, - "The provider rejected the saved OAuth token, which has now been refreshed. Retry the action explicitly; the original call was not replayed.", - "oauth_refreshed_retry_required", + minted + ? "AWS refused the saved credentials, and Paperclip has made new ones. Retry the action explicitly; the original call was not replayed." + : "The provider rejected the saved OAuth token, which has now been refreshed. Retry the action explicitly; the original call was not replayed.", + minted ? "credentials_refreshed_retry_required" : "oauth_refreshed_retry_required", { connectionId: connection.id, catalogEntryId: entry.id, execution }, ); }; @@ -8200,7 +8259,7 @@ export function createToolGatewayService( // declares form questions; it is kept apart from sessions that only // read (resources, prompts, listing), which declare none. const scope = `${connection.id}:grant:${grant.id}:actor:${session.agentId}:elicit-form:${endpoint}`; - requestHeaders = await getMcpHttpSession({ + const openSession = () => getMcpHttpSession({ scope, send: sendForNegotiation, headers, @@ -8208,6 +8267,15 @@ export function createToolGatewayService( eraKey, elicitationForm: true, }); + try { + requestHeaders = await openSession(); + } catch (error) { + if (!(error instanceof McpHttpInitializationError && error.status === 401 && isAwsMcpConnection(connection))) throw error; + // AWS refused the cached token while opening the session. No tool ran, + // so mint a fresh token and open the session once more. + await remintAwsCredentials(); + requestHeaders = await openSession(); + } const sessionId = new Headers(requestHeaders).get("mcp-session-id"); if (sessionId) mcpSession = { scope, headers, sessionId }; const negotiated = mcpProtocolVersionOf(requestHeaders); @@ -8467,6 +8535,11 @@ export function createToolGatewayService( headerSummary = builtHeaders.summary; await requireExplicitRetryAfterOAuthRefresh(response); } + if (response.status === 401 && isAwsMcpConnection(connection)) { + // The cached AWS token was refused: mint a fresh one, never replay the call. + await remintAwsCredentials(); + await requireExplicitRetryAfterOAuthRefresh(response); + } if ( response.status === 401 && connection.credentialSource === "vercel_connect" diff --git a/server/src/services/workload-identity.ts b/server/src/services/workload-identity.ts index 74040949844..eca2cd0a2ed 100644 --- a/server/src/services/workload-identity.ts +++ b/server/src/services/workload-identity.ts @@ -272,7 +272,9 @@ export function workloadIdentityService(db: Db, options: { now?: () => Date } = )); if (!connection) throw notFound("Connection not found"); // Disabling a connection must stop new cloud credentials at once. - if (!connection.enabled || connection.status !== "active") { + // A draft is being set up and tested; a disabled, archived or switched-off connection gets nothing. + const usable = connection.status === "draft" || (connection.status === "active" && connection.enabled); + if (!usable) { throw unprocessable("This connection is not active.", { code: "workload_identity_connection_inactive" }); } diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 99103671e41..34505c1d108 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -72,10 +72,10 @@ "packages/shared/src/antigravity-runtime.test.ts": "f9ebcc9430be51c342b42644b735f1434b405ec7", "packages/shared/src/api.ts": "1d61cdff51433c4136368d52ee7cf2f16aa820ed", "packages/shared/src/app-definitions-url.test.ts": "56792d6745a5bc7eafc36e7403f4c9bbd671ae99", - "packages/shared/src/app-definitions.generated.ts": "e314e97d3b535c8d3942052240f794049bb9f44a", + "packages/shared/src/app-definitions.generated.ts": "854539d487e1eb12bbef36f96889dc032ed56c41", "packages/shared/src/app-definitions.ingestion-report.json": "a7b60c7c16a484a411989315e9f08d48258fa647", - "packages/shared/src/app-definitions.test.ts": "54cf668cf97cf1b57e8af631beeb2828e9730558", - "packages/shared/src/app-definitions.ts": "6175eedde391d9ee0c13641546ea00c7cb0f6c2f", + "packages/shared/src/app-definitions.test.ts": "20b31d44848f415076431f03e829365c6ae19467", + "packages/shared/src/app-definitions.ts": "de39d817de0aa90ff1cc218d62bcc886bb5608d6", "packages/shared/src/app-definitions/1password.json": "c11a4777de2c78805b2d391da5eb075a9511e0f8", "packages/shared/src/app-definitions/agentmail.json": "edd0799b1980d0f5f43b89c8f7a1173dc623f7fa", "packages/shared/src/app-definitions/airtable.json": "c9b216a2bbe693bc6167413255d41c33512d418d", @@ -83,6 +83,7 @@ "packages/shared/src/app-definitions/api-key-generic.json": "09e6d4295513ac9f1002eaf37c34e7c2d00a3c05", "packages/shared/src/app-definitions/arcade.json": "c8379450055d4ea226d229b1cbf99c7ed2e52beb", "packages/shared/src/app-definitions/asana.json": "4cc2859043a30037fd5cdc3ebd0909938b9344a8", + "packages/shared/src/app-definitions/aws.json": "34f4845777ae61baa7fffa2e8590f4c91a72f128", "packages/shared/src/app-definitions/bedrock.json": "962d8a722ac6e2e4db00abc34f71947a3fdb733a", "packages/shared/src/app-definitions/beehiiv.json": "47aec8fdfbf5aed0919b6ac9bddb435de4988db3", "packages/shared/src/app-definitions/bitly.json": "81f4937e92f2971f2011acb50929adf5287315e4", @@ -255,7 +256,7 @@ "packages/shared/src/external-objects.ts": "a9953c4e3f77f2bad03cb7832914ffc0b1a1266a", "packages/shared/src/fast-response.ts": "a81332a2b46b59c1f6953cfc4da659eae2326beb", "packages/shared/src/feature-catalog.test.ts": "d3e000c039492daad1fe0b7302b34e7c3816a8ce", - "packages/shared/src/feature-catalog.ts": "37b81f802f8f75533c9b9261671a88b5ba3571b0", + "packages/shared/src/feature-catalog.ts": "35d8a9a5f5d6658bd99b8dad72317921392500fa", "packages/shared/src/frontmatter-runner-contract.test.ts": "cd121330e10aaa9da36c16293bcd9760561b6b41", "packages/shared/src/frontmatter.test.ts": "56635e331c8abca8868da76f23a08e98f20ff07f", "packages/shared/src/frontmatter.ts": "a86e046ce588d2f92d4996122cc2068ec275e89c", @@ -393,7 +394,7 @@ "packages/shared/src/types/agent-lifecycle.ts": "dcc5105d57856cc8ca34a122cf54117c950184ea", "packages/shared/src/types/agent.adapter-auth-session.test.ts": "d651511d78cb44b29940252df6138cd202e0ab45", "packages/shared/src/types/agent.ts": "11f5dbdf5b4c16271b5d79e22b159f97be68e896", - "packages/shared/src/types/app-definition.ts": "d1e521c8641a5f80c8552fa4ad8e20324f692e2c", + "packages/shared/src/types/app-definition.ts": "965d93e6671b465d781ee18019798ff99b5819eb", "packages/shared/src/types/approval.ts": "4554d36f804cb74b825b29711ed4c622df07ff6d", "packages/shared/src/types/artifact.ts": "6d022d34a718196df5c109a6164e7a70ede287e8", "packages/shared/src/types/asset.ts": "d148d6cba0e9a8d2e3aa6cb9182df6f59f909fba", @@ -427,7 +428,7 @@ "packages/shared/src/types/inbox-dismissal.ts": "58fb7013847396ac9971eb5799dd0bf0486e0371", "packages/shared/src/types/inbox-mine.ts": "1d302b531d34842189704abd2f75f8743d09490d", "packages/shared/src/types/index.ts": "4a489d81995adbb8e485cf7283e23fca4b8f3ff3", - "packages/shared/src/types/instance.ts": "4aa67dcaaddc2e7455ab535b6f352333585e8172", + "packages/shared/src/types/instance.ts": "77b0052be0f64a5531c5ebf0fd078c9854084479", "packages/shared/src/types/issue-tree-control.ts": "75489fffd491b8350b05caf57d7796419797d9df", "packages/shared/src/types/issue.ts": "e22382a60188594d17c0fa7c7c717a7612e68626", "packages/shared/src/types/live.ts": "b90e55e4de8600c6fc17d7fa8d89079d4ae655ec", @@ -469,7 +470,7 @@ "packages/shared/src/validators/agent-commentary.ts": "8242c5b28a77131aefdc00c873ad84c6c6736e4b", "packages/shared/src/validators/agent.test.ts": "d38767b0c1fc1439871855ed55dca3c8c7b645c6", "packages/shared/src/validators/agent.ts": "13ba04317b11c4281b7a2133a34630b4ad446dfd", - "packages/shared/src/validators/app-definition.ts": "c3f686a39add15032bf5f3648b26f0d585316813", + "packages/shared/src/validators/app-definition.ts": "c97907a348e9278a28588ed7d6a395ec04dde0da", "packages/shared/src/validators/approval.test.ts": "051d29b27400fdd1e311466587b276264cf072e4", "packages/shared/src/validators/approval.ts": "b8fd4da39568e3b70b767266196ea5303efeef25", "packages/shared/src/validators/artifact.test.ts": "2f0c138a6fa46d68507515d3932e9bc4cef44374", @@ -506,7 +507,7 @@ "packages/shared/src/validators/inbox-agent-policy.ts": "29cef157f4d9b564fd813868038aa8c813df4a7b", "packages/shared/src/validators/index.ts": "e9a8df3bfddd1d9b044ef80aa95f56e0d326a850", "packages/shared/src/validators/instance.test.ts": "3faa9593a9a05f74429d9b1d2251906a03e9a903", - "packages/shared/src/validators/instance.ts": "784b641f66b163f8c12e808c8da8fe6840fa3da7", + "packages/shared/src/validators/instance.ts": "9d09c2e2a8fa6d942c12d31d24dc1099f7228e58", "packages/shared/src/validators/issue-chat-bootstrap.test.ts": "e1ebb9aa94da22c825bc3ddd32ce2cfc98bfe645", "packages/shared/src/validators/issue-tree-control.ts": "7144ef86a83e008ac0626e1d62a1d6164c46f438", "packages/shared/src/validators/issue.test.ts": "c66108342e62370064b9f3e92652a71c71528012", diff --git a/ui/public/brands/apps/aws-dark.svg b/ui/public/brands/apps/aws-dark.svg new file mode 100644 index 00000000000..f9a48867fe3 --- /dev/null +++ b/ui/public/brands/apps/aws-dark.svg @@ -0,0 +1 @@ +AWS \ No newline at end of file diff --git a/ui/public/brands/apps/aws.svg b/ui/public/brands/apps/aws.svg new file mode 100644 index 00000000000..3291c3a396d --- /dev/null +++ b/ui/public/brands/apps/aws.svg @@ -0,0 +1 @@ +AWS \ No newline at end of file diff --git a/ui/public/brands/apps/manifest.json b/ui/public/brands/apps/manifest.json index 4b25a883b10..e6260708456 100644 --- a/ui/public/brands/apps/manifest.json +++ b/ui/public/brands/apps/manifest.json @@ -39,6 +39,13 @@ "catalogVisible": true, "localAsset": "/brands/apps/asana.svg" }, + { + "slug": "aws", + "provider": "Amazon Web Services", + "catalogVisible": true, + "localAsset": "/brands/apps/aws.svg", + "darkAsset": "/brands/apps/aws-dark.svg" + }, { "slug": "bedrock", "provider": "Amazon Bedrock", diff --git a/ui/src/pages/InstanceExperimentalSettings.test.tsx b/ui/src/pages/InstanceExperimentalSettings.test.tsx index a02aaf2b02c..814b4f9e65e 100644 --- a/ui/src/pages/InstanceExperimentalSettings.test.tsx +++ b/ui/src/pages/InstanceExperimentalSettings.test.tsx @@ -97,6 +97,7 @@ function defaultExperimentalSettings(): InstanceExperimentalSettingsPayload { enableGitHubReviewBots: false, enableMemoryConnectors: false, enableGoogleWorkspaceConnector: false, + enableAwsConnector: false, enablePaperclipNotebook: false, enableCases: false, enableAgentChat: false, diff --git a/ui/src/pages/InstanceExperimentalSettings.tsx b/ui/src/pages/InstanceExperimentalSettings.tsx index 939aacc449a..a134d5e7066 100644 --- a/ui/src/pages/InstanceExperimentalSettings.tsx +++ b/ui/src/pages/InstanceExperimentalSettings.tsx @@ -320,6 +320,18 @@ export function InstanceExperimentalSettings() { ariaLabel="Toggle Areas & Responsibilities dashboard experimental setting" /> + toggleMutation.mutate({ enableAwsConnector: checked })} + disabled={toggleMutation.isPending} + settingKey="enableAwsConnector" + managed={managedKeys.enableAwsConnector} + ariaLabel="Toggle AWS connector experimental setting" + /> + +