diff --git a/apps/docs/components/ui/icon-mapping.ts b/apps/docs/components/ui/icon-mapping.ts index c4c817a2963..39e82ed79c6 100644 --- a/apps/docs/components/ui/icon-mapping.ts +++ b/apps/docs/components/ui/icon-mapping.ts @@ -481,6 +481,7 @@ export const blockTypeToIconMap: Record = { generic_webhook: Webhook, github: GithubIcon, github_v2: GithubIcon, + github_v3: GithubIcon, gitlab: GitLabIcon, gitlab_v2: GitLabIcon, gmail: GmailIcon, diff --git a/apps/docs/content/docs/integrations/aws-credentials.mdx b/apps/docs/content/docs/integrations/aws-credentials.mdx index 55e5e9d22aa..94954d8983c 100644 --- a/apps/docs/content/docs/integrations/aws-credentials.mdx +++ b/apps/docs/content/docs/integrations/aws-credentials.mdx @@ -65,9 +65,9 @@ Generate a key with `openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:204 To rotate the signing key without failed runs: 1. Set the new key as `WORKLOAD_IDENTITY_PREVIOUS_KEY` and redeploy (including any background workers that run workflows). Sim publishes it but keeps signing with the current key. -2. Wait at least 5 minutes, so every cached copy of the published keys includes the new one. +2. Wait at least 5 minutes, so every cached copy of the published keys includes the new one. If any keyless [Snowflake connection](/integrations/snowflake-service-account#keyless-service-user) exists, wait 60 minutes instead: Snowflake caches an issuer's keys for up to an hour. 3. Swap them: set the new key as `WORKLOAD_IDENTITY_SIGNING_KEY` and the old key as `WORKLOAD_IDENTITY_PREVIOUS_KEY`, and redeploy everything that runs workflows. -4. Once every instance signs with the new key, wait 5 more minutes, then remove `WORKLOAD_IDENTITY_PREVIOUS_KEY`. +4. Once every instance signs with the new key, wait 5 more minutes (10 with keyless Snowflake connections, whose tokens last that long), then remove `WORKLOAD_IDENTITY_PREVIOUS_KEY`. Without a signing key, the keyless option is unavailable and access keys work as usual. diff --git a/apps/docs/content/docs/integrations/bitbucket-service-account.mdx b/apps/docs/content/docs/integrations/bitbucket-service-account.mdx new file mode 100644 index 00000000000..799e5f5138e --- /dev/null +++ b/apps/docs/content/docs/integrations/bitbucket-service-account.mdx @@ -0,0 +1,66 @@ +--- +title: Bitbucket access tokens +description: Connect Bitbucket Cloud to Sim with a workspace, project, or repository access token instead of a personal account +--- + +import { Callout } from '@/components/ui/callout' +import { Step, Steps } from '@/components/ui/steps' + +Connect Bitbucket Cloud with an access token when a workflow should act as an integration rather than as the person who connected it. An access token belongs to a workspace, project, or repository, not to a user, so it keeps working when people leave and its reach is limited to what it was created for. + +Bitbucket shows actions taken with the token (comments, merges, pipeline runs) under the token's name. + +## Prerequisites + +Admin access to the workspace, project, or repository the token is for. Workspace access tokens require a Bitbucket Cloud Premium plan; project and repository access tokens do not. + +## Create the access token [#creating-the-access-token] + + + + Open the repository, project, or workspace settings in Bitbucket Cloud and go to **Access tokens** + + + Click **Create access token** and give it a name (e.g. `Sim workflows`) — this is the name Bitbucket shows on everything the workflow does + + + Select **Repositories: Read** (`repository`). Add **Pull requests**, **Repositories: Write**, or **Pipelines** scopes for the actions the workflow takes + + + Create the token and copy it right away — Bitbucket shows it only once + + + + +A repository access token can only reach its repository, and a project access token only the repositories in its project. Treat the token like a password; Sim encrypts it at rest. + + +## Add the access token to Sim [#adding-the-access-token-to-sim] + + + + Open **Integrations** from your workspace sidebar + + + Search for "Bitbucket" and open it, then click **Add to Sim** and choose **Add access token** + + + Paste the token and enter a repository it can read as `workspace/repository` (the `my-workspace/my-repository` in `bitbucket.org/my-workspace/my-repository`). For a repository access token, that is its own repository + + + Click **Add access token**. Sim verifies the token by reading that repository once, so the token needs the `repository` scope + + + +## Use the credential in workflows [#using-the-credential-in-workflows] + +Add a Bitbucket block and select the saved access token in the account dropdown, then choose the workspace and repository. The block calls `api.bitbucket.org` with the token, exactly as it does with a connected account. + +Two things need a signed-in account and do not work with an access token: + +- **List Workspaces** lists the workspaces of the person who connected the account, so Sim refuses to run it with an access token. Use a connected account for it. +- The workspace picker lists a person's workspaces, so it cannot load them for an access token. Switch the workspace field to manual entry and type the slug. + +## Rotate tokens and handle permission failures + +If validation succeeds but an action fails, the token is likely missing that action's scope, or the repository is outside the token's project or repository. Access tokens cannot be edited after creation: create a replacement with the right scopes, update the credential in Sim, test the workflow, and then revoke the old token. See [Bitbucket's access token documentation](https://support.atlassian.com/bitbucket-cloud/docs/access-tokens/). diff --git a/apps/docs/content/docs/integrations/bitbucket.mdx b/apps/docs/content/docs/integrations/bitbucket.mdx index b3d0cc8a810..d0712cd7a4e 100644 --- a/apps/docs/content/docs/integrations/bitbucket.mdx +++ b/apps/docs/content/docs/integrations/bitbucket.mdx @@ -12,9 +12,11 @@ import { ReferenceDetails } from "@/components/ui/reference-details" {/* MANUAL-CONTENT-START:intro */} Use [Bitbucket](https://bitbucket.org/) Cloud to read repositories, branches, commits, files, and diffs; create or delete branches; and manage pull requests and comments. Pipeline actions list runs and steps, start or stop runs, and retrieve step logs. -Connect a Bitbucket account through OAuth. Triggers can start workflows on pushes, repository changes, build status updates, and pull request events; Sim manages their webhooks. For example, a workflow can read a failed pipeline's logs or review a newly opened pull request. +Connect a Bitbucket account through OAuth, or a workspace, project, or repository [access token](/integrations/bitbucket-service-account). Triggers can start workflows on pushes, repository changes, build status updates, and pull request events; Sim manages their webhooks. For example, a workflow can read a failed pipeline's logs or review a newly opened pull request. {/* MANUAL-CONTENT-END */} +Connection guides: [Access tokens](/integrations/bitbucket-service-account). + ## OAuth scopes [#oauth-scopes] Sim requests these scopes when someone connects a Bitbucket account. For a self-hosted deployment, register your own app with the provider using the settings below. See [Integrations and OAuth](/platform/self-hosting/integrations-oauth) for setup. diff --git a/apps/docs/content/docs/integrations/docusign-service-account.mdx b/apps/docs/content/docs/integrations/docusign-service-account.mdx new file mode 100644 index 00000000000..9abaab3b28e --- /dev/null +++ b/apps/docs/content/docs/integrations/docusign-service-account.mdx @@ -0,0 +1,88 @@ +--- +title: DocuSign JWT Grant +description: Connect DocuSign to Sim with an integration key and RSA keypair that acts as one DocuSign user, instead of a personal OAuth connection +--- + +import { Callout } from '@/components/ui/callout' +import { Step, Steps } from '@/components/ui/steps' + +Connect DocuSign with JWT Grant when a workflow should keep working without anyone signing in again. Sim signs a short-lived assertion with your app's RSA private key, exchanges it for an access token that acts as one DocuSign user, and repeats that every hour. DocuSign issues no refresh token for JWT Grant, so nothing expires as long as the key and the user's consent stay in place. + +Every envelope, template, and download runs as the impersonated user, with that user's DocuSign permissions. Use a dedicated user when you can. + +## Prerequisites + +- A DocuSign account in the environment you want: a free developer account (demo) or a production account +- Admin access to **Apps and Keys** in that account, to create the integration key + +## Create the integration key [#creating-the-integration-key] + + + + In DocuSign, open the **Apps and Keys** page and add an app. Give it a name (e.g. `Sim workflows`) and click **ADD** + + + Copy the integration key DocuSign assigns (a GUID) + + + Under **RSA key pair**, click **GENERATE RSA**. Copy the private key before you close the dialog, including its `BEGIN` and `END` lines. DocuSign masks it afterwards and can't show it again + + + Under **Redirect URI**, click **ADD URI** and enter the address you open Sim at (for example `https://sim.ai`). DocuSign requires a redirect URI for the consent step; Sim never uses what it receives there + + + Leave **User Application** set to **Yes** (the default) and click **SAVE** + + + + +The private key lets anyone holding it act as any user who has consented to this integration key. Sim encrypts it at rest and never shows it again. Treat it like a password. + + +## Find the user ID [#finding-the-user-id] + +The **Apps and Keys** page shows your **User ID** and **API Account ID**, both GUIDs. To act as a different user, use that user's ID instead. Use the user ID, not an email address. + +The account ID is optional. Sim uses the user's default account unless you enter one, so you only need it when the user belongs to more than one account. + +## Add the credential to Sim [#adding-the-credential-to-sim] + + + + Open **Integrations** from your workspace sidebar + + + Search for "DocuSign" and open it, then click **Add to Sim** and choose **Add JWT Grant app** + + + Choose the **Environment** the integration key was created in: **Developer (demo)** or **Production**. A key that hasn't gone live only works in the developer environment + + + Paste the integration key, the impersonated user ID, the RSA private key, and optionally the account ID + + + Click **Add JWT Grant app**. Sim requests a token and reads the user's accounts once to check everything matches + + + +## Grant consent [#granting-consent] + +DocuSign won't issue tokens for a user until that user (or an organization admin) consents to the integration key. The first time you add the credential, Sim shows an error with the exact consent link for your integration key and environment. Open the link signed in as the impersonated user and click **Accept**. DocuSign then redirects to the redirect URI you added; the page it lands on doesn't matter, so close it and add the credential again. + +You only need to consent once per user and integration key, unless the user revokes it. + +## Use the credential in workflows [#using-the-credential-in-workflows] + +Add a DocuSign block and select the saved credential in the account dropdown. Every DocuSign operation works with it the same way as with a connected account. Sim calls the eSignature REST API for the account it found when it last requested a token, in the environment stored on the credential. + +Knowledge base syncs from DocuSign can use the credential too. They read the same account in the same environment, and envelope links open in that environment's DocuSign web app. + +## Fix connection errors + +| Error | What to check | +| ----- | ------------- | +| Needs the impersonated user's consent | Open the consent link from the error signed in as that user, accept, and add the credential again. Consent can also be revoked later, which stops runs until it is granted again | +| Couldn't authenticate | The integration key, user ID, and private key must belong to the same app, in the environment you chose. A key created in the developer environment isn't valid in production until it goes live. A private key from a deleted keypair no longer works | +| User isn't a member of the account | The account ID you entered isn't one the user belongs to. Check it, or leave it blank | + +To rotate the key, generate a new RSA keypair on the integration key, reconnect the credential in Sim with the new private key, test a workflow, then delete the old keypair. DocuSign allows up to five keypairs per integration key. See [DocuSign's JWT Grant documentation](https://developers.docusign.com/platform/auth/jwt/jwt-get-token/). diff --git a/apps/docs/content/docs/integrations/docusign.mdx b/apps/docs/content/docs/integrations/docusign.mdx index b86be40bc45..b17fd5ce500 100644 --- a/apps/docs/content/docs/integrations/docusign.mdx +++ b/apps/docs/content/docs/integrations/docusign.mdx @@ -11,8 +11,12 @@ import { ReferenceDetails } from "@/components/ui/reference-details" {/* MANUAL-CONTENT-START:intro */} Use [DocuSign](https://www.docusign.com) to send envelopes for e-signature, create them from templates, inspect recipients and signing status, and download completed documents. Pending envelopes can be voided with a reason. + +Connect a DocuSign account through OAuth, or an integration key that acts as one user through [JWT Grant](/integrations/docusign-service-account). {/* MANUAL-CONTENT-END */} +Connection guides: [JWT Grant](/integrations/docusign-service-account). + ## OAuth scopes [#oauth-scopes] Sim requests these scopes when someone connects a DocuSign account. For a self-hosted deployment, register your own app with the provider using the settings below. See [Integrations and OAuth](/platform/self-hosting/integrations-oauth) for setup. diff --git a/apps/docs/content/docs/integrations/github.mdx b/apps/docs/content/docs/integrations/github.mdx index bb9c0cc5b8d..6d53cce14ca 100644 --- a/apps/docs/content/docs/integrations/github.mdx +++ b/apps/docs/content/docs/integrations/github.mdx @@ -2,7 +2,7 @@ title: GitHub description: Interact with GitHub or trigger workflows from GitHub events integration: - type: "github_v2" + type: "github_v3" color: "#181C1E" --- @@ -11,6 +11,8 @@ import { ReferenceDetails } from "@/components/ui/reference-details" {/* MANUAL-CONTENT-START:intro */} [GitHub](https://github.com/) hosts repositories and their pull requests, issues, and commit history. Use this integration to read repository content, automate code-review and issue workflows, and respond to GitHub events. Select an action below for its required repository identifiers, permissions, and inputs. + +Connect GitHub with a saved personal access token: in **Integrations**, open GitHub, click **Add to Sim**, and choose **Add personal access token**. Prefer a [fine-grained token](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens) limited to the repositories and permissions the workflow needs; a classic token with the `repo` scope also works. Sim verifies the token against `api.github.com/user`. GitHub answers **404 Not Found** or **403 Forbidden** when a token cannot reach a repository (a fine-grained token sees only the repositories it was given, plus public ones), and an organization that requires approval leaves a new fine-grained token read-only on public repositories until an owner approves it. GitHub Enterprise Server is not supported. {/* MANUAL-CONTENT-END */} ## Use the block [#usage-instructions] @@ -32,7 +34,6 @@ Fetch PR details including diff and files changed | `owner` | string | Yes | Repository owner | | `repo` | string | Yes | Repository name | | `pullNumber` | number | Yes | Pull request number | -| `apiKey` | string | Yes | GitHub API token | | `includeFiles` | boolean | No | Whether to fetch changed-file details from the separate files endpoint | #### Output @@ -112,7 +113,6 @@ Create comments on GitHub PRs | `path` | string | No | File path for review comment | | `commentType` | string | No | Type of comment \(pr_comment or file_comment\) | | `line` | number | No | Line number for review comment | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -148,7 +148,6 @@ Read GitHub repository metadata, including stars, forks, issues, and primary lan | --------- | ---- | -------- | ----------- | | `owner` | string | Yes | Repository owner \(user or organization\) | | `repo` | string | Yes | Repository name | -| `apiKey` | string | Yes | GitHub Personal Access Token | #### Output @@ -204,7 +203,6 @@ Retrieve the latest commit from a GitHub repository | `owner` | string | Yes | Repository owner \(user or organization\) | | `repo` | string | Yes | Repository name | | `branch` | string | No | Branch name \(defaults to the repository's default branch\) | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -267,7 +265,6 @@ Create a comment on a GitHub issue | `repo` | string | Yes | Repository name | | `issue_number` | number | Yes | Issue number | | `body` | string | Yes | Comment content | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -307,7 +304,6 @@ List all comments on a GitHub issue | `since` | string | No | Only show comments updated after this ISO 8601 timestamp | | `per_page` | number | No | Number of results per page \(max 100\) | | `page` | number | No | Page number | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -347,7 +343,6 @@ Update an existing comment on a GitHub issue or pull request | `repo` | string | Yes | Repository name | | `comment_id` | number | Yes | Comment ID | | `body` | string | Yes | Updated comment content | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -384,7 +379,6 @@ Delete a comment on a GitHub issue or pull request | `owner` | string | Yes | Repository owner | | `repo` | string | Yes | Repository name | | `comment_id` | number | Yes | Comment ID | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -413,7 +407,6 @@ List all review comments on a GitHub pull request | `since` | string | No | Only show comments updated after this ISO 8601 timestamp | | `per_page` | number | No | Number of results per page \(max 100\) | | `page` | number | No | Page number | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -460,7 +453,6 @@ Create a new pull request in a GitHub repository | `base` | string | Yes | The name of the branch you want the changes pulled into | | `body` | string | No | Pull request description \(Markdown\) | | `draft` | boolean | No | Create as draft pull request | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -500,7 +492,6 @@ Update an existing pull request in a GitHub repository | `body` | string | No | New pull request description \(Markdown\) | | `state` | string | No | New state \(open or closed\) | | `base` | string | No | New base branch name | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -538,7 +529,6 @@ Merge a pull request in a GitHub repository | `commit_title` | string | No | Title for the merge commit | | `commit_message` | string | No | Extra detail to append to merge commit message | | `merge_method` | string | No | Merge method: merge, squash, or rebase | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -569,7 +559,6 @@ List pull requests in a GitHub repository | `direction` | string | No | Sort direction: asc or desc | | `per_page` | number | No | Results per page \(max 100\) | | `page` | number | No | Page number | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -623,7 +612,6 @@ Get the list of files changed in a pull request | `pullNumber` | number | Yes | Pull request number | | `per_page` | number | No | Results per page \(max 100\) | | `page` | number | No | Page number | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -658,7 +646,6 @@ Close a pull request in a GitHub repository | `owner` | string | Yes | Repository owner | | `repo` | string | Yes | Repository name | | `pullNumber` | number | Yes | Pull request number | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -696,7 +683,6 @@ Request reviewers for a pull request | `pullNumber` | number | Yes | Pull request number | | `reviewers` | string | No | Comma-separated list of user logins to request reviews from \(at least one of reviewers or team_reviewers is required\) | | `team_reviewers` | string | No | Comma-separated list of team slugs to request reviews from | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -728,7 +714,6 @@ Submit a review for a pull request. Use APPROVE, REQUEST_CHANGES, or COMMENT. A | `body` | string | No | The body text of the review \(required for REQUEST_CHANGES and COMMENT\) | | `commit_id` | string | No | The SHA of the commit that needs a review \(required when posting inline comments; defaults to the most recent commit otherwise\) | | `comments` | array | No | Optional inline comments with required path, body, line, and side fields | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -764,7 +749,6 @@ Get the content of a file from a GitHub repository. Supports files up to 1MB. Co | `repo` | string | Yes | Repository name | | `path` | string | Yes | Path to the file in the repository \(e.g., "src/index.ts"\) | | `ref` | string | No | Branch name, tag, or commit SHA \(defaults to repository default branch\) | -| `apiKey` | string | Yes | GitHub Personal Access Token | #### Output @@ -801,7 +785,6 @@ Create a new file in a GitHub repository. The file content will be automatically | `message` | string | Yes | Commit message for this file creation | | `content` | string | Yes | File content \(plain text, will be Base64 encoded automatically\) | | `branch` | string | No | Branch to create the file in \(defaults to repository default branch\) | -| `apiKey` | string | Yes | GitHub Personal Access Token | #### Output @@ -829,7 +812,6 @@ Update an existing file in a GitHub repository. Requires the file SHA. Content w | `content` | string | Yes | New file content \(plain text, will be Base64 encoded automatically\) | | `sha` | string | Yes | The blob SHA of the file being replaced \(get from github_get_file_content\) | | `branch` | string | No | Branch to update the file in \(defaults to repository default branch\) | -| `apiKey` | string | Yes | GitHub Personal Access Token | #### Output @@ -856,7 +838,6 @@ Delete a file from a GitHub repository. Requires the file SHA. This operation ca | `message` | string | Yes | Commit message for this file deletion | | `sha` | string | Yes | The blob SHA of the file being deleted \(get from github_get_file_content\) | | `branch` | string | No | Branch to delete the file from \(defaults to repository default branch\) | -| `apiKey` | string | Yes | GitHub Personal Access Token | #### Output @@ -881,7 +862,6 @@ Get the contents of a directory in a GitHub repository. Returns a list of files | `repo` | string | Yes | Repository name | | `path` | string | No | Directory path \(e.g., "src/components"\). Leave empty for root directory. | | `ref` | string | No | Branch name, tag, or commit SHA \(defaults to repository default branch\) | -| `apiKey` | string | Yes | GitHub Personal Access Token | #### Output @@ -915,7 +895,6 @@ Get the preferred README for a GitHub repository, with its content decoded to pl | `owner` | string | Yes | Repository owner \(user or organization\) | | `repo` | string | Yes | Repository name | | `ref` | string | No | The name of the commit/branch/tag to read the README from \(defaults to the repository default branch\) | -| `apiKey` | string | Yes | GitHub Personal Access Token | #### Output @@ -946,7 +925,6 @@ List tags for a GitHub repository. Returns tag names with their commit SHA and d | `repo` | string | Yes | Repository name | | `per_page` | number | No | Number of results per page \(max 100\) | | `page` | number | No | Page number of the results to fetch | -| `apiKey` | string | Yes | GitHub Personal Access Token | #### Output @@ -979,7 +957,6 @@ List all branches in a GitHub repository. Optionally filter by protected status | `protected` | boolean | No | Filter branches by protection status | | `per_page` | number | No | Number of results per page \(max 100, default 30\) | | `page` | number | No | Page number for pagination \(default 1\) | -| `apiKey` | string | Yes | GitHub Personal Access Token | #### Output @@ -1008,7 +985,6 @@ Get detailed information about a specific branch in a GitHub repository, includi | `owner` | string | Yes | Repository owner \(user or organization\) | | `repo` | string | Yes | Repository name | | `branch` | string | Yes | Branch name | -| `apiKey` | string | Yes | GitHub Personal Access Token | #### Output @@ -1038,7 +1014,6 @@ Create a new branch in a GitHub repository by creating a git reference pointing | `repo` | string | Yes | Repository name | | `branch` | string | Yes | Name of the branch to create | | `sha` | string | Yes | Commit SHA to point the branch to | -| `apiKey` | string | Yes | GitHub Personal Access Token | #### Output @@ -1064,7 +1039,6 @@ Delete a branch from a GitHub repository by removing its git reference. Protecte | `owner` | string | Yes | Repository owner \(user or organization\) | | `repo` | string | Yes | Repository name | | `branch` | string | Yes | Name of the branch to delete | -| `apiKey` | string | Yes | GitHub Personal Access Token | #### Output @@ -1088,7 +1062,6 @@ Get the branch protection rules for a specific branch, including status checks, | `owner` | string | Yes | Repository owner \(user or organization\) | | `repo` | string | Yes | Repository name | | `branch` | string | Yes | Branch name | -| `apiKey` | string | Yes | GitHub Personal Access Token | #### Output @@ -1125,7 +1098,6 @@ Update branch protection rules for a specific branch, including status checks, r | `enforce_admins` | boolean | No | Whether to enforce restrictions for administrators. Omit to disable admin enforcement — GitHub receives an explicit null. | | `required_pull_request_reviews` | object | No | PR review requirements. Object with optional required_approving_review_count, dismiss_stale_reviews, require_code_owner_reviews. Omit to disable review requirements — GitHub receives an explicit null. | | `restrictions` | object | No | Push restrictions, available only for organization-owned repositories. Object with users \(string array\), teams \(string array\) and optional apps \(string array\). Omit to disable push restrictions — GitHub receives an explicit null. | -| `apiKey` | string | Yes | GitHub Personal Access Token | #### Output @@ -1162,7 +1134,6 @@ Create a new issue in a GitHub repository | `assignees` | string | No | Comma-separated list of usernames to assign to this issue | | `labels` | string | No | Comma-separated list of label names to add to this issue | | `milestone` | number | No | Milestone number to associate with this issue | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -1235,7 +1206,6 @@ Update an existing issue in a GitHub repository | `state` | string | No | Issue state \(open or closed\) | | `labels` | array | No | Array of label names \(replaces all existing labels\) | | `assignees` | array | No | Array of usernames \(replaces all existing assignees\) | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -1310,7 +1280,6 @@ List issues in a GitHub repository. Note: This includes pull requests as PRs are | `direction` | string | No | Sort direction: asc or desc \(default: desc\) | | `per_page` | number | No | Results per page \(max 100, default: 30\) | | `page` | number | No | Page number \(default: 1\) | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -1341,7 +1310,6 @@ Get detailed information about a specific issue in a GitHub repository | `owner` | string | Yes | Repository owner | | `repo` | string | Yes | Repository name | | `issue_number` | number | Yes | Issue number | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -1416,7 +1384,6 @@ Close an issue in a GitHub repository | `repo` | string | Yes | Repository name | | `issue_number` | number | Yes | Issue number | | `state_reason` | string | No | Reason for closing: completed or not_planned | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -1469,7 +1436,6 @@ Add labels to an issue in a GitHub repository | `repo` | string | Yes | Repository name | | `issue_number` | number | Yes | Issue number | | `labels` | string | Yes | Comma-separated list of label names to add to the issue | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -1498,7 +1464,6 @@ Remove a label from an issue in a GitHub repository | `repo` | string | Yes | Repository name | | `issue_number` | number | Yes | Issue number | | `name` | string | Yes | Label name to remove | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -1527,7 +1492,6 @@ Add assignees to an issue in a GitHub repository | `repo` | string | Yes | Repository name | | `issue_number` | number | Yes | Issue number | | `assignees` | string | Yes | Comma-separated list of usernames to assign to the issue | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -1565,7 +1529,6 @@ Create a new release for a GitHub repository. Specify tag name, target commit, t | `body` | string | No | Text describing the contents of the release \(markdown supported\) | | `draft` | boolean | No | true to create a draft \(unpublished\) release, false to create a published one | | `prerelease` | boolean | No | true to identify the release as a prerelease, false to identify as a full release | -| `apiKey` | string | Yes | GitHub Personal Access Token | #### Output @@ -1630,7 +1593,6 @@ Update an existing GitHub release. Modify tag name, target commit, title, descri | `body` | string | No | Text describing the contents of the release \(markdown supported\) | | `draft` | boolean | No | true to set as draft, false to publish | | `prerelease` | boolean | No | true to identify as a prerelease, false for a full release | -| `apiKey` | string | Yes | GitHub Personal Access Token | #### Output @@ -1690,7 +1652,6 @@ List all releases for a GitHub repository. Returns release information including | `repo` | string | Yes | Repository name | | `per_page` | number | No | Number of results per page \(max 100\) | | `page` | number | No | Page number of the results to fetch | -| `apiKey` | string | Yes | GitHub Personal Access Token | #### Output @@ -1751,7 +1712,6 @@ Get detailed information about a specific GitHub release by ID. Returns release | `owner` | string | Yes | Repository owner \(user or organization\) | | `repo` | string | Yes | Repository name | | `release_id` | number | Yes | The unique identifier of the release | -| `apiKey` | string | Yes | GitHub Personal Access Token | #### Output @@ -1809,7 +1769,6 @@ Get the latest published, non-draft, non-prerelease release for a GitHub reposit | --------- | ---- | -------- | ----------- | | `owner` | string | Yes | Repository owner \(user or organization\) | | `repo` | string | Yes | Repository name | -| `apiKey` | string | Yes | GitHub Personal Access Token | #### Output @@ -1868,7 +1827,6 @@ Delete a GitHub release by ID. This permanently removes the release but does not | `owner` | string | Yes | Repository owner \(user or organization\) | | `repo` | string | Yes | Repository name | | `release_id` | number | Yes | The unique identifier of the release to delete | -| `apiKey` | string | Yes | GitHub Personal Access Token | #### Output @@ -1893,7 +1851,6 @@ List all workflows in a GitHub repository. Returns workflow details including ID | `repo` | string | Yes | Repository name | | `per_page` | number | No | Number of results per page \(default: 30, max: 100\) | | `page` | number | No | Page number of results to fetch \(default: 1\) | -| `apiKey` | string | Yes | GitHub Personal Access Token | #### Output @@ -1928,7 +1885,6 @@ Get details of a specific GitHub Actions workflow by ID or filename. Returns wor | `owner` | string | Yes | Repository owner \(user or organization\) | | `repo` | string | Yes | Repository name | | `workflow_id` | string | Yes | Workflow ID \(number\) or workflow filename \(e.g., "main.yaml"\) | -| `apiKey` | string | Yes | GitHub Personal Access Token | #### Output @@ -1963,7 +1919,6 @@ Trigger a workflow dispatch event for a GitHub Actions workflow. The workflow mu | `workflow_id` | string | Yes | Workflow ID \(number\) or workflow filename \(e.g., "main.yaml"\) | | `ref` | string | Yes | Git reference \(branch or tag name\) to run the workflow on | | `inputs` | object | No | Input keys and values configured in the workflow file | -| `apiKey` | string | Yes | GitHub Personal Access Token | #### Output @@ -1994,7 +1949,6 @@ List workflow runs for a repository, or for a single workflow when a workflow ID | `status` | string | No | Filter by status \(queued, in_progress, completed, waiting, requested, pending\) | | `per_page` | number | No | Number of results per page \(default: 30, max: 100\) | | `page` | number | No | Page number of results to fetch \(default: 1\) | -| `apiKey` | string | Yes | GitHub Personal Access Token | #### Output @@ -2021,7 +1975,6 @@ Get detailed information about a specific workflow run by ID. Returns status, co | `owner` | string | Yes | Repository owner \(user or organization\) | | `repo` | string | Yes | Repository name | | `run_id` | number | Yes | Workflow run ID | -| `apiKey` | string | Yes | GitHub Personal Access Token | #### Output @@ -2079,7 +2032,6 @@ Cancel a workflow run. Returns 202 Accepted if cancellation is initiated, or 409 | `owner` | string | Yes | Repository owner \(user or organization\) | | `repo` | string | Yes | Repository name | | `run_id` | number | Yes | Workflow run ID to cancel | -| `apiKey` | string | Yes | GitHub Personal Access Token | #### Output @@ -2104,7 +2056,6 @@ Rerun a workflow run. Optionally enable debug logging for the rerun. Returns 201 | `repo` | string | Yes | Repository name | | `run_id` | number | Yes | Workflow run ID to rerun | | `enable_debug_logging` | boolean | No | Enable debug logging for the rerun \(default: false\) | -| `apiKey` | string | Yes | GitHub Personal Access Token | #### Output @@ -2127,7 +2078,6 @@ List GitHub Projects V2 for an organization or user. Returns up to 20 projects w | --------- | ---- | -------- | ----------- | | `owner_type` | string | Yes | Owner type: "org" for organization or "user" for user | | `owner_login` | string | Yes | Organization or user login name | -| `apiKey` | string | Yes | GitHub Personal Access Token with project read permissions | #### Output @@ -2158,7 +2108,6 @@ Get detailed information about a specific GitHub Project V2 by its number. Retur | `owner_type` | string | Yes | Owner type: "org" for organization or "user" for user | | `owner_login` | string | Yes | Organization or user login name | | `project_number` | number | Yes | Project number | -| `apiKey` | string | Yes | GitHub Personal Access Token with project read permissions | #### Output @@ -2189,7 +2138,6 @@ Create a new GitHub Project V2. Requires the owner Node ID (not login name). Ret | --------- | ---- | -------- | ----------- | | `owner_id` | string | Yes | Node ID of the owning user or organization, not a project ID or login name. Retrieve the owner id through the GitHub GraphQL API. | | `title` | string | Yes | Project title | -| `apiKey` | string | Yes | GitHub Personal Access Token with project write permissions | #### Output @@ -2220,7 +2168,6 @@ Update an existing GitHub Project V2. Can update title, description, visibility | `shortDescription` | string | No | New project short description | | `project_public` | boolean | No | Set project visibility \(true = public, false = private\) | | `closed` | boolean | No | Set project status \(true = closed, false = open\) | -| `apiKey` | string | Yes | GitHub Personal Access Token with project write permissions | #### Output @@ -2247,7 +2194,6 @@ Delete a GitHub Project V2. This action is permanent and cannot be undone. Requi | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `project_id` | string | Yes | Project Node ID \(format: PVT_...\) | -| `apiKey` | string | Yes | GitHub Personal Access Token with project admin permissions | #### Output @@ -2275,7 +2221,6 @@ Search for code across GitHub repositories. Use qualifiers like repo:owner/name, | `order` | string | No | Sort order: asc or desc \(default: desc\) | | `per_page` | number | No | Results per page \(max 100, default: 30\) | | `page` | number | No | Page number \(default: 1\) | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -2336,7 +2281,6 @@ Search for commits across GitHub. Use qualifiers like repo:owner/name, author:us | `order` | string | No | Sort order: asc or desc \(default: desc\) | | `per_page` | number | No | Results per page \(max 100, default: 30\) | | `page` | number | No | Page number \(default: 1\) | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -2423,7 +2367,6 @@ Search for issues and pull requests across GitHub. Use qualifiers like repo:owne | `order` | string | No | Sort order: asc or desc \(default: desc\) | | `per_page` | number | No | Results per page \(max 100, default: 30\) | | `page` | number | No | Page number \(default: 1\) | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -2515,7 +2458,6 @@ Search for repositories across GitHub. Use qualifiers like language:python, star | `order` | string | No | Sort order: asc or desc \(default: desc\) | | `per_page` | number | No | Results per page \(max 100, default: 30\) | | `page` | number | No | Page number \(default: 1\) | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -2579,7 +2521,6 @@ Search for users and organizations on GitHub. Use qualifiers like type:user, typ | `order` | string | No | Sort order: asc or desc \(default: desc\) | | `per_page` | number | No | Results per page \(max 100, default: 30\) | | `page` | number | No | Page number \(default: 1\) | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -2627,7 +2568,6 @@ List commits in a repository with optional filtering by SHA, path, author, commi | `until` | string | No | Only commits before this date \(ISO 8601 format\) | | `per_page` | number | No | Results per page \(max 100, default: 30\) | | `page` | number | No | Page number \(default: 1\) | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -2698,7 +2638,6 @@ Get detailed information about a specific commit including files changed and sta | `owner` | string | Yes | Repository owner | | `repo` | string | Yes | Repository name | | `ref` | string | Yes | Commit SHA, branch name, or tag name | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -2786,7 +2725,6 @@ Compare two commits or branches to see the diff, commits between them, and chang | `head` | string | Yes | Head branch/tag/SHA for comparison | | `per_page` | number | No | Results per page for files \(max 100, default: 30\) | | `page` | number | No | Page number for files \(default: 1\) | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -2914,7 +2852,6 @@ Create a new gist with one or more files | `description` | string | No | Description of the gist | | `files` | json | Yes | JSON object with filenames as keys and content as values. Example: \{"file.txt": \{"content": "Hello"\}\} | | `public` | boolean | No | Whether the gist is public \(default: false\) | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -2959,7 +2896,6 @@ Get a gist by ID including its file contents | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `gist_id` | string | Yes | The gist ID | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -3007,7 +2943,6 @@ List gists for a user or the authenticated user | `since` | string | No | Only gists updated after this time \(ISO 8601\) | | `per_page` | number | No | Results per page \(max 100, default: 30\) | | `page` | number | No | Page number \(default: 1\) | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -3056,7 +2991,6 @@ Update a gist description or files. To delete a file, set its value to null in f | `gist_id` | string | Yes | The gist ID to update | | `description` | string | No | New description for the gist | | `files` | json | No | JSON object with filenames as keys. Set to null to delete, or provide content to update/add | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -3101,7 +3035,6 @@ Delete a gist by ID | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `gist_id` | string | Yes | The gist ID to delete | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -3123,7 +3056,6 @@ Fork a gist to create your own copy | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `gist_id` | string | Yes | The gist ID to fork | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -3150,7 +3082,6 @@ Star a gist | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `gist_id` | string | Yes | The gist ID to star | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -3172,7 +3103,6 @@ Unstar a gist | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | | `gist_id` | string | Yes | The gist ID to unstar | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -3198,7 +3128,6 @@ Fork a repository to your account or an organization | `organization` | string | No | Organization to fork into \(omit to fork to your account\) | | `name` | string | No | Custom name for the forked repository | | `default_branch_only` | boolean | No | Only fork the default branch \(default: false\) | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -3254,7 +3183,6 @@ List forks of a repository | `sort` | string | No | Sort by: newest, oldest, stargazers, watchers \(default: newest\) | | `per_page` | number | No | Results per page \(max 100, default: 30\) | | `page` | number | No | Page number \(default: 1\) | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -3312,7 +3240,6 @@ Create a milestone in a repository | `state` | string | No | State: open or closed \(default: open\) | | `description` | string | No | Milestone description | | `due_on` | string | No | Due date \(ISO 8601 format, e.g., 2024-12-31T23:59:59Z\) | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -3358,7 +3285,6 @@ Get a specific milestone by number | `owner` | string | Yes | Repository owner | | `repo` | string | Yes | Repository name | | `milestone_number` | number | Yes | Milestone number | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -3408,7 +3334,6 @@ List milestones in a repository | `direction` | string | No | Sort direction: asc or desc \(default: asc\) | | `per_page` | number | No | Results per page \(max 100, default: 30\) | | `page` | number | No | Page number \(default: 1\) | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -3460,7 +3385,6 @@ Update a milestone in a repository | `state` | string | No | New state: open or closed | | `description` | string | No | New description | | `due_on` | string | No | New due date \(ISO 8601 format\) | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -3506,7 +3430,6 @@ Delete a milestone from a repository | `owner` | string | Yes | Repository owner | | `repo` | string | Yes | Repository name | | `milestone_number` | number | Yes | Milestone number to delete | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -3531,7 +3454,6 @@ Add a reaction to an issue | `repo` | string | Yes | Repository name | | `issue_number` | number | Yes | Issue number | | `content` | string | Yes | Reaction type: +1 \(thumbs up\), -1 \(thumbs down\), laugh, confused, heart, hooray, rocket, eyes | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -3564,7 +3486,6 @@ Remove a reaction from an issue | `repo` | string | Yes | Repository name | | `issue_number` | number | Yes | Issue number | | `reaction_id` | number | Yes | Reaction ID to delete | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -3589,7 +3510,6 @@ Add a reaction to an issue comment | `repo` | string | Yes | Repository name | | `comment_id` | number | Yes | Comment ID | | `content` | string | Yes | Reaction type: +1 \(thumbs up\), -1 \(thumbs down\), laugh, confused, heart, hooray, rocket, eyes | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -3622,7 +3542,6 @@ Remove a reaction from an issue comment | `repo` | string | Yes | Repository name | | `comment_id` | number | Yes | Comment ID | | `reaction_id` | number | Yes | Reaction ID to delete | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -3645,7 +3564,6 @@ Star a repository | --------- | ---- | -------- | ----------- | | `owner` | string | Yes | Repository owner | | `repo` | string | Yes | Repository name | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -3669,7 +3587,6 @@ Remove star from a repository | --------- | ---- | -------- | ----------- | | `owner` | string | Yes | Repository owner | | `repo` | string | Yes | Repository name | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -3693,7 +3610,6 @@ Check if you have starred a repository | --------- | ---- | -------- | ----------- | | `owner` | string | Yes | Repository owner | | `repo` | string | Yes | Repository name | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -3719,7 +3635,6 @@ List users who have starred a repository | `repo` | string | Yes | Repository name | | `per_page` | number | No | Results per page \(max 100, default: 30\) | | `page` | number | No | Page number \(default: 1\) | -| `apiKey` | string | Yes | GitHub API token | #### Output @@ -3760,7 +3675,6 @@ List one page of a pull request's review threads with their comments, plus the n | `threadsPerPage` | number | No | Review threads to fetch in this page \(1-100\) | | `commentsPerThread` | number | No | Comments to fetch per thread \(1-100\) | | `cursor` | string | No | Cursor from a previous page \(endCursor\) to continue from | -| `apiKey` | string | Yes | GitHub API token with pull request read access | #### Output diff --git a/apps/docs/content/docs/integrations/google-service-account.mdx b/apps/docs/content/docs/integrations/google-service-account.mdx index 5e31e7f8678..1aeb3fe868d 100644 --- a/apps/docs/content/docs/integrations/google-service-account.mdx +++ b/apps/docs/content/docs/integrations/google-service-account.mdx @@ -11,6 +11,8 @@ Google service accounts can access shared resources directly or impersonate a Go For example, you could build a workflow that iterates through a list of employees, impersonates each one to read their Google Docs, and uploads the contents to a shared knowledge base — all without requiring any of those users to sign in. +For Google Cloud APIs such as BigQuery and Vertex AI, you can skip the JSON key entirely: see [Keyless Google Cloud access](#keyless-google-cloud-access). + ## Prerequisites Create the service account and enable its APIs in Google Cloud. Configure the Google Workspace Admin Console only when using domain-wide delegation. @@ -172,3 +174,67 @@ Leave **Impersonated Account** blank to authenticate as the service account itse Domain-wide delegation requires a Google Workspace super administrator. It authorizes impersonation within that Workspace domain, subject to the authorized scopes and the impersonated user’s access. Consumer Gmail accounts and users outside that domain cannot be impersonated. Access also depends on the license required by the target service. See [Google’s service-account authorization guide](https://developers.google.com/identity/protocols/oauth2/service-account). A credential can serve multiple supported Google services when their APIs and scopes are configured. To rotate its key, create a replacement JSON key, update the credential in Sim, verify access, then delete the old key in Google Cloud. + +## Keyless Google Cloud access [#keyless-google-cloud-access] + +A Google service account credential can also be **keyless**: Sim stores no key. Instead, your Google Cloud project trusts Sim through [Workload Identity Federation](https://cloud.google.com/iam/docs/workload-identity-federation-with-other-providers). On each run, Sim signs a short-lived token for this credential's own subject, exchanges it at Google's Security Token Service for a federated token, and uses that to impersonate your service account. The service account's IAM roles decide what workflows can do, exactly as with a JSON key. + + +Keyless credentials work with Google Cloud APIs that the service account calls as itself: **BigQuery**, and **Vertex AI** wherever a Google service account credential is accepted. They can't use domain-wide delegation, so Gmail, Drive, Sheets, Calendar, and other Google Workspace blocks don't offer them, and a keyless credential refuses an **Impersonated Account**. Use a JSON key for those. + + + + + In the [Google Cloud Console](https://console.cloud.google.com/), enable the IAM, Service Account Credentials, and Security Token Service APIs in the project that will hold the workload identity pool, and note its **project number** (on the project's Dashboard; it's numeric, not the project ID). + + + Create or pick a service account, and grant it the roles your workflows need (for example, BigQuery Data Viewer and BigQuery Job User, or Vertex AI User). No key is needed. + + + In Sim, open the **Google BigQuery** integration, choose **Add service account**, and set **Authentication** to **Workload Identity Federation (keyless, via Sim OIDC)**. Enter the project number, a pool ID and provider ID (4 to 32 lowercase letters, digits, or hyphens, not starting with `gcp-`), and the service account email (`name@project-id.iam.gserviceaccount.com`). + + + The dialog shows the **Issuer**, **Audience**, and **Subject**, and three `gcloud` commands with your values filled in. Run them in that project. They run against the project number you entered and create the pool, an OIDC provider for Sim's issuer with the attribute mapping `google.subject=assertion.sub` and an attribute condition that accepts only this credential's subject, and grant that subject `roles/iam.workloadIdentityUser` on the service account: + + ```bash + gcloud iam workload-identity-pools create POOL_ID \ + --project="PROJECT_NUMBER" \ + --location="global" \ + --display-name="Sim" + + gcloud iam workload-identity-pools providers create-oidc PROVIDER_ID \ + --project="PROJECT_NUMBER" \ + --location="global" \ + --workload-identity-pool="POOL_ID" \ + --issuer-uri="ISSUER" \ + --attribute-mapping="google.subject=assertion.sub" \ + --attribute-condition="assertion.sub=='SUBJECT'" + + gcloud iam service-accounts add-iam-policy-binding SERVICE_ACCOUNT_EMAIL \ + --project="PROJECT_NUMBER" \ + --role="roles/iam.workloadIdentityUser" \ + --member="principal://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/subject/SUBJECT" + ``` + + The provider sets no allowed audiences, so it accepts its own resource name, which is the **Audience** the dialog shows. + + + Save in Sim. Sim exchanges a token at STS and impersonates the service account; a token from that step proves the setup works. It also checks that a subject no credential holds can't impersonate the service account, so only this credential can use it. New IAM bindings can take a few minutes to apply; if saving fails right after you run the commands, wait and try again. + + + + +Keep the attribute condition and bind the role to the exact `principal://…/subject/SUBJECT` member. Without the condition, the provider accepts a token for any Sim subject, and a role granted to a `principalSet` for the whole pool would let other Sim credentials act with it. Sim refuses to save a service account that another subject can impersonate, but it can't see roles you grant the pool directly on other resources. + + +Each keyless credential has its own subject; reconnecting keeps it by default so your provider and binding keep working. Use one provider per credential (a pool can hold many). Keyless credentials are available for workspace credentials, not organization credentials. Sim uses impersonation rather than direct federated access because some Google Cloud APIs don't accept federated tokens, and impersonation keeps the same identity a JSON key would use. + +Self-hosted deployments need `WORKLOAD_IDENTITY_SIGNING_KEY` set and an `https` issuer Google can reach over the public internet. See [AWS credentials](/integrations/aws-credentials#self-hosted-deployments). + +### Troubleshooting keyless access + +- **"Google Cloud refused Sim's token for this workload identity provider":** the project number, pool ID, or provider ID doesn't match; the provider is disabled, has allowed audiences set, or uses a different issuer; or its attribute condition doesn't allow this credential's subject. +- **"Google Cloud could not fetch the signing keys from Sim's issuer":** the issuer isn't reachable over public HTTPS (self-hosted deployments). +- **"The service account … does not let this credential impersonate it":** run the `add-iam-policy-binding` command with the exact member shown, and enable the IAM Service Account Credentials API. +- **"This service account also trusts other Sim credentials":** remove any `principalSet` binding for the pool from the service account and keep the attribute condition. +- **A block fails with "This credential cannot be used here":** the block is a Google Workspace block or sets an **Impersonated Account**. Use a JSON key credential for it. diff --git a/apps/docs/content/docs/integrations/meta.json b/apps/docs/content/docs/integrations/meta.json index e58780b050c..1193d5113c4 100644 --- a/apps/docs/content/docs/integrations/meta.json +++ b/apps/docs/content/docs/integrations/meta.json @@ -25,6 +25,7 @@ "azure_data_explorer", "azure_devops", "bitbucket", + "bitbucket-service-account", "box", "box-service-account", "brandfetch", @@ -65,6 +66,7 @@ "devin", "discord", "docusign", + "docusign-service-account", "downdetector", "dropbox", "dropcontact", @@ -171,6 +173,7 @@ "manageengine_sdp", "mem0", "memory", + "microsoft-app-credentials", "microsoft_ad", "microsoft_dataverse", "microsoft_dynamics_365", diff --git a/apps/docs/content/docs/integrations/microsoft-app-credentials.mdx b/apps/docs/content/docs/integrations/microsoft-app-credentials.mdx new file mode 100644 index 00000000000..caafcf050be --- /dev/null +++ b/apps/docs/content/docs/integrations/microsoft-app-credentials.mdx @@ -0,0 +1,72 @@ +--- +title: Microsoft app credentials +description: Run Microsoft Entra ID, SharePoint, Dataverse, and Dynamics 365 blocks as an app registration with a client secret, a certificate, or a keyless federated credential that trusts Sim +--- + +import { Callout } from '@/components/ui/callout' +import { Step, Steps } from '@/components/ui/steps' + +A Microsoft app credential signs in as a Microsoft Entra app registration instead of a person (the OAuth 2.0 client credentials flow). One credential works for the **Azure AD** (Microsoft Entra ID), **SharePoint**, **Microsoft Dataverse**, and **Dynamics 365** blocks. Connecting a Microsoft account through OAuth keeps working exactly as before; the app credential is an additional option in the same account picker. + + +Outlook, OneDrive, Excel, Word, Planner, and Teams act on behalf of a signed-in person and don't accept an app credential. The Azure AD **Reset password** operation also needs a signed-in admin, because Microsoft Graph doesn't support application permissions for it. + + +## Choose how the app signs in + +| Option | What Sim stores | When to use it | +| --- | --- | --- | +| **Federated credential (keyless, via Sim OIDC)** | Nothing secret: the tenant ID, client ID, and this credential's subject | Recommended. No secret to rotate, expire, or leak. | +| **Client secret** | The tenant ID, client ID, and client secret | Quick setup. Secrets expire, so plan to rotate them. | +| **Certificate** | The tenant ID, client ID, the certificate, and its private key | When your organization requires certificate credentials. Sim signs each token request with the key. | + +Every option resolves on Sim's servers at run time, and tokens never appear in block outputs, logs, or anything a model sees. Azure AD and SharePoint blocks get a Microsoft Graph token; Dataverse and Dynamics 365 blocks get a token for the credential's own environment. + +## Register the app and grant permissions + + + + In the [Microsoft Entra admin center](https://entra.microsoft.com), go to **App registrations** → **New registration**. A single-tenant app is fine. Copy the **Application (client) ID** and **Directory (tenant) ID** from its Overview page. + + + Under **API permissions** → **Add a permission** → **Microsoft Graph** → **Application permissions**, add what your workflows need, then select **Grant admin consent**. Application permissions always need admin consent. For example: + - Azure AD: `User.Read.All` or `User.ReadWrite.All`, `Group.ReadWrite.All`, `GroupMember.ReadWrite.All`, `AuditLog.Read.All` for sign-in and audit logs, `Policy.Read.All` for conditional access, `UserAuthenticationMethod.Read.All` for authentication methods, `User.RevokeSessions.All` to revoke sessions. Setting a password needs `User-PasswordProfile.ReadWrite.All` **and** the app assigned at least the User Administrator role. + - SharePoint: `Sites.Read.All` or `Sites.ReadWrite.All`. Creating and editing pages needs `Sites.ReadWrite.All`. `Sites.Selected` limits the app to sites you grant it, but searching for sites doesn't work with it, so enter site IDs directly. + + + Dataverse and Dynamics 365 don't use API permissions. Instead, in the [Power Platform admin center](https://admin.powerplatform.microsoft.com), open the environment → **Settings** → **Users + permissions** → **Application users** → **New app user**, add this app, pick a business unit, and assign a security role. Then enter the environment URL (like `https://contoso.crm.dynamics.com`) on the credential. + + + +## Set up a keyless federated credential [#keyless-federated-credential] + + + + In Sim, add a **Microsoft app credential**, choose **Federated credential (keyless, via Sim OIDC)**, and enter the tenant ID and client ID. The dialog shows an **Issuer**, **Audience**, and **Subject**. + + + In the app registration, go to **Certificates & secrets** → **Federated credentials** → **Add credential** → **Other issuer**. Paste the **Issuer** and the **Subject identifier** exactly as shown, set the audience to `api://AzureADTokenExchange` (the dialog's value), and give it a name. Matching is case-sensitive. + + + Save in Sim. Sim requests a token as the app and reads the app's own service principal from Microsoft Graph, which needs no extra permission. It also checks that the app refuses a subject no credential holds, so only this credential can use the app. A new federated credential can take a few minutes to take effect; if saving fails with a matching error right after you add it, wait and try again. + + + +An app can have up to 20 federated credentials. Each Sim credential has its own subject, and reconnecting keeps the subject by default so the federated credential keeps working. Keyless credentials are available for workspace credentials, not organization credentials. + +## Use a client secret or certificate + +- **Client secret:** under **Certificates & secrets** → **Client secrets** → **New client secret**, copy the secret's **Value** (not the Secret ID). +- **Certificate:** upload the certificate's public part (`.cer`, `.pem`, or `.crt`) under **Certificates & secrets** → **Certificates**, then paste the certificate and its unencrypted PEM RSA private key (2048 to 4096 bits) into Sim. Sim checks the key belongs to the certificate before saving, and signs a PS256 assertion with the certificate's SHA-256 thumbprint. + +## Self-hosted deployments + +Keyless credentials need `WORKLOAD_IDENTITY_SIGNING_KEY` set and an `https` issuer Microsoft Entra can reach over the public internet. See [AWS credentials](/integrations/aws-credentials#self-hosted-deployments) for the same settings and for rotating the signing key. App credentials use the global Microsoft Entra endpoint (`login.microsoftonline.com`) and public-cloud Dataverse environments. + +## Troubleshooting + +- **"No federated credential on this app matches…":** the federated credential's issuer, subject, or audience differs from the dialog (check case and trailing slashes), it's on a different app than the client ID, or it was added moments ago. +- **"Microsoft Entra rejected the client secret":** you pasted the Secret ID, or the secret was deleted. **"This client secret has expired":** create a new one and reconnect. +- **"…could not verify the signed assertion":** the certificate in Sim isn't the one uploaded to the app registration. +- **"…the Dataverse environment did not accept it":** add the app as an application user of the environment with a security role. +- **A block fails with 403 "Insufficient privileges":** the app is missing an application permission for that operation, or admin consent wasn't granted after adding it. diff --git a/apps/docs/content/docs/integrations/microsoft_ad.mdx b/apps/docs/content/docs/integrations/microsoft_ad.mdx index 1ab1662a7b1..b3ba8497c9c 100644 --- a/apps/docs/content/docs/integrations/microsoft_ad.mdx +++ b/apps/docs/content/docs/integrations/microsoft_ad.mdx @@ -13,6 +13,8 @@ import { ReferenceDetails } from "@/components/ui/reference-details" Use [Microsoft Entra ID](https://entra.microsoft.com), formerly Azure Active Directory, to manage directory users, groups, memberships, licenses, passwords, sign-in sessions, app roles, and directory roles. Read sign-in and audit logs, registered devices, and conditional access policies; device writes are excluded. Use OData filters to query directory records. Grant the connection the permissions and administrative roles required by each operation before using it for onboarding, offboarding, or access review. Microsoft 365 groups have a 30-day recovery window. Cloud security-group recovery is a [public-cloud preview with tenant restrictions](https://learn.microsoft.com/en-us/entra/identity/users/groups-restore-deleted); confirm eligibility before deleting a group. + +To run as an app registration instead of a signed-in admin, use a [Microsoft app credential](/integrations/microsoft-app-credentials). {/* MANUAL-CONTENT-END */} ## OAuth scopes [#oauth-scopes] diff --git a/apps/docs/content/docs/integrations/microsoft_dataverse.mdx b/apps/docs/content/docs/integrations/microsoft_dataverse.mdx index e846aa23bc7..dc1510f15eb 100644 --- a/apps/docs/content/docs/integrations/microsoft_dataverse.mdx +++ b/apps/docs/content/docs/integrations/microsoft_dataverse.mdx @@ -11,6 +11,8 @@ import { ReferenceDetails } from "@/components/ui/reference-details" {/* MANUAL-CONTENT-START:intro */} Use [Microsoft Dataverse](https://learn.microsoft.com/en-us/power-apps/maker/data-platform/data-platform-intro) to manage records and relationships in Dynamics 365, Power Platform, or custom environments. The block also supports queries, bulk operations, file transfer, metadata lookup, and Dataverse actions and functions. + +To run as an application user instead of a signed-in person, use a [Microsoft app credential](/integrations/microsoft-app-credentials). {/* MANUAL-CONTENT-END */} ## OAuth scopes [#oauth-scopes] diff --git a/apps/docs/content/docs/integrations/microsoft_dynamics_365.mdx b/apps/docs/content/docs/integrations/microsoft_dynamics_365.mdx index ad857b39fc2..a2e540d4a6a 100644 --- a/apps/docs/content/docs/integrations/microsoft_dynamics_365.mdx +++ b/apps/docs/content/docs/integrations/microsoft_dynamics_365.mdx @@ -18,6 +18,8 @@ Two block operations intentionally reuse the new CRM tools under a simpler CRM l - **Assign Record** updates the selected record's `ownerid@odata.bind` to an explicitly chosen user or team. Connect one credential per Dynamics environment. The credential is bound to that environment during Microsoft OAuth, and CRM requests refuse a different environment. This release supports public-cloud Dataverse hosts only. + +To run as an application user instead of a signed-in person, use a [Microsoft app credential](/integrations/microsoft-app-credentials). {/* MANUAL-CONTENT-END */} ## OAuth scopes [#oauth-scopes] diff --git a/apps/docs/content/docs/integrations/sharepoint.mdx b/apps/docs/content/docs/integrations/sharepoint.mdx index a6aa7dd4bad..5d1384a8484 100644 --- a/apps/docs/content/docs/integrations/sharepoint.mdx +++ b/apps/docs/content/docs/integrations/sharepoint.mdx @@ -11,6 +11,8 @@ import { ReferenceDetails } from "@/components/ui/reference-details" {/* MANUAL-CONTENT-START:intro */} Use [SharePoint](https://www.microsoft.com/en-us/microsoft-365/sharepoint/collaboration) in Sim to list sites, manage pages and lists, update list items, and upload or download files. Connect a Microsoft account through OAuth, then choose the target site or resource for each operation. + +To run as an app registration instead of a signed-in person, use a [Microsoft app credential](/integrations/microsoft-app-credentials). {/* MANUAL-CONTENT-END */} ## OAuth scopes [#oauth-scopes] diff --git a/apps/docs/content/docs/integrations/snowflake-service-account.mdx b/apps/docs/content/docs/integrations/snowflake-service-account.mdx index a32fbee19d8..f513f3bee7a 100644 --- a/apps/docs/content/docs/integrations/snowflake-service-account.mdx +++ b/apps/docs/content/docs/integrations/snowflake-service-account.mdx @@ -1,16 +1,60 @@ --- -title: Snowflake programmatic access tokens -description: Create a Snowflake programmatic access token and connect it to Sim so workflows can query your account +title: Snowflake connections +description: Connect Snowflake to Sim with a keyless service user that trusts Sim through OpenID Connect, or with a programmatic access token --- import { Callout } from '@/components/ui/callout' import { Step, Steps } from '@/components/ui/steps' -Connect Snowflake with a programmatic access token (PAT) and account host. The token belongs to one user; use `ROLE_RESTRICTION` to limit it to a role with the access your workflows need. +A Snowflake connection holds your account host and how Sim signs in to it: -Sim stores the token alongside your account host as one credential. Once it is added, every Snowflake block picks it from a dropdown — and the block's database, schema, table, warehouse, role, file-format, and procedure fields become pickers that list what the token can actually see. +| Option | What Sim stores | When to use it | +| --- | --- | --- | +| **Service user (keyless, via Sim OIDC)** | Nothing secret: the account host only | Recommended where available. No token to rotate, expire, or leak. | +| **Programmatic access token** | A programmatic access token (PAT) | Any account, and deployments without keyless support. The token belongs to one user; use `ROLE_RESTRICTION` to limit it to a role with the access your workflows need. | + +Sim stores the connection as one credential. Once it is added, every Snowflake block picks it from a dropdown — and the block's database, schema, table, warehouse, role, file-format, and procedure fields become pickers that list what the token can actually see. + +## Set up a keyless service user [#keyless-service-user] + +Snowflake's [workload identity federation](https://docs.snowflake.com/en/user-guide/workload-identity-federation) lets a service user trust an OpenID Connect issuer instead of holding a password or token. Sim signs a short-lived token for your connection on every run, and Snowflake accepts it only for the service user created with Sim's issuer and this connection's subject. + + + + In Sim, add a **Snowflake** connection, choose **Service user (keyless, via Sim OIDC)**, and enter the account host (`myorg-myaccount.snowflakecomputing.com`). The dialog shows the issuer, audience, and subject for this connection, and the statement to run. + + + A user whose role can create users (and has `OWNERSHIP` or `MODIFY PROGRAMMATIC AUTHENTICATION METHODS` on the user) runs the statement from the dialog. It looks like this: + +```sql +CREATE USER SIM_WORKFLOWS + WORKLOAD_IDENTITY = ( + TYPE = OIDC + ISSUER = '' + SUBJECT = '' + ) + TYPE = SERVICE; +``` + + The audience is `snowflakecomputing.com`, Snowflake's default, so the statement needs no `OIDC_AUDIENCE_LIST`. + + + Grant the user a role with the access your workflows need and make it the default, for example `GRANT ROLE SIM_WORKFLOW_ROLE TO USER SIM_WORKFLOWS;` and `ALTER USER SIM_WORKFLOWS SET DEFAULT_ROLE = SIM_WORKFLOW_ROLE;`. If a network policy or authentication policy applies to the user, it must allow Sim's egress and workload identity. + + + Save. Sim signs a token, sends it to your account's SQL API, and runs the same identity statement as for a token. Nothing is saved unless Snowflake accepts it. + + + +Snowflake requires each issuer and subject pair to be unique in an account, and matches the subject exactly, so the service user trusts this connection and no other Sim credential. Reconnecting a keyless connection keeps its subject by default, so the service user keeps working; if you choose **Issue a new subject**, update the user with the new one before saving. + +### Self-hosted deployments + +Keyless connections need `WORKLOAD_IDENTITY_SIGNING_KEY` set and an `https` issuer Snowflake can reach over the public internet. See [AWS credentials](/integrations/aws-credentials#self-hosted-deployments) for the settings. Snowflake caches an issuer's signing keys for up to **60 minutes**, so when rotating the signing key, publish the new key (`WORKLOAD_IDENTITY_PREVIOUS_KEY`) at least 60 minutes before Sim starts signing with it. A shorter wait fails runs until Snowflake refreshes its cache. + +## Use a programmatic access token [#programmatic-access-token] -## Prerequisites +### Prerequisites - A Snowflake user you can generate a token for. For another user or a service user, your role needs `OWNERSHIP` or `MODIFY PROGRAMMATIC AUTHENTICATION METHODS` on that user. - Your account host — the `.snowflakecomputing.com` hostname, for example `myorg-myaccount.snowflakecomputing.com`. Snowsight shows it under **Account details**. @@ -26,9 +70,9 @@ Snowflake's **network policy** requirement varies by user type, and getting it w If your account has no network policy, either create one (allowing Sim's egress) or set `NETWORK_POLICY_EVALUATION = ENFORCED_NOT_REQUIRED` on an authentication policy applied to the user. -## Create the token [#creating-the-token] +### Create the token [#creating-the-token] -### Option 1 — Snowsight +#### Option 1 — Snowsight @@ -45,7 +89,7 @@ If your account has no network policy, either create one (allowing Sim's egress) -### Option 2 — SQL +#### Option 2 — SQL ```sql ALTER USER my_service_user ADD PROGRAMMATIC ACCESS TOKEN sim_workflows @@ -59,11 +103,11 @@ Service users (`TYPE = SERVICE`, `LEGACY_SERVICE`, or `SERVICE_AGENT`) **must** If an authentication policy applies to the user, `'PROGRAMMATIC_ACCESS_TOKEN'` must appear in its `AUTHENTICATION_METHODS` list, otherwise the token is refused. -## Add the credential to Sim [#adding-the-credential-to-sim] +### Add the credential to Sim [#adding-the-credential-to-sim] - Add a **Snowflake** block to a workflow, open the credential dropdown, and choose to add a programmatic access token + Add a **Snowflake** block to a workflow, open the credential dropdown, add a connection, and choose **Programmatic access token** Enter the **account host** (`myorg-myaccount.snowflakecomputing.com`) and paste the **token** @@ -73,7 +117,7 @@ If an authentication policy applies to the user, `'PROGRAMMATIC_ACCESS_TOKEN'` m -The host and the token are encrypted before being stored, and the token is never returned to the browser — the block sends a credential id and Sim resolves it server-side. +The host and the token are encrypted before being stored, and the token is never returned to the browser — the block sends a credential id and Sim resolves it server-side. Keyless tokens are signed on Sim's servers at run time and never stored. ## Use the credential in workflows [#using-the-credential-in-workflows] @@ -91,7 +135,7 @@ With a credential selected, these fields become pickers backed by metadata-only | Named file format | `SHOW FILE FORMATS IN SCHEMA` | database, schema | | Procedure | `SHOW PROCEDURES IN SCHEMA` | database, schema | -Pickers use the token's effective role: its restricted role when set, otherwise the user's default role. They do not apply the execution role selected on the block. An empty list can indicate a privilege gap. Switch any field to advanced mode to type a name directly or reference an upstream block's output instead. +Pickers use the connection's effective role: its restricted role when set, otherwise the user's default role. They do not apply the execution role selected on the block. An empty list can indicate a privilege gap. Switch any field to advanced mode to type a name directly or reference an upstream block's output instead. **Unload Data requires a table or view.** To export a query result, create a view or use `CREATE TABLE AS SELECT` through Execute SQL, then unload that object. @@ -103,6 +147,10 @@ A token's expiry is fixed at creation. To rotate, generate a new token on the sa | Problem | What to check | | --- | --- | +| Keyless: "Snowflake did not accept Sim's token" | No user in this account was created with exactly the issuer and subject from the dialog, the user is not `TYPE = SERVICE`, or a network or authentication policy blocks it. Run `SHOW USER WORKLOAD IDENTITY AUTHENTICATION METHODS FOR USER SIM_WORKFLOWS` to compare. | +| Keyless: error 099706 when creating the user | Another user in the account already has this issuer and subject. Find it with `SHOW USER WORKLOAD IDENTITY AUTHENTICATION METHODS` and remove it, or reconnect with a new subject. | +| Keyless: runs fail for up to an hour after a signing-key rotation | Snowflake had not yet seen the new key. Publish a new key at least 60 minutes before signing with it (see [Self-hosted deployments](#self-hosted-deployments)). | +| Keyless option missing | The deployment has no workload-identity signing key, or the connection belongs to an organization rather than a workspace. Use a programmatic access token. | | Lost token secret | Snowflake shows it only at creation. Generate a replacement and reconnect the credential in Sim. | | Authentication fails | Check expiry or revocation, the user's network policy and Sim's egress, permitted authentication methods, role restriction, and SQL API access. | | Wrong host | Use the account's Snowflake hostname. Sim reports a host error separately when the verification endpoint returns `404`. | diff --git a/apps/docs/content/docs/integrations/snowflake.mdx b/apps/docs/content/docs/integrations/snowflake.mdx index 0883b45f500..dd3a2e53afe 100644 --- a/apps/docs/content/docs/integrations/snowflake.mdx +++ b/apps/docs/content/docs/integrations/snowflake.mdx @@ -23,7 +23,7 @@ Use the block to execute SQL, synchronize rows, move staged data, manage warehou - Snowflake now recommends Cortex Agents for new builds; Cortex Analyst remains available. {/* MANUAL-CONTENT-END */} -Connection guides: [Programmatic access tokens](/integrations/snowflake-service-account). +Connection guides: [Snowflake connections](/integrations/snowflake-service-account). ## Use the block [#usage-instructions] @@ -41,7 +41,7 @@ Execute one parameterized SQL statement through the Snowflake SQL API. | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token\) | +| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token or keyless sign-in\) | | `role` | string | No | Snowflake role to use for this statement | | `statementTimeoutSeconds` | number | No | Statement timeout in seconds; 0 uses Snowflake maximum of 604800 seconds | | `warehouse` | string | No | Warehouse to use for this statement; defaults to the PAT user setting | @@ -92,7 +92,7 @@ Check a running or completed statement and retrieve exactly one result partition | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token\) | +| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token or keyless sign-in\) | | `statementHandle` | string | Yes | Statement handle returned by Snowflake | | `partition` | number | No | Zero-based result partition to retrieve; defaults to 0 | | `partitionCount` | number | No | Total number of result partitions, taken from the partitionCount of the first partition. Snowflake omits metadata from every later partition response, so supply this when fetching partition 1 or higher to keep truncated and nextPartition accurate | @@ -137,7 +137,7 @@ Cancel a running Snowflake SQL API statement. | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token\) | +| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token or keyless sign-in\) | | `statementHandle` | string | Yes | Statement handle returned by Snowflake | #### Output @@ -180,7 +180,7 @@ Insert structured JSON rows using bound values. | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token\) | +| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token or keyless sign-in\) | | `role` | string | No | Snowflake role to use for this statement | | `statementTimeoutSeconds` | number | No | Statement timeout in seconds; 0 uses Snowflake maximum of 604800 seconds | | `warehouse` | string | No | Warehouse to use for this statement; defaults to the PAT user setting | @@ -229,7 +229,7 @@ Update matching rows with a bound MERGE statement without inserting new rows. | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token\) | +| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token or keyless sign-in\) | | `role` | string | No | Snowflake role to use for this statement | | `statementTimeoutSeconds` | number | No | Statement timeout in seconds; 0 uses Snowflake maximum of 604800 seconds | | `warehouse` | string | No | Warehouse to use for this statement; defaults to the PAT user setting | @@ -279,7 +279,7 @@ Update matching rows and insert unmatched rows with a bound MERGE statement. | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token\) | +| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token or keyless sign-in\) | | `role` | string | No | Snowflake role to use for this statement | | `statementTimeoutSeconds` | number | No | Statement timeout in seconds; 0 uses Snowflake maximum of 604800 seconds | | `warehouse` | string | No | Warehouse to use for this statement; defaults to the PAT user setting | @@ -329,7 +329,7 @@ Delete rows matching a required set of bound column filters. | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token\) | +| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token or keyless sign-in\) | | `role` | string | No | Snowflake role to use for this statement | | `statementTimeoutSeconds` | number | No | Statement timeout in seconds; 0 uses Snowflake maximum of 604800 seconds | | `warehouse` | string | No | Warehouse to use for this statement; defaults to the PAT user setting | @@ -378,7 +378,7 @@ Load files from an existing Snowflake stage with COPY INTO. | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token\) | +| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token or keyless sign-in\) | | `role` | string | No | Snowflake role to use for this statement | | `statementTimeoutSeconds` | number | No | Statement timeout in seconds; 0 uses Snowflake maximum of 604800 seconds | | `warehouse` | string | No | Warehouse to use for this statement; defaults to the PAT user setting | @@ -434,7 +434,7 @@ Export a Snowflake table to files in a stage with COPY INTO. | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token\) | +| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token or keyless sign-in\) | | `role` | string | No | Snowflake role to use for this statement | | `statementTimeoutSeconds` | number | No | Statement timeout in seconds; 0 uses Snowflake maximum of 604800 seconds | | `warehouse` | string | No | Warehouse to use for this statement; defaults to the PAT user setting | @@ -489,7 +489,7 @@ List the databases the credential can access. | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token\) | +| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token or keyless sign-in\) | | `role` | string | No | Snowflake role to use for this statement | | `statementTimeoutSeconds` | number | No | Statement timeout in seconds; 0 uses Snowflake maximum of 604800 seconds | | `nameLike` | string | No | Optional SQL LIKE pattern for object names | @@ -535,7 +535,7 @@ List the schemas in a Snowflake database. | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token\) | +| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token or keyless sign-in\) | | `role` | string | No | Snowflake role to use for this statement | | `statementTimeoutSeconds` | number | No | Statement timeout in seconds; 0 uses Snowflake maximum of 604800 seconds | | `database` | string | Yes | Database name | @@ -582,7 +582,7 @@ List the tables in a Snowflake schema. | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token\) | +| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token or keyless sign-in\) | | `role` | string | No | Snowflake role to use for this statement | | `statementTimeoutSeconds` | number | No | Statement timeout in seconds; 0 uses Snowflake maximum of 604800 seconds | | `database` | string | Yes | Database name | @@ -630,7 +630,7 @@ List warehouses visible to the active Snowflake role. | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token\) | +| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token or keyless sign-in\) | | `role` | string | No | Snowflake role to use for this statement | | `statementTimeoutSeconds` | number | No | Statement timeout in seconds; 0 uses Snowflake maximum of 604800 seconds | | `maxRows` | number | No | Maximum result rows; defaults to 1000 with a Sim safety limit of 10000 | @@ -676,7 +676,7 @@ Get the full details for a Snowflake virtual warehouse. | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token\) | +| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token or keyless sign-in\) | | `role` | string | No | Snowflake role to use for this statement | | `statementTimeoutSeconds` | number | No | Statement timeout in seconds; 0 uses Snowflake maximum of 604800 seconds | | `warehouseName` | string | Yes | Warehouse name | @@ -721,7 +721,7 @@ Resume a Snowflake virtual warehouse if it is suspended. | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token\) | +| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token or keyless sign-in\) | | `role` | string | No | Snowflake role to use for this statement | | `statementTimeoutSeconds` | number | No | Statement timeout in seconds; 0 uses Snowflake maximum of 604800 seconds | | `warehouseName` | string | Yes | Warehouse name | @@ -766,7 +766,7 @@ Suspend a Snowflake virtual warehouse. | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token\) | +| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token or keyless sign-in\) | | `role` | string | No | Snowflake role to use for this statement | | `statementTimeoutSeconds` | number | No | Statement timeout in seconds; 0 uses Snowflake maximum of 604800 seconds | | `warehouseName` | string | Yes | Warehouse name | @@ -811,7 +811,7 @@ Resize a Snowflake warehouse or change its auto-suspend and auto-resume settings | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token\) | +| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token or keyless sign-in\) | | `role` | string | No | Snowflake role to use for this statement | | `statementTimeoutSeconds` | number | No | Statement timeout in seconds; 0 uses Snowflake maximum of 604800 seconds | | `warehouseName` | string | Yes | Warehouse name | @@ -859,7 +859,7 @@ List tasks in a Snowflake schema. | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token\) | +| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token or keyless sign-in\) | | `role` | string | No | Snowflake role to use for this statement | | `statementTimeoutSeconds` | number | No | Statement timeout in seconds; 0 uses Snowflake maximum of 604800 seconds | | `database` | string | Yes | Database name | @@ -907,7 +907,7 @@ Describe a Snowflake task. | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token\) | +| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token or keyless sign-in\) | | `role` | string | No | Snowflake role to use for this statement | | `statementTimeoutSeconds` | number | No | Statement timeout in seconds; 0 uses Snowflake maximum of 604800 seconds | | `database` | string | Yes | Database name | @@ -954,7 +954,7 @@ Run a Snowflake task immediately, optionally retrying its last failed graph. | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token\) | +| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token or keyless sign-in\) | | `role` | string | No | Snowflake role to use for this statement | | `statementTimeoutSeconds` | number | No | Statement timeout in seconds; 0 uses Snowflake maximum of 604800 seconds | | `database` | string | Yes | Database name | @@ -1002,7 +1002,7 @@ Resume a suspended Snowflake task so its schedule runs again. | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token\) | +| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token or keyless sign-in\) | | `role` | string | No | Snowflake role to use for this statement | | `statementTimeoutSeconds` | number | No | Statement timeout in seconds; 0 uses Snowflake maximum of 604800 seconds | | `database` | string | Yes | Database name | @@ -1049,7 +1049,7 @@ Suspend a Snowflake task so its schedule stops triggering runs. | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token\) | +| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token or keyless sign-in\) | | `role` | string | No | Snowflake role to use for this statement | | `statementTimeoutSeconds` | number | No | Statement timeout in seconds; 0 uses Snowflake maximum of 604800 seconds | | `database` | string | Yes | Database name | @@ -1096,7 +1096,7 @@ Query up to seven days of Snowflake task history, capped at 10000 rows. | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token\) | +| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token or keyless sign-in\) | | `role` | string | No | Snowflake role to use for this statement | | `statementTimeoutSeconds` | number | No | Statement timeout in seconds; 0 uses Snowflake maximum of 604800 seconds | | `warehouse` | string | No | Warehouse to use for this statement; defaults to the PAT user setting | @@ -1146,7 +1146,7 @@ Find one task history record by query ID within Snowflake’s seven-day window a | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token\) | +| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token or keyless sign-in\) | | `role` | string | No | Snowflake role to use for this statement | | `statementTimeoutSeconds` | number | No | Statement timeout in seconds; 0 uses Snowflake maximum of 604800 seconds | | `warehouse` | string | No | Warehouse to use for this statement; defaults to the PAT user setting | @@ -1195,7 +1195,7 @@ Cancel one running task query by query ID with SYSTEM$CANCEL_QUERY. Task runs al | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token\) | +| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token or keyless sign-in\) | | `role` | string | No | Snowflake role to use for this statement | | `statementTimeoutSeconds` | number | No | Statement timeout in seconds; 0 uses Snowflake maximum of 604800 seconds | | `warehouse` | string | No | Warehouse to use for this statement; defaults to the PAT user setting | @@ -1241,7 +1241,7 @@ Read a task query result with RESULT_SCAN during Snowflake’s 24-hour retention | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token\) | +| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token or keyless sign-in\) | | `role` | string | No | Snowflake role to use for this statement | | `statementTimeoutSeconds` | number | No | Statement timeout in seconds; 0 uses Snowflake maximum of 604800 seconds | | `warehouse` | string | No | Warehouse to use for this statement; defaults to the PAT user setting | @@ -1288,7 +1288,7 @@ List queries that completed in the last seven days, optionally filtered. | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token\) | +| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token or keyless sign-in\) | | `role` | string | No | Snowflake role to use for this statement | | `statementTimeoutSeconds` | number | No | Statement timeout in seconds; 0 uses Snowflake maximum of 604800 seconds | | `warehouse` | string | No | Warehouse to use for this statement; defaults to the PAT user setting | @@ -1339,7 +1339,7 @@ List staged-file load results for a table over the last fourteen days. | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token\) | +| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token or keyless sign-in\) | | `role` | string | No | Snowflake role to use for this statement | | `statementTimeoutSeconds` | number | No | Statement timeout in seconds; 0 uses Snowflake maximum of 604800 seconds | | `warehouse` | string | No | Warehouse to use for this statement; defaults to the PAT user setting | @@ -1390,7 +1390,7 @@ Inspect table and column metadata through Snowflake INFORMATION_SCHEMA views. | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token\) | +| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token or keyless sign-in\) | | `role` | string | No | Snowflake role to use for this statement | | `statementTimeoutSeconds` | number | No | Statement timeout in seconds; 0 uses Snowflake maximum of 604800 seconds | | `warehouse` | string | No | Warehouse to use for this statement; defaults to the PAT user setting | @@ -1440,7 +1440,7 @@ Call a stored procedure with explicitly typed Snowflake bindings. | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token\) | +| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token or keyless sign-in\) | | `role` | string | No | Snowflake role to use for this statement | | `statementTimeoutSeconds` | number | No | Statement timeout in seconds; 0 uses Snowflake maximum of 604800 seconds | | `warehouse` | string | No | Warehouse to use for this statement; defaults to the PAT user setting | @@ -1490,7 +1490,7 @@ Ask Snowflake Cortex Analyst a question in natural language against a semantic v | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token\) | +| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token or keyless sign-in\) | | `question` | string | Yes | The question to ask about your data | | `semanticView` | string | No | Fully qualified semantic view name \(for example MY_DB.MY_SCHEMA.MY_VIEW\). Provide exactly one semantic source. | | `semanticModelFile` | string | No | Stage path to a semantic model YAML file \(for example @MY_DB.MY_SCHEMA.MY_STAGE/model.yaml\). Provide exactly one semantic source. | @@ -1566,7 +1566,7 @@ Rate a Cortex Analyst answer thumbs up or down, with an optional comment. Feedba | Parameter | Type | Required | Description | | --------- | ---- | -------- | ----------- | -| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token\) | +| `oauthCredential` | string | Yes | Snowflake credential \(account host and programmatic access token or keyless sign-in\) | | `requestId` | string | Yes | Request ID returned by Cortex Analyst Ask | | `positive` | boolean | Yes | true for positive \(thumbs up\) feedback, false for negative \(thumbs down\) | | `feedbackMessage` | string | No | Optional feedback comment | diff --git a/apps/docs/content/integration-navigation.json b/apps/docs/content/integration-navigation.json index 50bb58cefd0..17a8067e6a1 100644 --- a/apps/docs/content/integration-navigation.json +++ b/apps/docs/content/integration-navigation.json @@ -18,6 +18,10 @@ "aws-credentials": { "title": "AWS credentials" }, + "bitbucket-service-account": { + "integration": "bitbucket", + "title": "Access tokens" + }, "box-service-account": { "integration": "box", "title": "Service accounts" @@ -34,6 +38,10 @@ "integration": "databricks", "title": "Databricks connections" }, + "docusign-service-account": { + "integration": "docusign", + "title": "JWT Grant" + }, "google-service-account": { "title": "Google service accounts" }, @@ -49,6 +57,9 @@ "integration": "linear", "title": "API keys" }, + "microsoft-app-credentials": { + "title": "Microsoft app credentials" + }, "monday-service-account": { "integration": "monday", "title": "API tokens" @@ -75,7 +86,7 @@ }, "snowflake-service-account": { "integration": "snowflake", - "title": "Programmatic access tokens" + "title": "Snowflake connections" }, "trello-service-account": { "integration": "trello", diff --git a/apps/docs/scripts/fixtures/content-baseline.json b/apps/docs/scripts/fixtures/content-baseline.json index 88a1d78e393..189985604ba 100644 --- a/apps/docs/scripts/fixtures/content-baseline.json +++ b/apps/docs/scripts/fixtures/content-baseline.json @@ -67021,7 +67021,15 @@ "line": 122 } ], - "codeFences": [], + "codeFences": [ + { + "lang": "bash", + "meta": null, + "sha256": "b867716c5b178cc345e9ec091ffd5db588c778b02f244e3e51513c9266fbaf8a", + "bytes": 733, + "line": 199 + } + ], "links": [ "https://console.cloud.google.com/", "#scopes-reference", @@ -141488,12 +141496,19 @@ ], "expressions": [], "codeFences": [ + { + "lang": "sql", + "meta": null, + "sha256": "96716701cef0ce8a3205217105b932f669acc115ec2faed939bf81704eb83ed2", + "bytes": 169, + "line": 29 + }, { "lang": "sql", "meta": null, "sha256": "0fbd73d76ccb6a73e3f2f817a592bff15a0d1ffb45b4425fbfc91cc7ac0a48da", "bytes": 134, - "line": 46 + "line": 94 } ], "links": [ diff --git a/apps/sim/app/workspace/[workspaceId]/home/components/message-content/components/special-tags/special-tags.tsx b/apps/sim/app/workspace/[workspaceId]/home/components/message-content/components/special-tags/special-tags.tsx index a082d663828..b5d209fccd7 100644 --- a/apps/sim/app/workspace/[workspaceId]/home/components/message-content/components/special-tags/special-tags.tsx +++ b/apps/sim/app/workspace/[workspaceId]/home/components/message-content/components/special-tags/special-tags.tsx @@ -2540,6 +2540,7 @@ function ServiceAccountConnectDisplay({ atlassianProduct={match?.providerId === 'confluence' ? 'confluence' : 'jira'} serviceName={target.serviceName} serviceIcon={target.serviceIcon} + oauthServiceId={service?.providerId} credentialId={reconnectCredentialId} credentialDisplayName={reconnectCredential?.displayName ?? undefined} onCreated={() => { diff --git a/apps/sim/app/workspace/[workspaceId]/home/components/suggested-actions/connect-candidates.test.ts b/apps/sim/app/workspace/[workspaceId]/home/components/suggested-actions/connect-candidates.test.ts new file mode 100644 index 00000000000..93b4fa67358 --- /dev/null +++ b/apps/sim/app/workspace/[workspaceId]/home/components/suggested-actions/connect-candidates.test.ts @@ -0,0 +1,32 @@ +import { INTEGRATION_METADATA } from '@sim/deployment-config/integration-metadata' +import { describe, expect, it } from 'vitest' +import { OAUTH_PROVIDERS } from '@/lib/oauth/oauth' +import { unconnectedIntegrations } from '@/app/workspace/[workspaceId]/home/components/suggested-actions/connect-candidates' + +const SERVICES = Object.values(OAUTH_PROVIDERS).flatMap((provider) => + Object.entries(provider.services).map(([id, service]) => ({ ...service, id })) +) + +function githubCandidates(connected: string[]) { + return unconnectedIntegrations(SERVICES, new Set(connected), INTEGRATION_METADATA).filter( + ({ slug }) => slug === 'github' + ) +} + +describe('suggested connect rows', () => { + it('offers GitHub once, through the service its catalog entry names', () => { + expect(githubCandidates([]).map(({ service }) => service.id)).toEqual(['github-token']) + }) + + it.each([ + ['a saved personal access token', 'github-service-account'], + ['a Search OAuth account', 'github-repositories'], + ['a GitHub App installation', 'github-app-installation'], + ])('treats GitHub as connected by %s', (_, providerId) => { + expect(githubCandidates([providerId])).toEqual([]) + }) + + it("still offers GitHub when only another integration's credential is saved", () => { + expect(githubCandidates(['slack', 'gitlab-service-account'])).toHaveLength(1) + }) +}) diff --git a/apps/sim/app/workspace/[workspaceId]/home/components/suggested-actions/connect-candidates.ts b/apps/sim/app/workspace/[workspaceId]/home/components/suggested-actions/connect-candidates.ts new file mode 100644 index 00000000000..22d68f500ac --- /dev/null +++ b/apps/sim/app/workspace/[workspaceId]/home/components/suggested-actions/connect-candidates.ts @@ -0,0 +1,50 @@ +import { credentialProviderMatchesService, type ServiceProviderIdentity } from '@/lib/oauth/utils' + +interface ConnectableService extends ServiceProviderIdentity { + /** Service key in `OAUTH_PROVIDERS`. */ + id: string + name: string +} + +interface CatalogIntegration { + name: string + slug: string + oauthServiceId?: string +} + +/** + * One connect candidate per catalog integration that no saved credential powers + * yet. Several services can share an integration (GitHub has its Search App and + * its saved tokens), so an integration counts as connected when a credential + * matches any of them — by OAuth id or service-account id — and is offered once, + * through the service its catalog entry names. + */ +export function unconnectedIntegrations( + services: readonly S[], + connectedProviderIds: ReadonlySet, + catalog: readonly CatalogIntegration[] +): { service: S; slug: string }[] { + const integrationByName = new Map(catalog.map((entry) => [entry.name.toLowerCase(), entry])) + const servicesBySlug = new Map() + for (const service of services) { + const integration = integrationByName.get(service.name.toLowerCase()) + if (!integration) continue + const group = servicesBySlug.get(integration.slug) + if (group) group.push(service) + else servicesBySlug.set(integration.slug, [service]) + } + + const candidates: { service: S; slug: string }[] = [] + for (const [slug, group] of servicesBySlug) { + const connected = group.some((service) => + [...connectedProviderIds].some((providerId) => + credentialProviderMatchesService(providerId, service) + ) + ) + if (connected) continue + const oauthServiceId = catalog.find((entry) => entry.slug === slug)?.oauthServiceId + const service = group.find((candidate) => candidate.id === oauthServiceId) ?? group[0] + candidates.push({ service, slug }) + } + return candidates +} diff --git a/apps/sim/app/workspace/[workspaceId]/home/components/suggested-actions/suggested-actions.tsx b/apps/sim/app/workspace/[workspaceId]/home/components/suggested-actions/suggested-actions.tsx index 980eccdcc43..6b1eace7ee0 100644 --- a/apps/sim/app/workspace/[workspaceId]/home/components/suggested-actions/suggested-actions.tsx +++ b/apps/sim/app/workspace/[workspaceId]/home/components/suggested-actions/suggested-actions.tsx @@ -15,6 +15,7 @@ import { } from '@/lib/integrations/oauth-service' import { captureEvent } from '@/lib/posthog/client' import { ConnectOAuthModal } from '@/app/workspace/[workspaceId]/components/connect-oauth-modal' +import { unconnectedIntegrations } from '@/app/workspace/[workspaceId]/home/components/suggested-actions/connect-candidates' import type { Action, ActionIcon, @@ -29,11 +30,6 @@ import { useKnowledgeBasesQuery } from '@/hooks/queries/kb/knowledge' import { useOAuthConnections } from '@/hooks/queries/oauth/connections' import { useTablesList } from '@/hooks/queries/tables' -/** Lookup integration slug by OAuth service display name (case-insensitive). */ -const SLUG_BY_LOWER_NAME: ReadonlyMap = new Map( - INTEGRATION_METADATA.map((i) => [i.name.toLowerCase(), i.slug]) -) - /** Lookup base block type by catalog slug, for the connect-row popularity weight. */ const TYPE_BY_SLUG: ReadonlyMap = new Map( INTEGRATION_METADATA.map((i) => [i.slug, stripVersionSuffix(i.type)]) @@ -177,11 +173,11 @@ function toIntegrationAction(service: ServiceInfo, slug: string): Action { * prompts; fresh workspaces get two of each. */ function computeActions(services: readonly ServiceInfo[], signals: Signals): Action[] { - const connectCandidates = services.flatMap((s) => { - if (signals.connectedProviders.has(s.providerId)) return [] - const slug = SLUG_BY_LOWER_NAME.get(s.name.toLowerCase()) - return slug ? [{ service: s, slug }] : [] - }) + const connectCandidates = unconnectedIntegrations( + services, + signals.connectedProviders, + INTEGRATION_METADATA + ) const connectCount = signals.connectedProviders.size === 0 ? 2 : 1 const integrations = weightedSample( connectCandidates, diff --git a/apps/sim/app/workspace/[workspaceId]/integrations/[block]/integration-block-detail.tsx b/apps/sim/app/workspace/[workspaceId]/integrations/[block]/integration-block-detail.tsx index 13e3bd8a199..6056fc92067 100644 --- a/apps/sim/app/workspace/[workspaceId]/integrations/[block]/integration-block-detail.tsx +++ b/apps/sim/app/workspace/[workspaceId]/integrations/[block]/integration-block-detail.tsx @@ -355,6 +355,7 @@ function IntegrationBlockDetailContent({ integration, workspaceId }: Integration atlassianProduct={oauthService?.providerId === 'confluence' ? 'confluence' : 'jira'} serviceName={serviceAccountTarget.serviceName} serviceIcon={serviceAccountTarget.serviceIcon} + oauthServiceId={oauthService?.providerId} /> )}
> + +/** Submit-error copy, with an optional provider link the user must open to recover. */ +interface ClientCredentialErrorCopy { + message: string + link?: { href: string; label: string } +} + const FALLBACK_ERROR_MESSAGE = "We couldn't save this credential. Try again in a moment." /** @@ -46,37 +55,69 @@ function messageForClientCredentialError( err: unknown, descriptor: ClientCredentialAccountDescriptor, requiredFields: ClientCredentialAccountField[], + values: FieldValues, fallbackMessage = FALLBACK_ERROR_MESSAGE -): string { +): ClientCredentialErrorCopy { if (isApiClientError(err) && err.code) { // Names the fields the *selected* auth method needed, so a JWT failure // doesn't tell the user to check a consumer secret they never entered. const fieldLabels = requiredFields.map((field) => field.label).join(', ') switch (err.code) { case 'invalid_credentials': - return `We couldn't authenticate with those credentials. Check that the ${fieldLabels} all belong to the same ${descriptor.serviceLabel} app and that the app is authorized.` + return { + message: `We couldn't authenticate with those credentials. Check that the ${fieldLabels} all belong to the same ${descriptor.serviceLabel} app and that the app is authorized.`, + } case 'permission_conflict': - return 'Use the same permissions for connections to this application, or create a separate application for different permissions.' + return { + message: + 'Use the same permissions for connections to this application, or create a separate application for different permissions.', + } case 'site_not_found': { // "host field" named a label no provider renders — Salesforce calls it // My Domain host, and Zoom/Box/Zoho Desk have no host field at all. const hostFieldLabel = descriptor.fields.find((field) => field.id === 'orgId')?.label ?? 'host' - return `We couldn't find a ${descriptor.serviceLabel} account at that host. Check the ${hostFieldLabel} field and try again.` + return { + message: `We couldn't find a ${descriptor.serviceLabel} account at that host. Check the ${hostFieldLabel} field and try again.`, + } } case 'provider_unavailable': - return `We couldn't reach ${descriptor.serviceLabel} to verify these credentials. Try again in a moment.` + return { + message: `We couldn't reach ${descriptor.serviceLabel} to verify these credentials. Try again in a moment.`, + } + case 'consent_required': { + const redirectUri = window.location.origin + const consentUrl = descriptor.consentUrl?.(values, redirectUri) + return consentUrl + ? { + message: `${descriptor.serviceLabel} needs the impersonated user's consent first. Add ${redirectUri} as a redirect URI on the integration key, then open the consent page signed in as that user, accept, and try again.`, + link: { href: consentUrl, label: 'Open consent page' }, + } + : { + message: `${descriptor.serviceLabel} needs the impersonated user's consent first. See the setup guide.`, + } + } + case 'account_not_found': { + if (!values.orgId?.trim()) { + return { + message: `That user has no ${descriptor.serviceLabel} account in this environment. Check the environment and user ID.`, + } + } + const accountFieldLabel = + descriptor.fields.find((field) => field.id === 'orgId')?.label ?? 'account' + return { + message: `That user isn't a member of the ${accountFieldLabel} you entered. Check it, or leave it blank to use the user's default account.`, + } + } case 'duplicate_display_name': - return 'A credential with that name already exists in this workspace.' + return { message: 'A credential with that name already exists in this workspace.' } default: - return fallbackMessage + return { message: fallbackMessage } } } - return fallbackMessage + return { message: fallbackMessage } } -type FieldValues = Partial> - function openDocs(url: string): void { window.open(url, '_blank', 'noopener,noreferrer') } @@ -142,7 +183,7 @@ function ClientCredentialAccountModalForm({ const [values, setValues] = useState({}) const [displayName, setDisplayName] = useState(initialDisplayName ?? '') const [description, setDescription] = useState(initialDescription ?? '') - const [error, setError] = useState(null) + const [error, setError] = useState(null) const createCredential = useCreateScopedCredential() const updateCredential = useUpdateScopedCredential() @@ -242,6 +283,7 @@ function ClientCredentialAccountModalForm({ err, descriptor, required, + values, onSubmitCredentials ? getErrorMessage(err, FALLBACK_ERROR_MESSAGE) : undefined ) ) @@ -383,7 +425,26 @@ function ClientCredentialAccountModalForm({ minHeight={80} /> - {error} + + {error && ( + <> + {error.message} + {error.link && ( + + + {error.link.label} + + + + )} + + )} + onOpenChange(false)} diff --git a/apps/sim/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/connect-service-account-modal.tsx b/apps/sim/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/connect-service-account-modal.tsx index d4c8f6af607..a50d47b0815 100644 --- a/apps/sim/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/connect-service-account-modal.tsx +++ b/apps/sim/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/connect-service-account-modal.tsx @@ -4,6 +4,7 @@ import { type ComponentType, useState } from 'react' import { ChipModal, ChipModalBody, + ChipModalDescription, ChipModalError, ChipModalField, ChipModalFooter, @@ -25,9 +26,14 @@ import { type ClientCredentialAccountProviderId, getClientCredentialAccountDescriptor, } from '@/lib/credentials/client-credential-accounts/descriptors' +import { + GOOGLE_KEYLESS_SERVICES, + googleKeylessOffer, +} from '@/lib/credentials/google-workload-identity' import type { ServiceAccountSecretFields } from '@/lib/credentials/service-account-secret' import { getTokenServiceAccountDescriptor, + SNOWFLAKE_SERVICE_ACCOUNT_PROVIDER_ID, type TokenServiceAccountProviderId, } from '@/lib/credentials/token-service-accounts/descriptors' import { getServiceAccountCoverageSentence } from '@/lib/integrations/credential-display' @@ -36,6 +42,7 @@ import { AWS_SERVICE_ACCOUNT_PROVIDER_ID, DATABRICKS_SERVICE_ACCOUNT_PROVIDER_ID, GOOGLE_SERVICE_ACCOUNT_PROVIDER_ID, + MICROSOFT_APP_SERVICE_ACCOUNT_PROVIDER_ID, OCI_API_KEY_SERVICE_ACCOUNT_PROVIDER_ID, ORACLE_DATABASE_SERVICE_ACCOUNT_PROVIDER_ID, SLACK_CUSTOM_BOT_PROVIDER_ID, @@ -43,7 +50,20 @@ import { import { AwsAccountModal } from '@/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/aws-account-modal' import { ClientCredentialAccountModal } from '@/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/client-credential-account-modal' import { DatabricksAccountModal } from '@/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/databricks-account-modal' +import { + buildGoogleKeylessConfig, + EMPTY_GOOGLE_KEYLESS_INPUT, + GoogleKeylessFields, + type GoogleKeylessInput, + isGoogleKeylessInputComplete, +} from '@/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/google-keyless-fields' +import { + useKeylessSetup, + useSavedConnectionSubmit, +} from '@/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/keyless-connection' +import { MicrosoftAppAccountModal } from '@/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/microsoft-app-account-modal' import { OracleDatabaseAccountModal } from '@/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/oracle-database-account-modal' +import { SnowflakeAccountModal } from '@/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/snowflake-account-modal' import { TokenServiceAccountModal } from '@/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/token-service-account-modal' import { ConnectSlackBotModal } from '@/app/workspace/[workspaceId]/integrations/components/connect-slack-bot-modal/connect-slack-bot-modal' import { withBrandIcon } from '@/blocks/brand-icon' @@ -62,6 +82,7 @@ export type ServiceAccountProviderId = | typeof ORACLE_DATABASE_SERVICE_ACCOUNT_PROVIDER_ID | typeof AWS_SERVICE_ACCOUNT_PROVIDER_ID | typeof DATABRICKS_SERVICE_ACCOUNT_PROVIDER_ID + | typeof MICROSOFT_APP_SERVICE_ACCOUNT_PROVIDER_ID | TokenServiceAccountProviderId | ClientCredentialAccountProviderId @@ -144,6 +165,11 @@ interface ConnectServiceAccountModalProps { credentialDisplayName?: string /** Existing description, used to seed reconnect-capable modals. */ credentialDescription?: string + /** + * The OAuth service the dialog was opened for (`google-bigquery`). A Google service account + * offers keyless setup only for a Google Cloud service. + */ + oauthServiceId?: string /** Called with the new credential id after a successful create (token-paste providers). */ onCreated?: (credentialId: string) => void onSubmitCredentials?: ( @@ -179,6 +205,7 @@ export function ConnectServiceAccountModal({ credentialId, credentialDisplayName, credentialDescription, + oauthServiceId, onCreated, onSubmitCredentials, submitPending, @@ -198,6 +225,21 @@ export function ConnectServiceAccountModal({ /> ) } + if (serviceAccountProviderId === MICROSOFT_APP_SERVICE_ACCOUNT_PROVIDER_ID) { + return ( + + ) + } if (serviceAccountProviderId === AWS_SERVICE_ACCOUNT_PROVIDER_ID) { return ( ) } + // A caller that saves the fields itself (a connect draft) takes the token only. + if (serviceAccountProviderId === SNOWFLAKE_SERVICE_ACCOUNT_PROVIDER_ID && !onSubmitCredentials) { + return ( + + ) + } const tokenDescriptor = getTokenServiceAccountDescriptor(serviceAccountProviderId) if (tokenDescriptor) { return ( @@ -328,6 +387,7 @@ export function ConnectServiceAccountModal({ credentialId={credentialId} initialDisplayName={credentialDisplayName} initialDescription={credentialDescription} + oauthServiceId={oauthServiceId} onCreated={onCreated} /> ) @@ -560,12 +620,20 @@ function OciApiKeyServiceAccountModal({ ) } +interface GoogleServiceAccountModalProps extends ProviderModalProps { + oauthServiceId?: string +} + +type GoogleAuthType = 'json_key' | 'workload_identity' + /** * Google service-account flow. Accepts the raw JSON key (paste or drag/drop) * and validates against the shared `serviceAccountJsonSchema` so the same - * shape errors render here as in the server route. + * shape errors render here as in the server route. For a Google Cloud service + * (or a keyless credential being reconnected) on a deployment that can sign + * workload-identity tokens, it also offers keyless Workload Identity Federation. */ -function GoogleServiceAccountModal(props: ProviderModalProps) { +function GoogleServiceAccountModal(props: GoogleServiceAccountModalProps) { if (!props.open) return null return ( onOpenChange(false), + }) + const keylessOffer = googleKeylessOffer({ + oauthServiceId, + available: Boolean(keyless.available), + reconnectsKeyless: keyless.reconnectsKeyless, + }) + const offerKeyless = keylessOffer === 'offer' + const [selectedAuthType, setSelectedAuthType] = useState(null) + const authType: GoogleAuthType = offerKeyless + ? (selectedAuthType ?? (keyless.reconnectsKeyless ? 'workload_identity' : 'json_key')) + : 'json_key' + const [keylessInput, setKeylessInput] = useState(EMPTY_GOOGLE_KEYLESS_INPUT) const [jsonInput, setJsonInput] = useState('') const [uploadedFileName, setUploadedFileName] = useState(null) const [displayName, setDisplayName] = useState(initialDisplayName ?? '') @@ -675,8 +771,15 @@ function GoogleServiceAccountModalForm({ } } - const isPending = createCredential.isPending || updateCredential.isPending - const isDisabled = !jsonInput.trim() || isPending + const isPending = + createCredential.isPending || updateCredential.isPending || keylessSubmit.isPending + const cloudOnly = keylessOffer === 'cloud_only' + const isDisabled = + cloudOnly || + (authType === 'workload_identity' + ? isPending || !keyless.ready || !isGoogleKeylessInputComplete(keylessInput) + : !jsonInput.trim() || isPending) + const submitError = authType === 'workload_identity' ? keylessSubmit.error : error return ( - { - setJsonInput(value) - if (uploadedFileName) setUploadedFileName(null) - if (error) setError(null) - maybeFillDisplayNameFromJson(value) - }} - placeholder='Paste your service account JSON key here' - minHeight={120} - required - /> + {offerKeyless && ( + { + setSelectedAuthType(value as GoogleAuthType) + setError(null) + keylessSubmit.clearError() + }} + options={[ + { value: 'json_key', label: 'JSON key' }, + { + value: 'workload_identity', + label: 'Workload Identity Federation (keyless, via Sim OIDC)', + }, + ]} + required + hint={ + authType === 'workload_identity' + ? 'No key is stored. Sim signs a short-lived token your workload identity provider trusts, then impersonates the service account. Google Cloud APIs only, without domain-wide delegation.' + : undefined + } + /> + )} - + {authType === 'workload_identity' && ( + { + setKeylessInput(next) + keylessSubmit.clearError() + }} + setup={keyless} + /> + )} + + {cloudOnly && ( + + This keyless credential works only with Google Cloud services (BigQuery, Vertex AI). + Reconnect it from one of those integrations or from the credential’s own page. + + )} + + {authType === 'json_key' && !cloudOnly && ( + <> + { + setJsonInput(value) + if (uploadedFileName) setUploadedFileName(null) + if (error) setError(null) + maybeFillDisplayNameFromJson(value) + }} + placeholder='Paste your service account JSON key here' + minHeight={120} + required + /> + + + + )} @@ -734,7 +889,7 @@ function GoogleServiceAccountModalForm({ minHeight={80} /> - {error} + {submitError} onOpenChange(false)} @@ -745,8 +900,24 @@ function GoogleServiceAccountModalForm({ }, ]} primaryAction={{ - label: isPending ? 'Adding...' : 'Add service account', - onClick: handleSubmit, + label: isPending + ? authType === 'workload_identity' + ? 'Verifying...' + : 'Adding...' + : 'Add service account', + onClick: () => { + if (authType === 'json_key') { + void handleSubmit() + return + } + if (!isDisabled) { + void keylessSubmit.submit({ + config: buildGoogleKeylessConfig(keylessInput, keyless), + displayName, + description, + }) + } + }, disabled: isDisabled, }} /> diff --git a/apps/sim/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/databricks-account-modal.tsx b/apps/sim/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/databricks-account-modal.tsx index 3e36b5b1734..1f0852d9795 100644 --- a/apps/sim/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/databricks-account-modal.tsx +++ b/apps/sim/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/databricks-account-modal.tsx @@ -122,7 +122,7 @@ function DatabricksAccountForm({ } const federationCommand = - authType === 'oidc_federation' && keyless.trust + authType === 'oidc_federation' && keyless.trust?.audience ? buildFederationPolicyCommand( keyless.trust.issuer, keyless.trust.audience, diff --git a/apps/sim/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/google-keyless-fields.tsx b/apps/sim/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/google-keyless-fields.tsx new file mode 100644 index 00000000000..8af19e42f89 --- /dev/null +++ b/apps/sim/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/google-keyless-fields.tsx @@ -0,0 +1,143 @@ +'use client' + +import { ChipModalField, ChipTextarea } from '@sim/emcn' +import { + googleWorkloadIdentityAudience, + googleWorkloadIdentitySetupCommands, + isGoogleProjectNumber, + isGoogleServiceAccountEmail, + isGoogleWorkloadIdentityId, +} from '@/lib/credentials/google-workload-identity' +import { + type KeylessSetup, + KeylessTrustFields, + keylessSubjectFields, +} from '@/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/keyless-connection' + +/** What the person enters for a keyless Google Cloud credential. */ +export interface GoogleKeylessInput { + projectNumber: string + poolId: string + providerId: string + serviceAccountEmail: string +} + +export const EMPTY_GOOGLE_KEYLESS_INPUT: GoogleKeylessInput = { + projectNumber: '', + poolId: '', + providerId: '', + serviceAccountEmail: '', +} + +function normalize(input: GoogleKeylessInput): GoogleKeylessInput { + return { + projectNumber: input.projectNumber.trim(), + poolId: input.poolId.trim(), + providerId: input.providerId.trim(), + serviceAccountEmail: input.serviceAccountEmail.trim().toLowerCase(), + } +} + +/** Whether every field has Google's documented format, so the commands can be shown. */ +export function isGoogleKeylessInputComplete(input: GoogleKeylessInput): boolean { + const value = normalize(input) + return ( + isGoogleProjectNumber(value.projectNumber) && + isGoogleWorkloadIdentityId(value.poolId) && + isGoogleWorkloadIdentityId(value.providerId) && + isGoogleServiceAccountEmail(value.serviceAccountEmail) + ) +} + +/** The `serviceAccountJson` a keyless Google credential is submitted as. */ +export function buildGoogleKeylessConfig(input: GoogleKeylessInput, setup: KeylessSetup) { + return { authType: 'workload_identity', ...normalize(input), ...keylessSubjectFields(setup) } +} + +interface GoogleKeylessFieldsProps { + input: GoogleKeylessInput + onChange: (input: GoogleKeylessInput) => void + setup: KeylessSetup +} + +/** + * The workload identity provider and service account of a keyless Google + * Cloud credential, plus the trust values and gcloud commands to paste. + */ +export function GoogleKeylessFields({ input, onChange, setup }: GoogleKeylessFieldsProps) { + const complete = isGoogleKeylessInputComplete(input) + const value = normalize(input) + const audience = complete ? googleWorkloadIdentityAudience(value) : undefined + const commands = + complete && setup.trust + ? googleWorkloadIdentitySetupCommands({ + ref: value, + serviceAccountEmail: value.serviceAccountEmail, + issuer: setup.trust.issuer, + subject: setup.trust.subject, + }) + : null + const edit = (field: keyof GoogleKeylessInput) => (next: string) => + onChange({ ...input, [field]: next }) + + return ( + <> + + + + + + {commands && ( + + {(aria) => ( + + )} + + )} + + ) +} diff --git a/apps/sim/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/keyless-connection.tsx b/apps/sim/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/keyless-connection.tsx index 157deb5124f..c0d81b69cbd 100644 --- a/apps/sim/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/keyless-connection.tsx +++ b/apps/sim/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/keyless-connection.tsx @@ -25,6 +25,8 @@ interface KeylessSetupInput { workspaceId?: string organizationId?: string credentialId?: string + /** False when the dialog cannot offer keyless at all (a Google Workspace service). */ + enabled?: boolean } /** @@ -40,22 +42,26 @@ export function useKeylessSetup({ workspaceId, organizationId, credentialId, + enabled = true, }: KeylessSetupInput) { const [sessionKey] = useState(() => generateShortId()) const [subjectChoice, setSubjectChoice] = useState( credentialId ? 'keep' : 'new' ) - const workspaceScoped = Boolean(workspaceId) && !organizationId + const workspaceScoped = enabled && Boolean(workspaceId) && !organizationId const setup = useWorkloadIdentitySetup({ workspaceId, provider, sessionKey, enabled: workspaceScoped, + credentialId, }) const trust = setup.data?.available ? setup.data : undefined return { /** Undefined while this deployment's support is still loading. */ available: workspaceScoped ? setup.data?.available : false, + /** The credential being reconnected is keyless (reported for Snowflake and Google only). */ + reconnectsKeyless: Boolean(setup.data?.available && setup.data.reconnectsKeyless), isReconnect: Boolean(credentialId), subjectChoice, setSubjectChoice, @@ -76,10 +82,15 @@ export function keylessSubjectFields(setup: KeylessSetup) { interface KeylessTrustFieldsProps { setup: KeylessSetup + /** The credential's own audience, for a provider without a fixed one (Google). */ + audience?: string } /** Reconnect choice plus the issuer, audience, and subject the customer configures. */ -export function KeylessTrustFields({ setup }: KeylessTrustFieldsProps) { +export function KeylessTrustFields({ + setup, + audience = setup.trust?.audience, +}: KeylessTrustFieldsProps) { return ( <> {setup.isReconnect && ( @@ -114,12 +125,14 @@ export function KeylessTrustFields({ setup }: KeylessTrustFieldsProps) { value={setup.trust.issuer} copyLabel='Copy issuer' /> - + {audience && ( + + )} void onClose: () => void + /** + * Copy for a shared verification code (`invalid_credentials`, …) the + * provider reports by code rather than with its own message; undefined + * keeps the server's message. + */ + messageForCode?: (code: string) => string | undefined } /** @@ -154,6 +173,7 @@ export function useSavedConnectionSubmit({ credentialId, onCreated, onClose, + messageForCode, }: SavedConnectionSubmitInput) { const [error, setError] = useState(null) const createCredential = useCreateScopedCredential() @@ -194,10 +214,15 @@ export function useSavedConnectionSubmit({ setError('A credential with that name already exists. Choose a different display name.') return } + const codeMessage = + isApiClientError(submitError) && submitError.code + ? messageForCode?.(submitError.code) + : undefined setError( - isApiClientError(submitError) && submitError.message - ? submitError.message - : 'Could not verify the credential. Check the details and try again.' + codeMessage ?? + (isApiClientError(submitError) && submitError.message + ? submitError.message + : 'Could not verify the credential. Check the details and try again.') ) } } diff --git a/apps/sim/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/microsoft-app-account-modal.tsx b/apps/sim/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/microsoft-app-account-modal.tsx new file mode 100644 index 00000000000..7fdd73da9f4 --- /dev/null +++ b/apps/sim/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/microsoft-app-account-modal.tsx @@ -0,0 +1,265 @@ +'use client' + +import { type ComponentType, useState } from 'react' +import { + ChipModal, + ChipModalBody, + ChipModalError, + ChipModalField, + ChipModalFooter, + ChipModalHeader, + SecretInput, +} from '@sim/emcn' +import { resourceScopeFromOwner, resourceScopeKey } from '@/lib/core/resource-scope' +import { MICROSOFT_APP_SERVICE_ACCOUNT_PROVIDER_ID } from '@/lib/oauth/types' +import { + KeylessTrustFields, + keylessSubjectFields, + useKeylessSetup, + useSavedConnectionSubmit, +} from '@/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/keyless-connection' +import { withBrandIcon } from '@/blocks/brand-icon' + +interface MicrosoftAppAccountModalProps { + open: boolean + onOpenChange: (open: boolean) => void + workspaceId?: string + organizationId?: string + serviceIcon: ComponentType<{ className?: string }> + credentialId?: string + initialDisplayName?: string + initialDescription?: string + onCreated?: (credentialId: string) => void +} + +type MicrosoftAuthType = 'federated' | 'client_secret' | 'certificate' + +const AUTH_TYPE_HINTS: Record = { + federated: + 'No secret is stored. Sim signs a short-lived token a federated credential on your app trusts.', + client_secret: 'Sim exchanges the client secret for a short-lived token on each run.', + certificate: 'Sim signs each token request with the certificate’s private key.', +} + +const DOCS_URL = 'https://docs.sim.ai/integrations/microsoft-app-credentials' + +/** Saved Microsoft app credentials share the standard credential create/reconnect lifecycle. */ +export function MicrosoftAppAccountModal(props: MicrosoftAppAccountModalProps) { + if (!props.open) return null + return ( + + ) +} + +function MicrosoftAppAccountForm({ + open, + onOpenChange, + workspaceId, + organizationId, + serviceIcon: ServiceIcon, + credentialId, + initialDisplayName, + initialDescription, + onCreated, +}: MicrosoftAppAccountModalProps) { + const keyless = useKeylessSetup({ + provider: 'microsoft', + workspaceId, + organizationId, + credentialId, + }) + const { submit, error, clearError, isPending } = useSavedConnectionSubmit({ + providerId: MICROSOFT_APP_SERVICE_ACCOUNT_PROVIDER_ID, + workspaceId, + organizationId, + credentialId, + onCreated, + onClose: () => onOpenChange(false), + }) + const [selectedAuthType, setSelectedAuthType] = useState(null) + const [tenantId, setTenantId] = useState('') + const [clientId, setClientId] = useState('') + const [environmentUrl, setEnvironmentUrl] = useState('') + const [clientSecret, setClientSecret] = useState('') + const [privateKey, setPrivateKey] = useState('') + const [certificate, setCertificate] = useState('') + const [displayName, setDisplayName] = useState(initialDisplayName ?? '') + const [description, setDescription] = useState(initialDescription ?? '') + + // A reconnect opens on keyless only for a keyless credential, which has a subject to keep; a + // new connection defaults to keyless wherever this deployment supports it. + const defaultAuthType: MicrosoftAuthType = credentialId + ? keyless.reconnectsKeyless + ? 'federated' + : 'client_secret' + : keyless.available + ? 'federated' + : 'client_secret' + const authType: MicrosoftAuthType = selectedAuthType ?? defaultAuthType + const disabled = + isPending || + !tenantId.trim() || + !clientId.trim() || + (authType === 'client_secret' && !clientSecret.trim()) || + (authType === 'certificate' && (!privateKey.trim() || !certificate.trim())) || + (authType === 'federated' && !keyless.ready) + + const edit = (setter: (value: string) => void) => (value: string) => { + setter(value) + clearError() + } + + const buildConfig = (): Record => { + const base = { + authType, + tenantId: tenantId.trim(), + clientId: clientId.trim(), + ...(environmentUrl.trim() ? { environmentUrl: environmentUrl.trim() } : {}), + } + if (authType === 'federated') return { ...base, ...keylessSubjectFields(keyless) } + if (authType === 'certificate') return { ...base, privateKey, certificate } + return { ...base, clientSecret } + } + + const action = credentialId ? 'Reconnect' : 'Add' + const authOptions = [ + ...(keyless.available + ? [{ value: 'federated', label: 'Federated credential (keyless, via Sim OIDC)' }] + : []), + { value: 'client_secret', label: 'Client secret' }, + { value: 'certificate', label: 'Certificate' }, + ] + + return ( + + onOpenChange(false)}> + {action} Microsoft app credential + + + { + setSelectedAuthType(value as MicrosoftAuthType) + clearError() + }} + options={authOptions} + placeholder='Choose how the app signs in' + required + hint={AUTH_TYPE_HINTS[authType]} + /> + + + + + {authType === 'client_secret' && ( + + {(aria) => ( + + )} + + )} + + {authType === 'certificate' && ( + <> + + + + )} + + {authType === 'federated' && } + + + + {error} + + onOpenChange(false)} + secondaryActions={[ + { + label: 'Setup guide', + onClick: () => window.open(DOCS_URL, '_blank', 'noopener,noreferrer'), + }, + ]} + primaryAction={{ + label: isPending ? 'Verifying...' : `${action} credential`, + onClick: () => { + if (!disabled) void submit({ config: buildConfig(), displayName, description }) + }, + disabled, + }} + /> + + ) +} diff --git a/apps/sim/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/snowflake-account-modal.tsx b/apps/sim/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/snowflake-account-modal.tsx new file mode 100644 index 00000000000..9bb2c85b5bf --- /dev/null +++ b/apps/sim/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/snowflake-account-modal.tsx @@ -0,0 +1,352 @@ +'use client' + +import { type ComponentType, useState } from 'react' +import { + ChipModal, + ChipModalBody, + ChipModalError, + ChipModalField, + ChipModalFooter, + ChipModalHeader, + ChipTextarea, + SecretInput, +} from '@sim/emcn' +import { isApiClientError } from '@/lib/api/client/errors' +import { + resourceScopeFields, + resourceScopeFromOwner, + resourceScopeKey, +} from '@/lib/core/resource-scope' +import { + getTokenServiceAccountDescriptor, + getTokenServiceAccountErrorMessage, + SNOWFLAKE_SERVICE_ACCOUNT_PROVIDER_ID, +} from '@/lib/credentials/token-service-accounts/descriptors' +import { + type KeylessSetup, + KeylessTrustFields, + keylessSubjectFields, + useKeylessSetup, + useSavedConnectionSubmit, +} from '@/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/keyless-connection' +import { TokenServiceAccountModal } from '@/app/workspace/[workspaceId]/integrations/components/connect-service-account-modal/token-service-account-modal' +import { withBrandIcon } from '@/blocks/brand-icon' +import { + useCreateScopedCredential, + useUpdateScopedCredential, +} from '@/hooks/queries/scoped-credentials' + +interface SnowflakeAccountModalProps { + open: boolean + onOpenChange: (open: boolean) => void + workspaceId?: string + organizationId?: string + serviceName: string + serviceIcon: ComponentType<{ className?: string }> + credentialId?: string + initialDisplayName?: string + initialDescription?: string + onCreated?: (credentialId: string) => void +} + +type SnowflakeAuthType = 'workload_identity' | 'programmatic_access_token' + +const SNOWFLAKE_DESCRIPTOR = getTokenServiceAccountDescriptor(SNOWFLAKE_SERVICE_ACCOUNT_PROVIDER_ID) +const SNOWFLAKE_DOCS_URL = 'https://docs.sim.ai/integrations/snowflake-service-account' +const HOST_PATTERN = /^[a-z0-9][a-z0-9.-]*\.snowflakecomputing\.(com|cn)$/i + +const AUTH_TYPE_HINTS: Record = { + workload_identity: + 'No secret is stored. Sim signs a short-lived token your Snowflake service user trusts.', + programmatic_access_token: 'Sim sends this token on every request.', +} + +/** Copy for the shared verification codes a keyless save reports. */ +function keylessErrorMessage(code: string): string | undefined { + switch (code) { + case 'invalid_credentials': + return 'Snowflake did not accept Sim’s token. Check that a service user on this account was created with exactly the issuer and subject shown, that a network policy allows Sim to reach the account, and that no authentication policy blocks workload identity.' + case 'site_not_found': + return "We couldn't find a Snowflake account at that host. It should look like myorg-myaccount.snowflakecomputing.com." + case 'provider_unavailable': + return "We couldn't reach Snowflake to verify this connection. Try again in a moment." + default: + return undefined + } +} + +/** The statement that creates a service user trusting only this credential's subject. */ +function buildCreateUserStatement(issuer: string, subject: string) { + return [ + 'CREATE USER SIM_WORKFLOWS', + ' WORKLOAD_IDENTITY = (', + ' TYPE = OIDC', + ` ISSUER = '${issuer}'`, + ` SUBJECT = '${subject}'`, + ' )', + ' TYPE = SERVICE;', + ].join('\n') +} + +function normalizeHostInput(raw: string): string { + return raw + .trim() + .replace(/^https?:\/\//i, '') + .replace(/[/?#].*$/, '') +} + +/** + * Snowflake connections: a programmatic access token, or keyless workload + * identity where this deployment can sign tokens. Where it cannot (or for an + * organization credential, which keyless never binds to), the standard + * token dialog is shown unchanged. + */ +export function SnowflakeAccountModal(props: SnowflakeAccountModalProps) { + if (!props.open) return null + return ( + + ) +} + +function SnowflakeAccountGate(props: SnowflakeAccountModalProps) { + const keyless = useKeylessSetup({ + provider: 'snowflake', + workspaceId: props.workspaceId, + organizationId: props.organizationId, + credentialId: props.credentialId, + }) + if (keyless.available === false && SNOWFLAKE_DESCRIPTOR) { + return + } + return +} + +function SnowflakeAccountForm({ + open, + onOpenChange, + workspaceId, + organizationId, + serviceIcon: ServiceIcon, + credentialId, + initialDisplayName, + initialDescription, + onCreated, + keyless, +}: SnowflakeAccountModalProps & { keyless: KeylessSetup }) { + const close = () => onOpenChange(false) + const keylessSubmit = useSavedConnectionSubmit({ + providerId: SNOWFLAKE_SERVICE_ACCOUNT_PROVIDER_ID, + workspaceId, + organizationId, + credentialId, + onCreated, + onClose: close, + messageForCode: keylessErrorMessage, + }) + const createCredential = useCreateScopedCredential() + const updateCredential = useUpdateScopedCredential() + const [tokenError, setTokenError] = useState(null) + const [selectedAuthType, setSelectedAuthType] = useState(null) + const [host, setHost] = useState('') + const [token, setToken] = useState('') + const [displayName, setDisplayName] = useState(initialDisplayName ?? '') + const [description, setDescription] = useState(initialDescription ?? '') + + // A reconnect opens on the credential's current mode, so a keyless connection is never + // turned into a token one by default; a new connection defaults to keyless wherever this + // deployment supports it. + const defaultAuthType: SnowflakeAuthType = credentialId + ? keyless.reconnectsKeyless + ? 'workload_identity' + : 'programmatic_access_token' + : keyless.available + ? 'workload_identity' + : 'programmatic_access_token' + const authType: SnowflakeAuthType = selectedAuthType ?? defaultAuthType + const normalizedHost = normalizeHostInput(host) + const isPending = + keylessSubmit.isPending || createCredential.isPending || updateCredential.isPending + const disabled = + isPending || + !normalizedHost || + (authType === 'programmatic_access_token' && !token.trim()) || + (authType === 'workload_identity' && !keyless.ready) + const error = authType === 'workload_identity' ? keylessSubmit.error : tokenError + + const clearErrors = () => { + keylessSubmit.clearError() + setTokenError(null) + } + const edit = (setter: (value: string) => void) => (value: string) => { + setter(value) + clearErrors() + } + + const submitToken = async () => { + const fields = { + ...resourceScopeFields(resourceScopeFromOwner({ workspaceId, organizationId })), + apiToken: token.trim(), + domain: normalizedHost, + displayName: displayName.trim() || undefined, + description: description.trim() || undefined, + } + try { + if (credentialId) { + await updateCredential.mutateAsync({ ...fields, credentialId }) + onCreated?.(credentialId) + } else { + const created = await createCredential.mutateAsync({ + ...fields, + type: 'service_account', + providerId: SNOWFLAKE_SERVICE_ACCOUNT_PROVIDER_ID, + }) + onCreated?.(created.credential.id) + } + close() + } catch (submitError) { + const code = isApiClientError(submitError) ? submitError.code : undefined + setTokenError( + SNOWFLAKE_DESCRIPTOR + ? getTokenServiceAccountErrorMessage(SNOWFLAKE_DESCRIPTOR, code) + : 'Could not verify the credential. Check the details and try again.' + ) + } + } + + const handleSubmit = () => { + if (disabled) return + clearErrors() + if (authType === 'programmatic_access_token') { + void submitToken() + return + } + void keylessSubmit.submit({ + config: { + authType: 'workload_identity', + host: normalizedHost, + ...keylessSubjectFields(keyless), + }, + displayName, + description, + }) + } + + const createUserStatement = + authType === 'workload_identity' && keyless.trust + ? buildCreateUserStatement(keyless.trust.issuer, keyless.trust.subject) + : null + const action = credentialId ? 'Reconnect' : 'Add' + const authOptions = [ + ...(keyless.available + ? [{ value: 'workload_identity', label: 'Service user (keyless, via Sim OIDC)' }] + : []), + { value: 'programmatic_access_token', label: 'Programmatic access token' }, + ] + + return ( + + + {action} Snowflake connection + + + { + setSelectedAuthType(value as SnowflakeAuthType) + clearErrors() + }} + options={authOptions} + placeholder='Choose how Sim signs in to Snowflake' + required + hint={AUTH_TYPE_HINTS[authType]} + /> + + + {authType === 'programmatic_access_token' && ( + + {(aria) => ( + + )} + + )} + + {authType === 'workload_identity' && } + + {createUserStatement && ( + + {(aria) => ( + + )} + + )} + + + + {error} + + window.open(SNOWFLAKE_DOCS_URL, '_blank', 'noopener,noreferrer'), + }, + ]} + primaryAction={{ + label: isPending ? 'Verifying...' : `${action} connection`, + onClick: handleSubmit, + disabled, + }} + /> + + ) +} diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/credential-selector/credential-selector.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/credential-selector/credential-selector.tsx index 5d65eb013a5..3061fb6958f 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/credential-selector/credential-selector.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/credential-selector/credential-selector.tsx @@ -563,6 +563,7 @@ export function CredentialSelector({ } serviceName={serviceAccountTarget.serviceName} serviceIcon={serviceAccountTarget.serviceIcon} + oauthServiceId={serviceId} onCreated={(newCredentialId) => { setStoreValue(newCredentialId) refetchCredentials() diff --git a/apps/sim/blocks/blocks/github.ts b/apps/sim/blocks/blocks/github.ts index 447299d3fee..a40fcf32d95 100644 --- a/apps/sim/blocks/blocks/github.ts +++ b/apps/sim/blocks/blocks/github.ts @@ -2,7 +2,7 @@ import { Calendar } from '@sim/emcn/icons' import { GithubIcon } from '@/components/icons' import type { BlockConfig, BlockMeta } from '@/blocks/types' import { AuthMode, IntegrationType } from '@/blocks/types' -import { createVersionedToolSelector } from '@/blocks/utils' +import { createVersionedToolSelector, withSavedCredential } from '@/blocks/utils' import { getTrigger } from '@/triggers' /** Reviewers can be named individually or by team slug; either identifies the request. */ @@ -369,7 +369,7 @@ export const GitHubBlock: BlockConfig = { }, triggerAllowed: true, hideFromToolbar: true, - sunset: { status: 'legacy', replacedBy: 'github_v2' }, + sunset: { status: 'legacy', replacedBy: 'github_v3' }, subBlocks: [ { id: 'operation', @@ -2436,10 +2436,10 @@ Return ONLY the timestamp string - no explanations, no quotes, no extra text.`, export const GitHubV2Block: BlockConfig = { ...GitHubBlock, - sunset: undefined, + sunset: { status: 'legacy', replacedBy: 'github_v3' }, type: 'github_v2', name: 'GitHub', - hideFromToolbar: false, + hideFromToolbar: true, integrationType: IntegrationType.DevOps, tools: { ...GitHubBlock.tools, @@ -2481,6 +2481,20 @@ export const GitHubV2Block: BlockConfig = { }, } +export const GitHubV3Block: BlockConfig = { + ...GitHubV2Block, + type: 'github_v3', + authMode: AuthMode.OAuth, + hideFromToolbar: false, + sunset: undefined, + ...withSavedCredential(GitHubV2Block, { + id: 'credential', + type: 'oauth-input', + serviceId: 'github-token', + title: 'GitHub Credential', + }), +} + export const GitHubBlockMeta = { tags: ['version-control', 'ci-cd'], url: 'https://github.com', diff --git a/apps/sim/blocks/registry-maps.ts b/apps/sim/blocks/registry-maps.ts index af7149b90f2..1e0b4959fb3 100644 --- a/apps/sim/blocks/registry-maps.ts +++ b/apps/sim/blocks/registry-maps.ts @@ -122,6 +122,7 @@ import { GitHubBlockMeta, GitHubV2Block, GitHubV2BlockMeta, + GitHubV3Block, } from '@/blocks/blocks/github' import { GitLabBlock, GitLabBlockMeta, GitLabV2Block } from '@/blocks/blocks/gitlab' import { GmailBlock, GmailBlockMeta, GmailV2Block, GmailV2BlockMeta } from '@/blocks/blocks/gmail' @@ -627,6 +628,7 @@ export const BLOCK_REGISTRY: Record = { generic_webhook: GenericWebhookBlock, github: GitHubBlock, github_v2: GitHubV2Block, + github_v3: GitHubV3Block, gitlab: GitLabBlock, gitlab_v2: GitLabV2Block, gmail: GmailBlock, @@ -1065,6 +1067,7 @@ export const BLOCK_META_REGISTRY: Record = { gauge: GaugeBlockMeta, github: GitHubBlockMeta, github_v2: GitHubV2BlockMeta, + github_v3: GitHubV2BlockMeta, gitlab: GitLabBlockMeta, gmail: GmailBlockMeta, gmail_v2: GmailV2BlockMeta, diff --git a/apps/sim/connectors/docusign/docusign.test.ts b/apps/sim/connectors/docusign/docusign.test.ts new file mode 100644 index 00000000000..5565d57633e --- /dev/null +++ b/apps/sim/connectors/docusign/docusign.test.ts @@ -0,0 +1,98 @@ +import { knowledgeDocumentsUtilsMock } from '@sim/testing/mocks/knowledge-documents-utils.mock' +import { + knowledgeSecureFetchMock, + knowledgeSecureFetchMockFns, +} from '@sim/testing/mocks/knowledge-secure-fetch.mock' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('@/lib/knowledge/documents/utils', () => knowledgeDocumentsUtilsMock) +vi.mock('@/lib/knowledge/documents/secure-fetch.server', () => knowledgeSecureFetchMock) + +import { docusignConnector } from '@/connectors/docusign/docusign' + +const mockFetchWithRetry = knowledgeSecureFetchMockFns.mockFetchWithRetry + +const DEFAULT_ACCOUNT = '99999999-0000-0000-0000-000000000001' +const PINNED_ACCOUNT = '99999999-0000-0000-0000-000000000002' +/** A production account, pinned, while the deployment's OAuth host stays on demo. */ +const BOUND_BASE = `https://na3.docusign.net/restapi/v2.1/accounts/${PINNED_ACCOUNT}` + +function reply(body: unknown, status = 200): Response { + return { + ok: status >= 200 && status < 300, + status, + json: async () => body, + text: async () => JSON.stringify(body), + } as unknown as Response +} + +/** Answers userinfo with a demo default account and every envelope listing with one envelope. */ +function mockDocuSign() { + mockFetchWithRetry.mockImplementation(async (url: string) => { + if (url.endsWith('/oauth/userinfo')) { + return reply({ + accounts: [ + { account_id: DEFAULT_ACCOUNT, is_default: true, base_uri: 'https://demo.docusign.net' }, + ], + }) + } + return reply({ + envelopes: [{ envelopeId: 'env-1', emailSubject: 'Offer', status: 'sent' }], + totalSetSize: '1', + }) + }) +} + +describe('docusign connector account binding', () => { + it("lists the JWT credential's pinned account in its own environment, never the deployment default", async () => { + mockDocuSign() + + const result = await docusignConnector.listDocuments('jwt-token', {}, undefined, { + credentialInstanceUrl: BOUND_BASE, + }) + + const urls = mockFetchWithRetry.mock.calls.map(([url]) => String(url)) + expect(urls.some((url) => url.endsWith('/oauth/userinfo'))).toBe(false) + expect(urls[0].startsWith(`${BOUND_BASE}/envelopes?`)).toBe(true) + expect(result.documents[0]?.sourceUrl).toBe('https://app.docusign.com/documents/details/env-1') + }) + + it('resolves an OAuth token through userinfo on the deployment host as before', async () => { + mockDocuSign() + + const result = await docusignConnector.listDocuments('oauth-token', {}, undefined, {}) + + const urls = mockFetchWithRetry.mock.calls.map(([url]) => String(url)) + expect(urls[0]).toBe('https://account-d.docusign.com/oauth/userinfo') + expect( + urls[1].startsWith(`https://demo.docusign.net/restapi/v2.1/accounts/${DEFAULT_ACCOUNT}/`) + ).toBe(true) + expect(result.documents[0]?.sourceUrl).toBe( + 'https://appdemo.docusign.com/documents/details/env-1' + ) + }) + + it('validates a JWT credential without asking the deployment host', async () => { + mockDocuSign() + + await expect( + docusignConnector.validateConfig('jwt-token', {}, { credentialInstanceUrl: BOUND_BASE }) + ).resolves.toEqual({ valid: true }) + expect(mockFetchWithRetry).not.toHaveBeenCalled() + }) + + it.each([ + 'https://evil.example.com/restapi/v2.1/accounts/x', + `http://na3.docusign.net/restapi/v2.1/accounts/${PINNED_ACCOUNT}`, + ])('fails closed on a seeded account base of the wrong shape: %s', async (bound) => { + mockDocuSign() + + await expect( + docusignConnector.listDocuments('jwt-token', {}, undefined, { credentialInstanceUrl: bound }) + ).rejects.toThrow('DocuSign credential account URL is invalid') + await expect( + docusignConnector.validateConfig('jwt-token', {}, { credentialInstanceUrl: bound }) + ).resolves.toMatchObject({ valid: false }) + expect(mockFetchWithRetry).not.toHaveBeenCalled() + }) +}) diff --git a/apps/sim/connectors/docusign/docusign.ts b/apps/sim/connectors/docusign/docusign.ts index 365d362aa0c..22187974c0f 100644 --- a/apps/sim/connectors/docusign/docusign.ts +++ b/apps/sim/connectors/docusign/docusign.ts @@ -2,7 +2,11 @@ import { createLogger } from '@sim/logger' import { getErrorMessage, toError } from '@sim/utils/errors' import { fetchWithRetry } from '@/lib/knowledge/documents/secure-fetch.server' import { VALIDATE_RETRY_OPTIONS } from '@/lib/knowledge/documents/utils' -import { getDocusignOAuthUrl, getDocusignWebBase } from '@/lib/oauth/docusign' +import { + getDocusignOAuthUrl, + getDocusignWebBase, + parseDocuSignAccountApiBase, +} from '@/lib/oauth/docusign' import { docusignConnectorMeta } from '@/connectors/docusign/meta' import type { ConnectorConfig, ExternalDocument, ExternalDocumentList } from '@/connectors/types' import { parseTagDate } from '@/connectors/utils' @@ -34,6 +38,8 @@ interface DocuSignUserInfo { interface ResolvedAccount { accountId: string baseUri: string + /** Web app origin for envelope links; set only for a credential-bound account. */ + webBase?: string } interface DocuSignSigner { @@ -138,6 +144,22 @@ function computeLookbackDays( return Math.min(incremental, baseline) } +/** + * The account a JWT Grant credential is bound to, seeded into the sync context + * from its token. Its environment and pinned account come from the credential, + * so the deployment's OAuth host is never asked. A seeded value of the wrong + * shape fails the run rather than falling back to the user's default account. + */ +function credentialBoundAccount( + syncContext: Record | undefined +): ResolvedAccount | undefined { + const bound = syncContext?.credentialInstanceUrl + if (bound === undefined) return undefined + const account = parseDocuSignAccountApiBase(bound) + if (!account) throw new Error('DocuSign credential account URL is invalid') + return account +} + /** * Resolves and caches the user's DocuSign account ID and base URI in the sync context. * The userinfo lookup is expensive and identical across every page of a sync run, so it is @@ -151,6 +173,11 @@ async function resolveAccount( const cacheKey = '_docusignAccount' const cached = syncContext?.[cacheKey] as ResolvedAccount | undefined if (cached) return cached + const bound = credentialBoundAccount(syncContext) + if (bound) { + if (syncContext) syncContext[cacheKey] = bound + return bound + } const response = await fetchWithRetry( getDocusignOAuthUrl('/oauth/userinfo'), @@ -211,9 +238,12 @@ function buildContentHash(envelope: DocuSignEnvelope): string { /** * Builds a DocuSign web console link to the envelope, when an envelope ID is present. */ -function buildSourceUrl(envelopeId: string | undefined): string | undefined { +function buildSourceUrl( + envelopeId: string | undefined, + account: ResolvedAccount +): string | undefined { if (!envelopeId) return undefined - return `${getDocusignWebBase()}/documents/details/${envelopeId}` + return `${account.webBase ?? getDocusignWebBase()}/documents/details/${envelopeId}` } /** @@ -286,14 +316,14 @@ function buildMetadata(envelope: DocuSignEnvelope): Record { * Creates a lightweight document stub from an envelope list entry. No per-envelope API * calls are made — content is fetched lazily by getDocument for new/changed envelopes only. */ -function envelopeToStub(envelope: DocuSignEnvelope): ExternalDocument { +function envelopeToStub(envelope: DocuSignEnvelope, account: ResolvedAccount): ExternalDocument { return { externalId: envelope.envelopeId ?? '', title: envelope.emailSubject?.trim() || 'Untitled DocuSign Envelope', content: '', contentDeferred: true, mimeType: 'text/plain', - sourceUrl: buildSourceUrl(envelope.envelopeId), + sourceUrl: buildSourceUrl(envelope.envelopeId, account), contentHash: buildContentHash(envelope), metadata: buildMetadata(envelope), } @@ -505,7 +535,7 @@ export const docusignConnector: ConnectorConfig = { */ let capped = envelopes.length < rawEnvelopes.length - let documents = envelopes.map(envelopeToStub) + let documents = envelopes.map((envelope) => envelopeToStub(envelope, account)) if (documents.length > remaining) { documents = documents.slice(0, remaining) capped = true @@ -597,7 +627,7 @@ export const docusignConnector: ConnectorConfig = { content, contentDeferred: false, mimeType: 'text/plain', - sourceUrl: buildSourceUrl(envelope.envelopeId), + sourceUrl: buildSourceUrl(envelope.envelopeId, account), contentHash: buildContentHash(envelope), metadata: buildMetadata(envelope), } @@ -618,7 +648,8 @@ export const docusignConnector: ConnectorConfig = { validateConfig: async ( accessToken: string, - sourceConfig: Record + sourceConfig: Record, + syncContext?: Record ): Promise<{ valid: boolean; error?: string }> => { const maxEnvelopes = sourceConfig.maxEnvelopes as string | undefined if (maxEnvelopes && (Number.isNaN(Number(maxEnvelopes)) || Number(maxEnvelopes) < 0)) { @@ -626,7 +657,9 @@ export const docusignConnector: ConnectorConfig = { } try { - await resolveAccount(accessToken, undefined, VALIDATE_RETRY_OPTIONS) + if (!credentialBoundAccount(syncContext)) { + await resolveAccount(accessToken, undefined, VALIDATE_RETRY_OPTIONS) + } return { valid: true } } catch (error) { const message = getErrorMessage(error, 'Failed to validate configuration') diff --git a/apps/sim/ee/access-requests/lib/catalog.test.ts b/apps/sim/ee/access-requests/lib/catalog.test.ts index 0d497835e1d..d73504d5745 100644 --- a/apps/sim/ee/access-requests/lib/catalog.test.ts +++ b/apps/sim/ee/access-requests/lib/catalog.test.ts @@ -145,7 +145,7 @@ describe('access request catalog deployment ceilings', () => { name: 'Slack', tools: { access: ['slack_send_message_v2', 'missing'] }, }, - github_v2: { type: 'github_v2', name: 'GitHub', tools: { access: ['github_create_issue'] } }, + github_v3: { type: 'github_v3', name: 'GitHub', tools: { access: ['github_create_issue'] } }, github: { type: 'github', name: 'Retired GitHub', @@ -168,7 +168,7 @@ describe('access request catalog deployment ceilings', () => { 'loop', 'parallel', 'slack_v2', - 'github_v2', + 'github_v3', 'revealed', ]) expect([...catalog.tools.keys()]).toEqual(['slack_send_message_v2', 'github_create_issue']) @@ -193,16 +193,16 @@ describe('access request catalog deployment ceilings', () => { mocks.allowedIntegrations.mockReturnValue(['slack']) const catalog = await loadAccessRequestCatalog(context, 'integration') expect( - validateAccessRequestTarget({ kind: 'integration', id: 'github_v2' }, catalog) + validateAccessRequestTarget({ kind: 'integration', id: 'github_v3' }, catalog) ).toBeNull() - const config = { ...DEFAULT_PERMISSION_GROUP_CONFIG, allowedIntegrations: ['github_v2'] } + const config = { ...DEFAULT_PERMISSION_GROUP_CONFIG, allowedIntegrations: ['github_v3'] } const delta = buildAccessRequestPolicyDelta( { kind: 'integration', id: 'slack_v2' }, config, catalog ) - expect(delta.config.allowedIntegrations).toEqual(['github_v2', 'slack_v2']) - expect(config.allowedIntegrations).toEqual(['github_v2']) + expect(delta.config.allowedIntegrations).toEqual(['github_v3', 'slack_v2']) + expect(config.allowedIntegrations).toEqual(['github_v3']) }) it('omits blacklisted/retired models, unconfigured endpoints, and private dynamic names', async () => { diff --git a/apps/sim/ee/access-requests/lib/targets.test.ts b/apps/sim/ee/access-requests/lib/targets.test.ts index 6c03eabd2fd..8d60e5d2aae 100644 --- a/apps/sim/ee/access-requests/lib/targets.test.ts +++ b/apps/sim/ee/access-requests/lib/targets.test.ts @@ -107,7 +107,7 @@ describe('access request targets', () => { config, catalog ) - expect(delta.config.allowedIntegrations).toEqual(['github_v2', 'slack_v2']) + expect(delta.config.allowedIntegrations).toEqual(['github_v3', 'slack_v2']) expect(delta.config.deniedTools).toEqual(['other_tool']) expect(delta.changes.map((change) => change.configKey)).toEqual([ 'allowedIntegrations', diff --git a/apps/sim/executor/utils/credential-token.assistant.test.ts b/apps/sim/executor/utils/credential-token.assistant.test.ts new file mode 100644 index 00000000000..14ee2aec557 --- /dev/null +++ b/apps/sim/executor/utils/credential-token.assistant.test.ts @@ -0,0 +1,114 @@ +/** + * Drives the Assistant's GitHub token resolution through the real token resolver + * (`lib/oauth/token-resolution`), so the tool policy it binds against is the one the + * resolver actually reads, not a mock's. + */ +import { auditMock } from '@sim/testing/mocks/audit.mock' +import { authOAuthUtilsMock, authOAuthUtilsMockFns } from '@sim/testing/mocks/auth-oauth-utils.mock' +import { posthogServerMock } from '@sim/testing/mocks/posthog-server.mock' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { mockAuthorizeCredentialUseForAuth, mockPersonalCredentialUseCase } = vi.hoisted(() => ({ + mockAuthorizeCredentialUseForAuth: vi.fn(), + mockPersonalCredentialUseCase: vi.fn(), +})) + +vi.mock('@sim/audit', () => auditMock) +vi.mock('@/lib/posthog/server', () => posthogServerMock) +vi.mock('@/lib/oauth/credential-service', () => authOAuthUtilsMock) +vi.mock('@/lib/auth/credential-access', () => ({ + authorizeCredentialUseForAuth: mockAuthorizeCredentialUseForAuth, +})) +vi.mock('@/lib/mothership/application/execute-credential-use-case', () => ({ + executeCopilotCredentialUseCase: mockPersonalCredentialUseCase, +})) +vi.unmock('@/lib/oauth/utils') + +import { resolveExecutorCredentialToken } from '@/executor/utils/credential-token' +import { getToolMetadata } from '@/tools/metadata' + +const { mockGetCredential, mockRefreshTokenIfNeeded, mockResolveOAuthAccountId } = + authOAuthUtilsMockFns + +const ASSISTANT = { + userId: 'person', + workspaceId: 'ws-1', + chatId: 'chat-1', + toolCallId: 'call-1', + copilotToolExecution: true, + requestMode: 'assistant' as const, +} + +function resolve(overrides: Partial[0]> = {}) { + return resolveExecutorCredentialToken({ + requestId: 'req-1', + credentialId: 'own-account', + userId: 'person', + toolId: 'github_search_users_v2', + copilotExecutionContext: ASSISTANT, + ...overrides, + }) +} + +describe('Assistant GitHub calls through the real token resolver', () => { + beforeEach(async () => { + const actual = await vi.importActual('@/tools/metadata') + vi.mocked(getToolMetadata).mockImplementation(actual.getToolMetadata) + mockPersonalCredentialUseCase.mockResolvedValue({ id: 'own-account' }) + mockAuthorizeCredentialUseForAuth.mockResolvedValue({ + ok: true, + requesterUserId: 'person', + credentialOwnerUserId: 'person', + workspaceId: 'ws-1', + resolvedCredentialId: 'own-account', + }) + mockRefreshTokenIfNeeded.mockResolvedValue({ accessToken: 'personal-github-oauth' }) + }) + + it("resolves the person's own GitHub account for a GitHub tool", async () => { + mockResolveOAuthAccountId.mockResolvedValue({ + credentialType: 'oauth', + credentialId: 'own-account', + providerId: 'github-repositories', + accountId: 'account-1', + workspaceId: 'ws-1', + usedCredentialTable: true, + }) + mockGetCredential.mockResolvedValue({ providerId: 'github-repositories', scope: 'repo' }) + + await expect(resolve()).resolves.toMatchObject({ accessToken: 'personal-github-oauth' }) + }) + + it('never hands the Assistant a saved workspace GitHub token', async () => { + mockResolveOAuthAccountId.mockResolvedValue({ + credentialType: 'service_account', + credentialId: 'workspace-token', + providerId: 'github-service-account', + accountId: '', + workspaceId: 'ws-1', + usedCredentialTable: true, + }) + + await expect(resolve({ credentialId: 'workspace-token' })).rejects.toThrow( + 'The selected credential type is not supported by this tool' + ) + expect(authOAuthUtilsMockFns.mockResolveServiceAccountToken).not.toHaveBeenCalled() + }) + + it("does not let a workflow run bind GitHub tools to a person's GitHub account", async () => { + mockResolveOAuthAccountId.mockResolvedValue({ + credentialType: 'oauth', + credentialId: 'own-account', + providerId: 'github-repositories', + accountId: 'account-1', + workspaceId: 'ws-1', + usedCredentialTable: true, + }) + mockGetCredential.mockResolvedValue({ providerId: 'github-repositories', scope: 'repo' }) + + await expect(resolve({ copilotExecutionContext: undefined })).rejects.toThrow( + 'The selected credential type is not supported by this tool' + ) + expect(mockRefreshTokenIfNeeded).not.toHaveBeenCalled() + }) +}) diff --git a/apps/sim/executor/utils/credential-token.ts b/apps/sim/executor/utils/credential-token.ts index e68542abace..471c678c1ea 100644 --- a/apps/sim/executor/utils/credential-token.ts +++ b/apps/sim/executor/utils/credential-token.ts @@ -115,6 +115,7 @@ export async function resolveExecutorCredentialToken( workflowId, executionId: params.executionId, toolId, + assistantConnectedAccount: copilotExecutionContext?.requestMode === 'assistant', scopes: params.scopes, impersonateEmail: params.impersonateEmail, callerUserId: userId && params.enforceCredentialAccess ? userId : undefined, diff --git a/apps/sim/executor/utils/vertex-credential.ts b/apps/sim/executor/utils/vertex-credential.ts index 0fb22b53188..4914d66d405 100644 --- a/apps/sim/executor/utils/vertex-credential.ts +++ b/apps/sim/executor/utils/vertex-credential.ts @@ -58,9 +58,12 @@ export async function resolveVertexCredential({ } if (cred.type === 'service_account') { - const accessToken = await getServiceAccountToken(cred.id, [ - 'https://www.googleapis.com/auth/cloud-platform', - ]) + const accessToken = await getServiceAccountToken( + cred.id, + ['https://www.googleapis.com/auth/cloud-platform'], + undefined, + { service: 'vertex-ai' } + ) recordCredentialAccess({ actorId: actingUserId, workspaceId: cred.workspaceId, diff --git a/apps/sim/hooks/queries/oauth/connections.test.tsx b/apps/sim/hooks/queries/oauth/connections.test.tsx index 8c0cbee19af..91e6563793c 100644 --- a/apps/sim/hooks/queries/oauth/connections.test.tsx +++ b/apps/sim/hooks/queries/oauth/connections.test.tsx @@ -3,7 +3,10 @@ */ import { act, type ReactNode } from 'react' -import { apiClientRequestMock } from '@sim/testing/mocks/api-client-request.mock' +import { + apiClientRequestMock, + apiClientRequestMockFns, +} from '@sim/testing/mocks/api-client-request.mock' import { authClientMock, authClientMockFns } from '@sim/testing/mocks/auth-client.mock' import { libDesktopMock, libDesktopMockFns } from '@sim/testing/mocks/lib-desktop.mock' import { QueryClient, QueryClientProvider } from '@tanstack/react-query' @@ -13,9 +16,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' vi.mock('@/lib/api/client/request', () => apiClientRequestMock) vi.mock('@/lib/auth/client', () => authClientMock) vi.mock('@/lib/desktop', () => libDesktopMock) -vi.mock('@/lib/oauth', () => ({ OAUTH_PROVIDERS: {} })) +const { oauthProviders } = vi.hoisted(() => ({ + oauthProviders: {} as Record }>, +})) +vi.mock('@/lib/oauth', () => ({ OAUTH_PROVIDERS: oauthProviders })) -import { useConnectOAuthService } from '@/hooks/queries/oauth/connections' +import { useConnectOAuthService, useOAuthConnections } from '@/hooks/queries/oauth/connections' const beginOAuthConnect = vi.fn() const oauthLink = authClientMockFns.mockClient.oauth2.link @@ -72,3 +78,69 @@ describe('useConnectOAuthService', () => { } ) }) + +describe('useOAuthConnections', () => { + afterEach(() => { + for (const key of Object.keys(oauthProviders)) delete oauthProviders[key] + }) + + it('never marks a token-only service connected from a sign-in account sharing its prefix', async () => { + oauthProviders['github-token'] = { + services: { + 'github-token': { + name: 'GitHub', + providerId: 'github-token', + serviceAccountProviderId: 'github-service-account', + authType: 'service_account', + scopes: [], + }, + }, + } + oauthProviders.dub = { + services: { dub: { name: 'Dub', providerId: 'dub', scopes: [] } }, + } + apiClientRequestMockFns.mockRequestJson.mockResolvedValue({ + connections: [ + { + provider: 'github', + baseProvider: 'github', + featureType: 'default', + isConnected: true, + scopes: ['read:user'], + lastConnected: '2026-11-01T00:00:00.000Z', + accounts: [{ id: 'sign-in', name: 'octo (GitHub)' }], + }, + { + provider: 'dub-legacy', + baseProvider: 'dub', + featureType: 'default', + isConnected: true, + scopes: [], + lastConnected: '2026-11-01T00:00:00.000Z', + accounts: [{ id: 'dub-account', name: 'Dub' }], + }, + ], + }) + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }) + const container = document.createElement('div') + const root = createRoot(container) + let services: ReturnType['data'] + function Probe() { + services = useOAuthConnections().data + return null + } + ;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true + await act(async () => { + root.render( + + + + ) + }) + await vi.waitFor(() => expect(services).toBeDefined()) + + expect(services?.find((service) => service.id === 'github-token')?.isConnected).toBe(false) + expect(services?.find((service) => service.id === 'dub')?.isConnected).toBe(true) + act(() => root.unmount()) + }) +}) diff --git a/apps/sim/hooks/queries/oauth/connections.ts b/apps/sim/hooks/queries/oauth/connections.ts index beaf36c6e67..7fbce7ed4d2 100644 --- a/apps/sim/hooks/queries/oauth/connections.ts +++ b/apps/sim/hooks/queries/oauth/connections.ts @@ -88,6 +88,10 @@ async function fetchOAuthConnections(signal?: AbortSignal): Promise { if (!conn.baseProvider || !service.providerId.startsWith(conn.baseProvider)) { return false diff --git a/apps/sim/hooks/queries/scoped-credentials.ts b/apps/sim/hooks/queries/scoped-credentials.ts index 310f802e9a2..5f71035e48b 100644 --- a/apps/sim/hooks/queries/scoped-credentials.ts +++ b/apps/sim/hooks/queries/scoped-credentials.ts @@ -136,6 +136,8 @@ interface UseWorkloadIdentitySetupProps { /** One per modal session, so each open gets its own subject. */ sessionKey: string enabled: boolean + /** The credential being reconnected, if any. */ + credentialId?: string } /** @@ -149,7 +151,11 @@ export function useWorkloadIdentitySetup(input: UseWorkloadIdentitySetupProps) { queryKey: workloadIdentityKeys.setup(input.workspaceId, input.provider, input.sessionKey), queryFn: async ({ signal }) => requestJson(prepareWorkloadIdentityContract, { - body: { workspaceId: input.workspaceId ?? '', provider: input.provider }, + body: { + workspaceId: input.workspaceId ?? '', + provider: input.provider, + ...(input.credentialId ? { credentialId: input.credentialId } : {}), + }, signal, }), enabled: input.enabled && Boolean(input.workspaceId), diff --git a/apps/sim/lib/api/contracts/credentials.ts b/apps/sim/lib/api/contracts/credentials.ts index bc998acbe30..4b0ecc6146c 100644 --- a/apps/sim/lib/api/contracts/credentials.ts +++ b/apps/sim/lib/api/contracts/credentials.ts @@ -3,7 +3,7 @@ import { organizationIdSchema, workspaceIdSchema } from '@/lib/api/contracts/pri import { defineRouteContract } from '@/lib/api/contracts/types' import { ATLASSIAN_PRODUCTS, - getServiceAccountRequiredFields, + getMissingServiceAccountFields, } from '@/lib/credentials/service-account-fields' import { WORKLOAD_IDENTITY_PROVIDERS } from '@/lib/credentials/workload-identity/audiences' import type { OAuthProvider } from '@/lib/oauth/types' @@ -237,14 +237,12 @@ export function refineCredentialCreate( } if (data.type === 'service_account') { - for (const field of getServiceAccountRequiredFields(data.providerId)) { - if (!data[field]) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: `${field} is required for ${data.providerId ?? 'service account'} credentials`, - path: [field], - }) - } + for (const field of getMissingServiceAccountFields(data.providerId, data)) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: `${field} is required for ${data.providerId ?? 'service account'} credentials`, + path: [field], + }) } return } @@ -563,6 +561,8 @@ export const prepareWorkloadIdentityContract = defineRouteContract({ body: z.object({ workspaceId: workspaceIdSchema, provider: z.enum(WORKLOAD_IDENTITY_PROVIDERS), + /** The credential being reconnected, so the dialog opens on its current mode. */ + credentialId: z.string().min(1).max(255).optional(), }), response: { mode: 'json', @@ -573,13 +573,18 @@ export const prepareWorkloadIdentityContract = defineRouteContract({ available: z.literal(true), /** Register this URL as the OpenID Connect issuer the cloud trusts. */ issuer: z.string(), - /** The `aud` the cloud must accept (AWS client ID, Databricks policy audience). */ - audience: z.string(), + /** + * The `aud` the cloud must accept (AWS client ID, Databricks policy audience). Absent for + * Google, whose audience is each credential's own workload identity provider. + */ + audience: z.string().optional(), /** The exact `sub` the role's trust policy must allow. */ subject: z.string(), /** Opaque proof submitted with the credential; binds the subject to its creator. */ subjectProof: z.string(), expiresAt: z.string(), + /** The reconnected credential is keyless (Snowflake, Microsoft app, and Google only). */ + reconnectsKeyless: z.literal(true).optional(), }), ]), }, diff --git a/apps/sim/lib/api/contracts/oauth-connections.ts b/apps/sim/lib/api/contracts/oauth-connections.ts index 5e7e7df6680..25af9d40e45 100644 --- a/apps/sim/lib/api/contracts/oauth-connections.ts +++ b/apps/sim/lib/api/contracts/oauth-connections.ts @@ -123,7 +123,7 @@ const oauthTokenResponseSchema = z.object({ providerWorkspaceId: z.string().optional(), realmId: z.string().optional(), quickBooksEnvironment: z.enum(['sandbox', 'production']).optional(), - authStyle: z.enum(['x-api-token']).optional(), + authStyle: z.enum(['x-api-token', 'snowflake-workload-identity']).optional(), }) /** Token material a resolved credential yields, on the wire and in-process alike. */ diff --git a/apps/sim/lib/api/contracts/v2/credentials.ts b/apps/sim/lib/api/contracts/v2/credentials.ts index b5be8e98215..5a679ceb00e 100644 --- a/apps/sim/lib/api/contracts/v2/credentials.ts +++ b/apps/sim/lib/api/contracts/v2/credentials.ts @@ -20,7 +20,7 @@ import { v2TimestampSchema, } from '@/lib/api/contracts/v2/shared' import { - getServiceAccountRequiredFields, + getMissingServiceAccountFields, SERVICE_ACCOUNT_REQUIRED_FIELDS, } from '@/lib/credentials/service-account-fields' import { SLACK_CUSTOM_BOT_PROVIDER_ID } from '@/lib/oauth/types' @@ -597,14 +597,12 @@ export const v2CreateServiceAccountCredentialBodySchema = z }) return } - for (const field of getServiceAccountRequiredFields(body.providerId)) { - if (!body.credentials[field]) { - ctx.addIssue({ - code: 'custom', - path: ['credentials', field], - message: `${field} is required for ${body.providerId} credentials`, - }) - } + for (const field of getMissingServiceAccountFields(body.providerId, body.credentials)) { + ctx.addIssue({ + code: 'custom', + path: ['credentials', field], + message: `${field} is required for ${body.providerId} credentials`, + }) } }) export type V2CreateServiceAccountCredentialBody = z.input< diff --git a/apps/sim/lib/block-metadata/names.generated.ts b/apps/sim/lib/block-metadata/names.generated.ts index f7c44c38f7e..4eec2893e1f 100644 --- a/apps/sim/lib/block-metadata/names.generated.ts +++ b/apps/sim/lib/block-metadata/names.generated.ts @@ -95,7 +95,7 @@ export const BLOCK_NAMES: Readonly> = { gamma_v2: 'Gamma', gauge: 'Gauge', generic_webhook: 'Webhook Trigger', - github_v2: 'GitHub', + github_v3: 'GitHub', gitlab_v2: 'GitLab', gmail_v2: 'Gmail', gong: 'Gong', diff --git a/apps/sim/lib/credentials/application/organization-credentials.ts b/apps/sim/lib/credentials/application/organization-credentials.ts index 5fe2bb1282a..f56f6c8cb13 100644 --- a/apps/sim/lib/credentials/application/organization-credentials.ts +++ b/apps/sim/lib/credentials/application/organization-credentials.ts @@ -392,7 +392,10 @@ export async function authorizeOrganizationCredentialUse(input: { } export async function resolveOrganizationCredentialTokenBundle( - input: Parameters[0] + input: Parameters[0] & { + /** The service the token is for, from the caller's server-side definition. */ + service?: string + } ): Promise { const { credential: row, userId } = await authorizeOrganizationCredentialUse(input) if (row.type === 'managed_oauth') { @@ -409,7 +412,7 @@ export async function resolveOrganizationCredentialTokenBundle( input.requestId, input.requiredScopes, input.impersonateEmail, - { privacyMode: 'selector' } + { privacyMode: 'selector', service: input.service } ) } diff --git a/apps/sim/lib/credentials/application/prepare-workload-identity.test.ts b/apps/sim/lib/credentials/application/prepare-workload-identity.test.ts new file mode 100644 index 00000000000..88b929c3b9c --- /dev/null +++ b/apps/sim/lib/credentials/application/prepare-workload-identity.test.ts @@ -0,0 +1,200 @@ +/** + * @vitest-environment node + */ +import { generateKeyPairSync } from 'node:crypto' +import { createSessionPrincipal } from '@sim/testing/factories/principal.factory' +import { + credentialsAccessMock, + credentialsAccessMockFns, +} from '@sim/testing/mocks/credentials-access.mock' +import { encryptionMock, encryptionMockFns } from '@sim/testing/mocks/encryption.mock' +import { workspaceAuthzMock, workspaceAuthzMockFns } from '@sim/testing/mocks/workspace-authz.mock' +import { + workspaceContextMock, + workspaceContextMockFns, +} from '@sim/testing/mocks/workspace-context.mock' +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@/lib/workspaces/application/context', () => workspaceContextMock) +vi.mock('@sim/platform-authz/workspace', () => workspaceAuthzMock) +vi.mock('@/lib/core/security/encryption', () => encryptionMock) +vi.mock('@/lib/credentials/access', () => credentialsAccessMock) + +import { env } from '@/lib/core/config/env' +import { prepareWorkloadIdentity } from '@/lib/credentials/application/prepare-workload-identity' + +const principal = createSessionPrincipal() +const keylessSecret = { + type: 'snowflake_workload_identity_v1', + config: { + authType: 'workload_identity', + host: 'myorg-myaccount.snowflakecomputing.com', + subject: 'sim:workspace:workspace-1:credential:abcdef0123456789', + }, +} +const tokenSecret = { + type: 'token_service_account', + providerId: 'snowflake-service-account', + apiToken: 'pat-secret', + domain: 'myorg-myaccount.snowflakecomputing.com', +} + +/** The credential being reconnected, as the caller's access to it resolves. */ +function reconnecting( + secret: object, + access: { isAdmin?: boolean; workspaceId?: string; providerId?: string } = {} +) { + credentialsAccessMockFns.mockGetCredentialActorContext.mockResolvedValue({ + credential: { + workspaceId: access.workspaceId ?? 'workspace-1', + type: 'service_account', + providerId: access.providerId ?? 'snowflake-service-account', + encryptedServiceAccountKey: 'ciphertext', + }, + member: null, + hasWorkspaceAccess: true, + canWriteWorkspace: true, + isAdmin: access.isAdmin ?? true, + }) + encryptionMockFns.mockDecryptSecret.mockResolvedValue({ decrypted: JSON.stringify(secret) }) +} + +function prepare(provider: 'snowflake' | 'google' | 'microsoft' = 'snowflake') { + return prepareWorkloadIdentity.execute({ + principal, + input: { workspaceId: 'workspace-1', provider, credentialId: 'cred-1' }, + }) +} + +beforeAll(() => { + Reflect.set( + env, + 'WORKLOAD_IDENTITY_SIGNING_KEY', + generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey.export({ + type: 'pkcs8', + format: 'pem', + }) + ) + Reflect.set(env, 'WORKLOAD_IDENTITY_ISSUER', 'https://sim.example.com/oidc/workload') +}) + +afterAll(() => { + Reflect.set(env, 'WORKLOAD_IDENTITY_SIGNING_KEY', undefined) + Reflect.set(env, 'WORKLOAD_IDENTITY_ISSUER', undefined) +}) + +describe('preparing a Snowflake reconnect', () => { + beforeEach(() => { + workspaceContextMockFns.mockLoadActiveWorkspaceApplicationContext.mockResolvedValue({ + workspaceId: 'workspace-1', + workspaceOrganizationId: null, + allowPersonalApiKeys: true, + billedAccountUserId: 'user-1', + }) + workspaceAuthzMockFns.mockResolveEffectiveWorkspacePermission.mockResolvedValue('write') + }) + + it('opens a keyless credential on keyless', async () => { + reconnecting(keylessSecret) + await expect(prepare()).resolves.toMatchObject({ reconnectsKeyless: true }) + }) + + it('opens a token credential on the token', async () => { + reconnecting(tokenSecret) + expect(await prepare()).not.toHaveProperty('reconnectsKeyless') + }) + + it('reveals nothing about a credential the caller does not administer', async () => { + reconnecting(keylessSecret, { isAdmin: false }) + expect(await prepare()).not.toHaveProperty('reconnectsKeyless') + expect(encryptionMockFns.mockDecryptSecret).not.toHaveBeenCalled() + }) + + it('reveals nothing about a credential from another workspace', async () => { + reconnecting(keylessSecret, { workspaceId: 'workspace-2' }) + expect(await prepare()).not.toHaveProperty('reconnectsKeyless') + expect(encryptionMockFns.mockDecryptSecret).not.toHaveBeenCalled() + }) +}) + +describe('preparing a Google service account reconnect', () => { + const google = { providerId: 'google-service-account' } + + beforeEach(() => { + workspaceContextMockFns.mockLoadActiveWorkspaceApplicationContext.mockResolvedValue({ + workspaceId: 'workspace-1', + workspaceOrganizationId: null, + allowPersonalApiKeys: true, + billedAccountUserId: 'user-1', + }) + workspaceAuthzMockFns.mockResolveEffectiveWorkspacePermission.mockResolvedValue('write') + }) + + it('opens a keyless credential on keyless, with no fixed audience', async () => { + reconnecting( + { + type: 'google_workload_identity_v1', + config: { subject: 'sim:workspace:workspace-1:credential:abcdef0123456789' }, + }, + google + ) + const result = await prepare('google') + expect(result).toMatchObject({ available: true, reconnectsKeyless: true }) + expect(result).not.toHaveProperty('audience') + }) + + it('opens a JSON key credential on the key', async () => { + reconnecting({ type: 'service_account', client_email: 'sa@p.iam.gserviceaccount.com' }, google) + expect(await prepare('google')).not.toHaveProperty('reconnectsKeyless') + }) + + it('does not read a Snowflake credential as a Google one', async () => { + reconnecting(keylessSecret) + expect(await prepare('google')).not.toHaveProperty('reconnectsKeyless') + expect(encryptionMockFns.mockDecryptSecret).not.toHaveBeenCalled() + }) +}) + +describe('preparing a Microsoft app credential reconnect', () => { + const microsoft = { providerId: 'microsoft-app-service-account' } + const appConfig = { + tenantId: '11111111-2222-3333-4444-555555555555', + clientId: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee', + } + + beforeEach(() => { + workspaceContextMockFns.mockLoadActiveWorkspaceApplicationContext.mockResolvedValue({ + workspaceId: 'workspace-1', + workspaceOrganizationId: null, + allowPersonalApiKeys: true, + billedAccountUserId: 'user-1', + }) + workspaceAuthzMockFns.mockResolveEffectiveWorkspacePermission.mockResolvedValue('write') + }) + + it('opens a federated credential on keyless', async () => { + reconnecting( + { + type: 'microsoft_app_credential_v1', + config: { + ...appConfig, + authType: 'federated', + subject: 'sim:workspace:workspace-1:credential:abcdef0123456789', + }, + }, + microsoft + ) + await expect(prepare('microsoft')).resolves.toMatchObject({ reconnectsKeyless: true }) + }) + + it.each([ + { authType: 'client_secret', clientSecret: 'value' }, + { authType: 'certificate', privateKey: 'key', certificate: 'cert' }, + ])('opens a $authType credential on its keyed mode', async (mode) => { + reconnecting( + { type: 'microsoft_app_credential_v1', config: { ...appConfig, ...mode } }, + microsoft + ) + expect(await prepare('microsoft')).not.toHaveProperty('reconnectsKeyless') + }) +}) diff --git a/apps/sim/lib/credentials/application/prepare-workload-identity.ts b/apps/sim/lib/credentials/application/prepare-workload-identity.ts index 4624723801d..e42b5dea9f0 100644 --- a/apps/sim/lib/credentials/application/prepare-workload-identity.ts +++ b/apps/sim/lib/credentials/application/prepare-workload-identity.ts @@ -1,9 +1,15 @@ import { requirePrincipalSubjectUserId } from '@sim/auth/principal' import { defineAuthorizedWorkspaceUseCase } from '@/lib/core/application' import { OrchestrationError } from '@/lib/core/orchestration/types' +import { decryptSecret } from '@/lib/core/security/encryption' +import { getCredentialActorContext } from '@/lib/credentials/access' import { credentialOperations } from '@/lib/credentials/application/operations' +import { isGoogleWorkloadIdentitySecret } from '@/lib/credentials/google-workload-identity' +import { isKeylessMicrosoftAppSecret } from '@/lib/credentials/microsoft-app-service-account.server' +import { isKeylessSnowflakeSecret } from '@/lib/credentials/snowflake-service-account.server' +import { SNOWFLAKE_SERVICE_ACCOUNT_PROVIDER_ID } from '@/lib/credentials/token-service-accounts/descriptors' import { - WORKLOAD_IDENTITY_AUDIENCES, + fixedWorkloadIdentityAudience, type WorkloadIdentityProvider, } from '@/lib/credentials/workload-identity/audiences' import { @@ -11,11 +17,17 @@ import { isWorkloadIdentityConfigured, } from '@/lib/credentials/workload-identity/issuer' import { issueWorkloadIdentitySubject } from '@/lib/credentials/workload-identity/subject' +import { + GOOGLE_SERVICE_ACCOUNT_PROVIDER_ID, + MICROSOFT_APP_SERVICE_ACCOUNT_PROVIDER_ID, +} from '@/lib/oauth/types' import { loadActiveWorkspaceApplicationContext } from '@/lib/workspaces/application/context' export interface PrepareWorkloadIdentityInput { workspaceId: string provider: WorkloadIdentityProvider + /** The credential being reconnected, so the dialog can open on its current mode. */ + credentialId?: string } export type PrepareWorkloadIdentityResult = @@ -23,16 +35,69 @@ export type PrepareWorkloadIdentityResult = | { available: true issuer: string - audience: string + /** Absent for Google, whose audience is each credential's own workload identity provider. */ + audience?: string subject: string subjectProof: string expiresAt: string + /** The reconnected credential is keyless; absent when there is none or it is not. */ + reconnectsKeyless?: true } +/** Providers whose credentials can be keyless or key-based under one provider ID. */ +const MIXED_MODE_PROVIDERS: Partial< + Record< + WorkloadIdentityProvider, + { providerId: string; isKeyless: (decrypted: string) => boolean } + > +> = { + snowflake: { + providerId: SNOWFLAKE_SERVICE_ACCOUNT_PROVIDER_ID, + isKeyless: isKeylessSnowflakeSecret, + }, + microsoft: { + providerId: MICROSOFT_APP_SERVICE_ACCOUNT_PROVIDER_ID, + isKeyless: isKeylessMicrosoftAppSecret, + }, + google: { + providerId: GOOGLE_SERVICE_ACCOUNT_PROVIDER_ID, + isKeyless: isGoogleWorkloadIdentitySecret, + }, +} + +/** + * Whether a Snowflake, Microsoft app, or Google credential in this workspace, which this person + * administers, is keyless. Only that one bit leaves the stored secret, and only + * for someone allowed to reconnect the credential. + */ +async function isKeylessCredential( + provider: WorkloadIdentityProvider, + credentialId: string, + workspaceId: string, + userId: string +): Promise { + const mixedMode = MIXED_MODE_PROVIDERS[provider] + const access = await getCredentialActorContext(credentialId, userId, { workspaceId }) + const row = access.credential + if ( + !access.isAdmin || + !row || + row.workspaceId !== workspaceId || + row.type !== 'service_account' || + !mixedMode || + row.providerId !== mixedMode.providerId || + !row.encryptedServiceAccountKey + ) { + return false + } + const { decrypted } = await decryptSecret(row.encryptedServiceAccountKey) + return mixedMode.isKeyless(decrypted) +} + /** - * Starts a keyless cloud connection (an AWS role or a Databricks service - * principal): the subject the customer's trust configuration will pin, signed - * for this person and workspace so only they can attach it to the credential + * Starts a keyless cloud connection (an AWS role, a Databricks service + * principal, a Snowflake service user, a Microsoft app, or a Google service account): the subject the customer's trust + * configuration will pin, signed for this person and workspace so only they can attach it to the credential * they are about to create. Reports `available: false` when this deployment * cannot sign tokens, so the connect dialog offers only key-based modes. */ @@ -47,16 +112,23 @@ export const prepareWorkloadIdentity = defineAuthorizedWorkspaceUseCase({ execute: async ({ principal, input }): Promise => { // A deployment without a signing key offers only key- and secret-based credentials. if (!(await isWorkloadIdentityConfigured())) return { available: false } + const userId = requirePrincipalSubjectUserId(principal) const grant = issueWorkloadIdentitySubject( input.provider, { workspaceId: input.workspaceId }, - requirePrincipalSubjectUserId(principal) + userId ) + const reconnectsKeyless = + MIXED_MODE_PROVIDERS[input.provider] && input.credentialId + ? await isKeylessCredential(input.provider, input.credentialId, input.workspaceId, userId) + : false + const audience = fixedWorkloadIdentityAudience(input.provider) return { available: true, issuer: getWorkloadIdentityIssuer(), - audience: WORKLOAD_IDENTITY_AUDIENCES[input.provider], + ...(audience ? { audience } : {}), ...grant, + ...(reconnectsKeyless ? { reconnectsKeyless: true as const } : {}), } }, }) diff --git a/apps/sim/lib/credentials/application/provider-catalog.ts b/apps/sim/lib/credentials/application/provider-catalog.ts index 5ae98321d89..3b21c793b67 100644 --- a/apps/sim/lib/credentials/application/provider-catalog.ts +++ b/apps/sim/lib/credentials/application/provider-catalog.ts @@ -21,6 +21,7 @@ import { AWS_SERVICE_ACCOUNT_PROVIDER_ID, DATABRICKS_SERVICE_ACCOUNT_PROVIDER_ID, GOOGLE_SERVICE_ACCOUNT_PROVIDER_ID, + MICROSOFT_APP_SERVICE_ACCOUNT_PROVIDER_ID, type OAuthServiceMetadata, OCI_API_KEY_SERVICE_ACCOUNT_PROVIDER_ID, ORACLE_DATABASE_SERVICE_ACCOUNT_PROVIDER_ID, @@ -150,6 +151,26 @@ function getServiceAccountDescriptor(providerId: string): ServiceAccountDescript ], } } + if (providerId === MICROSOFT_APP_SERVICE_ACCOUNT_PROVIDER_ID) { + return { + name: 'Microsoft app credential', + description: + 'Use Microsoft Entra ID, SharePoint, Dataverse, and Dynamics 365 as an app registration (app-only), with a client secret, a certificate, or a keyless federated credential that trusts Sim.', + docsUrl: 'https://docs.sim.ai/integrations/microsoft-app-credentials', + fields: [ + { + id: 'serviceAccountJson', + label: 'Credential configuration', + placeholder: + '{"authType":"client_secret","tenantId":"...","clientId":"...","clientSecret":"..."}', + required: true, + secret: true, + multiline: true, + hint: 'JSON object with tenantId, clientId, optional environmentUrl (Dataverse and Dynamics 365), and authType: "client_secret" (clientSecret) or "certificate" (privateKey, certificate as PEM). Keyless "federated" credentials are created from the Microsoft connect dialog, which issues the trusted subject.', + }, + ], + } + } if (providerId === AWS_SERVICE_ACCOUNT_PROVIDER_ID) { return { name: 'AWS credential', diff --git a/apps/sim/lib/credentials/client-credential-accounts/descriptors.ts b/apps/sim/lib/credentials/client-credential-accounts/descriptors.ts index e57ce214e28..a9d365612cd 100644 --- a/apps/sim/lib/credentials/client-credential-accounts/descriptors.ts +++ b/apps/sim/lib/credentials/client-credential-accounts/descriptors.ts @@ -105,6 +105,16 @@ export interface ClientCredentialAccountDescriptor { defaultAuthMethod?: string /** Sim setup guide, docked bottom-left of the connect modal. */ docsUrl: string + /** + * Builds the provider's one-time consent URL from the values in the connect + * modal, for providers whose grant fails with `consent_required` until a user + * approves the app (DocuSign JWT Grant). `redirectUri` is the Sim origin the + * modal is open on. Returns `undefined` when the values can't form one. + */ + consentUrl?: ( + values: Partial>, + redirectUri: string + ) => string | undefined /** * Optional one-line caveat, rendered under the `orgId` field of the connect modal. A descriptor * without an `orgId` field puts its guidance in a field `hint` instead. @@ -125,6 +135,7 @@ export const ORACLE_FUSION_SERVICE_ACCOUNT_PROVIDER_ID = 'oracle-fusion-service- export const GREENHOUSE_SERVICE_ACCOUNT_PROVIDER_ID = 'greenhouse-service-account' as const export const JAMA_SERVICE_ACCOUNT_PROVIDER_ID = 'jama-service-account' as const export const HELPSCOUT_SERVICE_ACCOUNT_PROVIDER_ID = 'helpscout-service-account' as const +export const DOCUSIGN_SERVICE_ACCOUNT_PROVIDER_ID = 'docusign-service-account' as const /** Permissions requested when connecting a Manage Vanta application. */ export const VANTA_PERMISSION_OPTIONS = [ @@ -150,6 +161,7 @@ export type ClientCredentialAccountProviderId = | typeof GREENHOUSE_SERVICE_ACCOUNT_PROVIDER_ID | typeof HELPSCOUT_SERVICE_ACCOUNT_PROVIDER_ID | typeof JAMA_SERVICE_ACCOUNT_PROVIDER_ID + | typeof DOCUSIGN_SERVICE_ACCOUNT_PROVIDER_ID /** * Exact account-specific SuiteTalk origin accepted by NetSuite's OAuth and @@ -385,6 +397,63 @@ export function resolveZohoDeskDataCenter(rawDataCenter?: string): { return { id, ...ZOHO_DESK_DATA_CENTERS[id] } } +/** + * DocuSign's two account systems. Each environment has its own authentication + * service and its own eSignature REST hosts, and a token from one is never + * accepted by the other, so the credential stores which one it belongs to and + * nothing a caller types can change it. + * @see https://developers.docusign.com/platform/auth/jwt/jwt-get-token/ + */ +export const DOCUSIGN_ENVIRONMENTS = { + demo: { authHost: 'account-d.docusign.com', label: 'Developer (demo)' }, + production: { authHost: 'account.docusign.com', label: 'Production' }, +} as const satisfies Record + +export type DocuSignEnvironment = keyof typeof DOCUSIGN_ENVIRONMENTS + +/** Resolves a stored environment value, or `undefined` when it is not exactly one of the two. */ +export function resolveDocuSignEnvironment( + value: string | undefined +): DocuSignEnvironment | undefined { + const trimmed = value?.trim() + return trimmed && Object.hasOwn(DOCUSIGN_ENVIRONMENTS, trimmed) + ? (trimmed as DocuSignEnvironment) + : undefined +} + +/** DocuSign integration keys, user IDs, and account IDs are all GUIDs. */ +export const DOCUSIGN_GUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i + +/** An unencrypted PEM RSA private key, in the PKCS#1 form DocuSign generates or PKCS#8. */ +const DOCUSIGN_PRIVATE_KEY_REGEX = + /^-----BEGIN (RSA )?PRIVATE KEY-----[\s\S]+-----END (RSA )?PRIVATE KEY-----$/ + +/** Scopes a JWT Grant credential requests; `impersonation` is what JWT consent covers. */ +export const DOCUSIGN_JWT_SCOPES = 'signature impersonation' + +/** + * The one-time consent URL the impersonated user opens to let the integration + * key act as them. DocuSign requires a `redirect_uri` registered on the key; + * the JWT flow ignores the `code` it receives. + * @see https://developers.docusign.com/platform/auth/jwt/jwt-get-token/ + */ +function buildDocuSignConsentUrl( + integrationKey: string, + environment: string | undefined, + redirectUri: string +): string | undefined { + const resolved = resolveDocuSignEnvironment(environment) + const key = integrationKey.trim() + if (!resolved || !DOCUSIGN_GUID_REGEX.test(key)) return undefined + const params = new URLSearchParams({ + response_type: 'code', + scope: DOCUSIGN_JWT_SCOPES, + client_id: key, + redirect_uri: redirectUri, + }) + return `https://${DOCUSIGN_ENVIRONMENTS[resolved].authHost}/oauth/auth?${params.toString()}` +} + export const CLIENT_CREDENTIAL_ACCOUNT_DESCRIPTORS: Record< ClientCredentialAccountProviderId, ClientCredentialAccountDescriptor @@ -417,6 +486,69 @@ export const CLIENT_CREDENTIAL_ACCOUNT_DESCRIPTORS: Record< helpText: 'Create API credentials in your Jama profile. Your account needs REST API access and a Named Creator license.', }, + [DOCUSIGN_SERVICE_ACCOUNT_PROVIDER_ID]: { + providerId: DOCUSIGN_SERVICE_ACCOUNT_PROVIDER_ID, + serviceLabel: 'DocuSign', + connectNoun: 'JWT Grant app', + fields: [ + { + id: 'dataCenter', + label: 'Environment', + placeholder: 'Select an environment', + secret: false, + options: (Object.keys(DOCUSIGN_ENVIRONMENTS) as DocuSignEnvironment[]).map((id) => ({ + value: id, + label: DOCUSIGN_ENVIRONMENTS[id].label, + })), + hint: 'Where the integration key was created. Keys start in the developer environment until they go live.', + }, + { + id: 'clientId', + label: 'Integration key', + placeholder: '00000000-0000-0000-0000-000000000000', + secret: false, + hintPattern: DOCUSIGN_GUID_REGEX, + hintNormalize: (value) => value.trim(), + hintMessage: 'Expected the integration key GUID from Apps and Keys.', + }, + { + id: 'username', + label: 'Impersonated user ID', + placeholder: '00000000-0000-0000-0000-000000000000', + secret: false, + hintPattern: DOCUSIGN_GUID_REGEX, + hintNormalize: (value) => value.trim(), + hintMessage: 'Expected the User ID GUID from Apps and Keys, not an email address.', + hint: 'Every call runs as this user, with their DocuSign permissions.', + }, + { + id: 'privateKey', + label: 'RSA private key', + placeholder: '-----BEGIN RSA PRIVATE KEY-----', + secret: true, + multiline: true, + hintPattern: DOCUSIGN_PRIVATE_KEY_REGEX, + hintNormalize: (value) => value.trim(), + hintMessage: + 'Expected the full PEM private key from the RSA keypair, including its BEGIN and END lines.', + }, + { + id: 'orgId', + label: 'Account ID', + placeholder: "Defaults to the user's default account", + secret: false, + optional: true, + hintPattern: DOCUSIGN_GUID_REGEX, + hintNormalize: (value) => value.trim(), + hintMessage: 'Expected the API Account ID GUID from Apps and Keys.', + }, + ], + docsUrl: 'https://docs.sim.ai/integrations/docusign-service-account', + helpText: + "Only needed when the user belongs to more than one account and the one to use isn't their default.", + consentUrl: (values, redirectUri) => + buildDocuSignConsentUrl(values.clientId ?? '', values.dataCenter, redirectUri), + }, [RAMP_SERVICE_ACCOUNT_PROVIDER_ID]: { providerId: RAMP_SERVICE_ACCOUNT_PROVIDER_ID, serviceLabel: 'Ramp', diff --git a/apps/sim/lib/credentials/client-credential-accounts/minters/docusign.test.ts b/apps/sim/lib/credentials/client-credential-accounts/minters/docusign.test.ts new file mode 100644 index 00000000000..f77718f4dce --- /dev/null +++ b/apps/sim/lib/credentials/client-credential-accounts/minters/docusign.test.ts @@ -0,0 +1,284 @@ +import { generateKeyPairSync } from 'crypto' +import { jsonResponse } from '@sim/testing/helpers/http' +import { decodeProtectedHeader, jwtVerify } from 'jose' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { mintDocuSignServiceAccountToken } from '@/lib/credentials/client-credential-accounts/minters/docusign' + +const INTEGRATION_KEY = '11111111-2222-3333-4444-555555555555' +const USER_ID = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee' +const DEFAULT_ACCOUNT = '99999999-0000-0000-0000-000000000001' +const OTHER_ACCOUNT = '99999999-0000-0000-0000-000000000002' + +const { privateKey: RSA_PEM, publicKey: RSA_PUBLIC } = generateKeyPairSync('rsa', { + modulusLength: 2048, + privateKeyEncoding: { type: 'pkcs1', format: 'pem' }, + publicKeyEncoding: { type: 'spki', format: 'pem' }, +}) +const EC_PEM = generateKeyPairSync('ec', { + namedCurve: 'P-256', + privateKeyEncoding: { type: 'pkcs8', format: 'pem' }, + publicKeyEncoding: { type: 'spki', format: 'pem' }, +}).privateKey +const SHORT_RSA_PEM = generateKeyPairSync('rsa', { + modulusLength: 1024, + privateKeyEncoding: { type: 'pkcs1', format: 'pem' }, + publicKeyEncoding: { type: 'spki', format: 'pem' }, +}).privateKey + +const FIELDS = { + clientId: INTEGRATION_KEY, + username: USER_ID, + privateKey: RSA_PEM, + dataCenter: 'demo', + orgId: '', +} + +const ACCESS_TOKEN = 'eyJ0eXAiOiJNVCJ9.access-token-value' + +function userinfo(accounts: Array>) { + return jsonResponse({ + sub: USER_ID, + name: 'Integration User', + email: 'ops@example.com', + accounts, + }) +} + +const DEMO_ACCOUNTS = [ + { + account_id: OTHER_ACCOUNT, + is_default: false, + account_name: 'Other', + base_uri: 'https://demo.docusign.net', + }, + { + account_id: DEFAULT_ACCOUNT, + is_default: true, + account_name: 'Main', + base_uri: 'https://demo.docusign.net', + }, +] + +const mockFetch = vi.fn() + +function mockMint(accounts = DEMO_ACCOUNTS) { + mockFetch + .mockResolvedValueOnce( + jsonResponse({ access_token: ACCESS_TOKEN, token_type: 'Bearer', expires_in: 3600 }) + ) + .mockResolvedValueOnce(userinfo(accounts)) +} + +/** Every string a failure exposes: its message plus the log detail callers write to logs. */ +function exposedText(error: unknown): string { + const failure = error as { message?: string; logDetail?: unknown } + return `${failure.message} ${JSON.stringify(failure.logDetail)}` +} + +describe('mintDocuSignServiceAccountToken', () => { + beforeEach(() => { + vi.stubGlobal('fetch', mockFetch) + }) + + it('signs the documented assertion for the demo environment and binds the default account', async () => { + mockMint() + + const result = await mintDocuSignServiceAccountToken(FIELDS) + + const [tokenUrl, tokenInit] = mockFetch.mock.calls[0] + expect(tokenUrl).toBe('https://account-d.docusign.com/oauth/token') + const body = new URLSearchParams(tokenInit.body as string) + expect(body.get('grant_type')).toBe('urn:ietf:params:oauth:grant-type:jwt-bearer') + const assertion = body.get('assertion') ?? '' + expect(decodeProtectedHeader(assertion)).toMatchObject({ alg: 'RS256', typ: 'JWT' }) + const { createPublicKey } = await import('crypto') + const { payload } = await jwtVerify(assertion, createPublicKey(RSA_PUBLIC), { + issuer: INTEGRATION_KEY, + subject: USER_ID, + audience: 'account-d.docusign.com', + }) + expect(payload.scope).toBe('signature impersonation') + expect((payload.exp ?? 0) - (payload.iat ?? 0)).toBeLessThanOrEqual(3600) + + expect(mockFetch.mock.calls[1][0]).toBe('https://account-d.docusign.com/oauth/userinfo') + expect(mockFetch.mock.calls[1][1].headers.Authorization).toBe(`Bearer ${ACCESS_TOKEN}`) + expect(result).toMatchObject({ + accessToken: ACCESS_TOKEN, + expiresInSeconds: 3000, + instanceUrl: `https://demo.docusign.net/restapi/v2.1/accounts/${DEFAULT_ACCOUNT}`, + identity: { principal: { kind: 'user', id: USER_ID } }, + }) + }) + + it('mints and resolves accounts on the production host when the credential says production', async () => { + mockMint([ + { + account_id: DEFAULT_ACCOUNT, + is_default: true, + account_name: 'Production', + base_uri: 'https://na3.docusign.net', + }, + ]) + + const result = await mintDocuSignServiceAccountToken({ ...FIELDS, dataCenter: 'production' }) + + expect(mockFetch.mock.calls[0][0]).toBe('https://account.docusign.com/oauth/token') + expect(mockFetch.mock.calls[1][0]).toBe('https://account.docusign.com/oauth/userinfo') + expect(result.instanceUrl).toBe( + `https://na3.docusign.net/restapi/v2.1/accounts/${DEFAULT_ACCOUNT}` + ) + }) + + it('binds the pinned account rather than the default one', async () => { + mockMint() + + const result = await mintDocuSignServiceAccountToken({ ...FIELDS, orgId: OTHER_ACCOUNT }) + + expect(result.instanceUrl).toBe( + `https://demo.docusign.net/restapi/v2.1/accounts/${OTHER_ACCOUNT}` + ) + }) + + it('refuses a pinned account the user does not belong to', async () => { + mockMint() + + await expect( + mintDocuSignServiceAccountToken({ + ...FIELDS, + orgId: '99999999-0000-0000-0000-000000000003', + }) + ).rejects.toMatchObject({ code: 'account_not_found' }) + }) + + it.each([ + ['https://evil.example.com', 'demo'], + ['https://na3.docusign.net', 'demo'], + ['https://demo.docusign.net', 'production'], + ['http://na3.docusign.net', 'production'], + ])('never binds a %s base_uri to a %s credential', async (baseUri, environment) => { + mockMint([ + { + account_id: DEFAULT_ACCOUNT, + is_default: true, + account_name: 'Default', + base_uri: baseUri, + }, + ]) + + await expect( + mintDocuSignServiceAccountToken({ ...FIELDS, dataCenter: environment }) + ).rejects.toMatchObject({ code: 'provider_unavailable' }) + }) + + it.each([ + ['an absent environment', { dataCenter: undefined }], + ['an environment that is a host', { dataCenter: 'https://evil.example.com' }], + ['an unknown environment', { dataCenter: 'staging' }], + ['a non-GUID integration key', { clientId: 'my-app' }], + ['an email as the user ID', { username: 'ops@example.com' }], + ['a non-GUID account ID', { orgId: '12345' }], + ['a certificate instead of a key', { privateKey: RSA_PUBLIC }], + [ + 'an encrypted key', + { + privateKey: + '-----BEGIN ENCRYPTED PRIVATE KEY-----\nAAAA\n-----END ENCRYPTED PRIVATE KEY-----', + }, + ], + [ + 'an unreadable PEM', + { privateKey: '-----BEGIN RSA PRIVATE KEY-----\nAAAA\n-----END RSA PRIVATE KEY-----' }, + ], + ['a non-RSA key', { privateKey: EC_PEM }], + ])('rejects %s before any request', async (_label, overrides) => { + await expect( + mintDocuSignServiceAccountToken({ ...FIELDS, ...overrides }) + ).rejects.toMatchObject({ code: 'invalid_credentials' }) + expect(mockFetch).not.toHaveBeenCalled() + }) + + it('reports consent_required as its own code', async () => { + mockFetch.mockResolvedValueOnce(jsonResponse({ error: 'consent_required' }, 400)) + + await expect(mintDocuSignServiceAccountToken(FIELDS)).rejects.toMatchObject({ + code: 'consent_required', + }) + }) + + it.each([ + ['issuer_not_found', 'integration key not found in this environment'], + ['user_not_found', 'impersonated user ID not found in this environment'], + ['no_valid_keys_or_signatures', expect.stringContaining('private key does not match')], + ])('maps invalid_grant %s to invalid_credentials', async (description, hint) => { + mockFetch.mockResolvedValueOnce( + jsonResponse({ error: 'invalid_grant', error_description: description }, 400) + ) + + await expect(mintDocuSignServiceAccountToken(FIELDS)).rejects.toMatchObject({ + code: 'invalid_credentials', + logDetail: expect.objectContaining({ hint }), + }) + }) + + it('refuses an RSA key under 2048 bits with copy that says so, before any request', async () => { + await expect( + mintDocuSignServiceAccountToken({ ...FIELDS, privateKey: SHORT_RSA_PEM }) + ).rejects.toMatchObject({ + code: 'invalid_credentials', + logDetail: expect.objectContaining({ reason: expect.stringContaining('1024-bit') }), + }) + expect(mockFetch).not.toHaveBeenCalled() + }) + + it.each([ + [900, 360], + [300, 240], + ])( + 'reports a short %ss token so the cache reuses it before, never past, its expiry', + async (expiresIn, reported) => { + mockFetch + .mockResolvedValueOnce(jsonResponse({ access_token: ACCESS_TOKEN, expires_in: expiresIn })) + .mockResolvedValueOnce(userinfo(DEMO_ACCOUNTS)) + + const result = await mintDocuSignServiceAccountToken(FIELDS) + + expect(result.expiresInSeconds).toBe(reported) + } + ) + + it.each([429, 503])('treats a %s from the token endpoint as an outage', async (status) => { + mockFetch.mockResolvedValueOnce(jsonResponse({ error: 'busy' }, status)) + + await expect(mintDocuSignServiceAccountToken(FIELDS)).rejects.toMatchObject({ + code: 'provider_unavailable', + }) + }) + + it('keeps the key, assertion, and access token out of every failure', async () => { + const failures: unknown[] = [] + mockFetch.mockResolvedValueOnce( + jsonResponse({ error: 'invalid_grant', error_description: 'user_not_found' }, 400) + ) + failures.push(await mintDocuSignServiceAccountToken(FIELDS).catch((error) => error)) + mockFetch + .mockResolvedValueOnce(jsonResponse({ access_token: ACCESS_TOKEN, expires_in: 3600 })) + .mockResolvedValueOnce(jsonResponse({ error: 'unauthorized' }, 401)) + failures.push(await mintDocuSignServiceAccountToken(FIELDS).catch((error) => error)) + mockMint([]) + failures.push(await mintDocuSignServiceAccountToken(FIELDS).catch((error) => error)) + failures.push( + await mintDocuSignServiceAccountToken({ ...FIELDS, clientId: 'bad' }).catch((error) => error) + ) + + const assertion = new URLSearchParams(mockFetch.mock.calls[0][1].body as string).get( + 'assertion' + ) + const keyBody = RSA_PEM.split('\n')[1] + for (const failure of failures) { + const text = exposedText(failure) + expect(text).not.toContain(keyBody) + expect(text).not.toContain(ACCESS_TOKEN) + expect(text).not.toContain(String(assertion)) + } + }) +}) diff --git a/apps/sim/lib/credentials/client-credential-accounts/minters/docusign.ts b/apps/sim/lib/credentials/client-credential-accounts/minters/docusign.ts new file mode 100644 index 00000000000..2a0aee7ee39 --- /dev/null +++ b/apps/sim/lib/credentials/client-credential-accounts/minters/docusign.ts @@ -0,0 +1,360 @@ +import { createPrivateKey, type KeyObject } from 'crypto' +import { SignJWT } from 'jose' +import { + DOCUSIGN_ENVIRONMENTS, + DOCUSIGN_GUID_REGEX, + DOCUSIGN_JWT_SCOPES, + type DocuSignEnvironment, + resolveDocuSignEnvironment, +} from '@/lib/credentials/client-credential-accounts/descriptors' +import type { + ClientCredentialAccountFields, + ClientCredentialAccountMintOptions, + ClientCredentialAccountMintResult, +} from '@/lib/credentials/client-credential-accounts/server' +import { userPrincipal } from '@/lib/credentials/principal' +import { + fetchProvider, + isTransientProviderStatus, + parseProviderJson, + readProviderErrorSnippet, + TokenServiceAccountValidationError, +} from '@/lib/credentials/token-service-accounts/errors' + +const TOKEN_STEP = 'docusign_token_mint' +const USERINFO_STEP = 'docusign_userinfo' +const VALIDATION_STEP = 'docusign_field_validation' + +const JWT_BEARER_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:jwt-bearer' + +/** + * Lifetime of the signed assertion (not the access token). DocuSign defaults + * `exp` to an hour after `iat`; a short window bounds replay. + */ +const JWT_ASSERTION_LIFETIME_SECONDS = 300 + +/** + * DocuSign advises fetching a new token about 15 minutes before the old one + * expires. The resolver re-mints once less than 5 minutes remain, so reporting + * 10 minutes less than `expires_in` lands the re-mint at the advised point. + * @see https://developers.docusign.com/platform/auth/jwt/jwt-get-token/ + */ +const TOKEN_EXPIRY_MARGIN_SECONDS = 600 +const DEFAULT_TOKEN_LIFETIME_SECONDS = 3600 + +/** + * Floor for the reported lifetime when DocuSign ever returns a short + * `expires_in`: one minute above the resolver's 5-minute reuse threshold, so a + * token is reused briefly instead of re-minted on every call. Never more than + * a minute short of the real expiry. + */ +const SHORT_TOKEN_CACHE_SECONDS = 360 +const SHORT_TOKEN_EXPIRY_MARGIN_SECONDS = 60 + +/** Smallest RSA key DocuSign's RS256 signing accepts in `jose`. */ +const MIN_RSA_MODULUS_BITS = 2048 + +/** Lifetime to report to the token cache for a token that really lasts `lifetime` seconds. */ +function cacheLifetimeSeconds(lifetime: number): number { + const advised = lifetime - TOKEN_EXPIRY_MARGIN_SECONDS + const shortTokenFloor = Math.min( + lifetime - SHORT_TOKEN_EXPIRY_MARGIN_SECONDS, + SHORT_TOKEN_CACHE_SECONDS + ) + return Math.max(advised, shortTokenFloor, 0) +} + +/** + * eSignature REST hosts per environment. Demo accounts live only on + * `demo.docusign.net`; production accounts on a regional `*.docusign.net` + * host (`na3`, `eu`, …). A `base_uri` outside its environment's shape is never + * trusted with the token. + */ +const DEMO_BASE_URI_HOST = 'demo.docusign.net' +const PRODUCTION_BASE_URI_HOST_REGEX = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.docusign\.net$/ + +interface DocuSignTokenResponse { + access_token?: string + expires_in?: number +} + +interface DocuSignUserinfoAccount { + account_id?: unknown + is_default?: unknown + account_name?: unknown + base_uri?: unknown +} + +interface DocuSignUserinfoResponse { + sub?: unknown + name?: unknown + email?: unknown + accounts?: unknown +} + +function invalid(reason: string, step = VALIDATION_STEP): TokenServiceAccountValidationError { + return new TokenServiceAccountValidationError('invalid_credentials', 400, { step, reason }) +} + +/** + * Loads the pasted RSA key. DocuSign generates PKCS#1 (`BEGIN RSA PRIVATE + * KEY`); PKCS#8 is accepted too. Encrypted keys and certificates fail to load + * (Sim collects no passphrase). Keys under 2048 bits are refused because + * `jose` will not sign RS256 with them, and keys past 4096 bits because signing + * cost grows sharply with modulus size. + */ +function loadDocuSignPrivateKey(privateKeyPem: string): KeyObject { + let key: KeyObject + try { + key = createPrivateKey(privateKeyPem) + } catch { + throw invalid('private key is not a readable PEM key') + } + if (key.asymmetricKeyType !== 'rsa') { + throw invalid('DocuSign signs assertions with RS256, which needs an RSA key') + } + const modulusLength = key.asymmetricKeyDetails?.modulusLength ?? 0 + if (modulusLength < MIN_RSA_MODULUS_BITS) { + throw invalid( + `RSA key is ${modulusLength}-bit; generate a 2048-bit keypair on the integration key` + ) + } + if (modulusLength > 4096) { + throw invalid('RSA key is larger than 4096 bits') + } + return key +} + +interface ValidatedDocuSignFields { + environment: DocuSignEnvironment + integrationKey: string + userId: string + accountId?: string + key: KeyObject +} + +/** Rejects malformed input before anything is signed or sent. */ +function validateDocuSignFields(fields: ClientCredentialAccountFields): ValidatedDocuSignFields { + const environment = resolveDocuSignEnvironment(fields.dataCenter) + if (!environment) throw invalid('environment must be demo or production') + const integrationKey = fields.clientId.trim() + if (!DOCUSIGN_GUID_REGEX.test(integrationKey)) throw invalid('integration key is not a GUID') + const userId = fields.username?.trim() ?? '' + if (!DOCUSIGN_GUID_REGEX.test(userId)) throw invalid('impersonated user ID is not a GUID') + const accountId = fields.orgId.trim() || undefined + if (accountId && !DOCUSIGN_GUID_REGEX.test(accountId)) throw invalid('account ID is not a GUID') + const key = loadDocuSignPrivateKey(fields.privateKey?.trim() ?? '') + return { environment, integrationKey, userId, accountId, key } +} + +/** + * Maps a JWT Grant token error to an operator-facing hint for server logs. + * DocuSign reports every failure as HTTP 400 `{ error, error_description }`. + */ +function docuSignErrorHint(error: string, description: string): string | undefined { + if (error === 'consent_required') { + return 'the impersonated user has not granted (or revoked) consent for this integration key' + } + switch (description) { + case 'issuer_not_found': + return 'integration key not found in this environment' + case 'user_not_found': + return 'impersonated user ID not found in this environment' + case 'no_valid_keys_or_signatures': + return 'private key does not match an RSA keypair on this integration key, or the clock is skewed' + default: + return undefined + } +} + +function parseErrorBody(body: string): { error: string; description: string } { + try { + const parsed = JSON.parse(body) as { error?: unknown; error_description?: unknown } + return { + error: typeof parsed.error === 'string' ? parsed.error : '', + description: typeof parsed.error_description === 'string' ? parsed.error_description : '', + } + } catch { + return { error: '', description: '' } + } +} + +/** + * The eSignature REST base for one account, or `undefined` when its + * `base_uri` is not an https host of the credential's environment. + */ +function accountApiBase( + account: DocuSignUserinfoAccount, + environment: DocuSignEnvironment +): string | undefined { + if (typeof account.base_uri !== 'string' || typeof account.account_id !== 'string') return + if (!DOCUSIGN_GUID_REGEX.test(account.account_id)) return + let url: URL + try { + url = new URL(account.base_uri) + } catch { + return + } + if (url.protocol !== 'https:' || url.port || url.username || url.password) return + const host = url.hostname.toLowerCase() + const allowed = + environment === 'demo' + ? host === DEMO_BASE_URI_HOST + : host !== DEMO_BASE_URI_HOST && PRODUCTION_BASE_URI_HOST_REGEX.test(host) + if (!allowed) return + return `https://${host}/restapi/v2.1/accounts/${account.account_id.toLowerCase()}` +} + +/** + * Mints a DocuSign access token with the JWT Grant: an RS256 assertion + * (`iss` = integration key, `sub` = impersonated user, `aud` = the + * environment's authentication host, scope `signature impersonation`) posted + * to `https://{aud}/oauth/token`. Tokens last an hour and carry no refresh + * token, so they are re-minted. + * + * Every mint also reads `/oauth/userinfo` to pick the account (the pinned + * Account ID, else the user's default) and returns its eSignature REST base as + * `instanceUrl`, so tools never resolve the account against the deployment's + * OAuth host. DocuSign rate-limits userinfo per user per hour; one call per + * mint stays well inside it. + * + * Both hosts come only from the stored environment, never from input. + * @see https://developers.docusign.com/platform/auth/jwt/jwt-get-token/ + * @see https://developers.docusign.com/platform/auth/reference/user-info/ + */ +export async function mintDocuSignServiceAccountToken( + fields: ClientCredentialAccountFields, + options?: ClientCredentialAccountMintOptions +): Promise { + const { environment, integrationKey, userId, accountId, key } = validateDocuSignFields(fields) + const authHost = DOCUSIGN_ENVIRONMENTS[environment].authHost + + const now = Math.floor(Date.now() / 1000) + const assertion = await new SignJWT({ scope: DOCUSIGN_JWT_SCOPES }) + .setProtectedHeader({ alg: 'RS256', typ: 'JWT' }) + .setIssuer(integrationKey) + .setSubject(userId) + // DocuSign: "Do not include https:// in the aud value!" + .setAudience(authHost) + .setIssuedAt(now) + .setExpirationTime(now + JWT_ASSERTION_LIFETIME_SECONDS) + .sign(key) + + const tokenRes = await fetchProvider( + `https://${authHost}/oauth/token`, + { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ grant_type: JWT_BEARER_GRANT_TYPE, assertion }).toString(), + signal: options?.signal, + }, + TOKEN_STEP + ) + + if (!tokenRes.ok) { + const body = await readProviderErrorSnippet(tokenRes) + if ( + tokenRes.status >= 400 && + tokenRes.status < 500 && + !isTransientProviderStatus(tokenRes.status) + ) { + const { error, description } = parseErrorBody(body) + const hint = docuSignErrorHint(error, description) + throw new TokenServiceAccountValidationError( + error === 'consent_required' ? 'consent_required' : 'invalid_credentials', + tokenRes.status, + { step: TOKEN_STEP, environment, body, ...(hint ? { hint } : {}) } + ) + } + throw new TokenServiceAccountValidationError('provider_unavailable', tokenRes.status, { + step: TOKEN_STEP, + environment, + body, + }) + } + + const payload = await parseProviderJson(tokenRes, TOKEN_STEP) + if (typeof payload.access_token !== 'string' || !payload.access_token) { + throw new TokenServiceAccountValidationError('provider_unavailable', 502, { + step: TOKEN_STEP, + reason: 'token response missing access_token', + }) + } + const accessToken = payload.access_token + const lifetime = + typeof payload.expires_in === 'number' && payload.expires_in > 0 + ? payload.expires_in + : DEFAULT_TOKEN_LIFETIME_SECONDS + const expiresInSeconds = cacheLifetimeSeconds(lifetime) + + const userinfoRes = await fetchProvider( + `https://${authHost}/oauth/userinfo`, + { + headers: { Authorization: `Bearer ${accessToken}`, Accept: 'application/json' }, + signal: options?.signal, + }, + USERINFO_STEP + ) + if (!userinfoRes.ok) { + const body = await readProviderErrorSnippet(userinfoRes) + throw new TokenServiceAccountValidationError('provider_unavailable', userinfoRes.status, { + step: USERINFO_STEP, + environment, + body, + }) + } + const userinfo = await parseProviderJson(userinfoRes, USERINFO_STEP) + const accounts = (Array.isArray(userinfo.accounts) ? userinfo.accounts : []).filter( + (account): account is DocuSignUserinfoAccount => Boolean(account) && typeof account === 'object' + ) + const account = accountId + ? accounts.find( + (candidate) => + typeof candidate.account_id === 'string' && + candidate.account_id.toLowerCase() === accountId.toLowerCase() + ) + : (accounts.find((candidate) => candidate.is_default === true) ?? accounts[0]) + if (!account) { + throw new TokenServiceAccountValidationError('account_not_found', 400, { + step: USERINFO_STEP, + environment, + reason: accountId + ? 'the impersonated user is not a member of the pinned account' + : 'the impersonated user has no DocuSign accounts', + }) + } + const instanceUrl = accountApiBase(account, environment) + if (!instanceUrl) { + throw new TokenServiceAccountValidationError('provider_unavailable', 502, { + step: USERINFO_STEP, + environment, + reason: 'account base_uri is not an eSignature host of this environment', + }) + } + + if (options?.skipIdentity) { + return { accessToken, expiresInSeconds, instanceUrl } + } + + const resolvedAccountId = String(account.account_id).toLowerCase() + const accountName = + typeof account.account_name === 'string' && account.account_name + ? account.account_name + : undefined + const userName = typeof userinfo.name === 'string' && userinfo.name ? userinfo.name : undefined + const email = typeof userinfo.email === 'string' && userinfo.email ? userinfo.email : undefined + const sub = typeof userinfo.sub === 'string' && userinfo.sub ? userinfo.sub : userId + return { + accessToken, + expiresInSeconds, + instanceUrl, + identity: { + displayName: + [userName ?? email, accountName].filter(Boolean).join(' · ') || + `DocuSign ${resolvedAccountId}`, + principal: userPrincipal(sub, email), + auditMetadata: { docusignAccountId: resolvedAccountId, docusignEnvironment: environment }, + storedMetadata: { accountId: resolvedAccountId, environment, apiBase: instanceUrl }, + }, + } +} diff --git a/apps/sim/lib/credentials/client-credential-accounts/server.ts b/apps/sim/lib/credentials/client-credential-accounts/server.ts index c4bba3af9d1..ae13062cac4 100644 --- a/apps/sim/lib/credentials/client-credential-accounts/server.ts +++ b/apps/sim/lib/credentials/client-credential-accounts/server.ts @@ -2,6 +2,7 @@ import { BOX_SERVICE_ACCOUNT_PROVIDER_ID, CLIENT_CREDENTIAL_ACCOUNT_SECRET_TYPE, type ClientCredentialAccountProviderId, + DOCUSIGN_SERVICE_ACCOUNT_PROVIDER_ID, FIVETRAN_SERVICE_ACCOUNT_PROVIDER_ID, GREENHOUSE_SERVICE_ACCOUNT_PROVIDER_ID, getClientCredentialAccountDescriptor, @@ -19,6 +20,7 @@ import { ZOOM_SERVICE_ACCOUNT_PROVIDER_ID, } from '@/lib/credentials/client-credential-accounts/descriptors' import { mintBoxServiceAccountToken } from '@/lib/credentials/client-credential-accounts/minters/box' +import { mintDocuSignServiceAccountToken } from '@/lib/credentials/client-credential-accounts/minters/docusign' import { mintFivetranServiceAccountToken } from '@/lib/credentials/client-credential-accounts/minters/fivetran' import { mintGreenhouseServiceAccountToken } from '@/lib/credentials/client-credential-accounts/minters/greenhouse' import { mintHelpScoutServiceAccountToken } from '@/lib/credentials/client-credential-accounts/minters/helpscout' @@ -69,7 +71,7 @@ export interface ClientCredentialAccountFields { * {@link clientSecret} in practice. */ privateKey?: string - /** Username a key-based grant authenticates as (Salesforce JWT `sub`). */ + /** User a key-based grant authenticates as (Salesforce JWT username, DocuSign user ID). */ username?: string } @@ -102,7 +104,8 @@ export interface ClientCredentialAccountMintResult { expiresInSeconds: number /** * Provider API destination the minted token must be used against (Salesforce, - * NetSuite, or Oracle EPM), forwarded to tools alongside the token. + * NetSuite, Oracle EPM, or the DocuSign account's eSignature REST base), + * forwarded to tools alongside the token. */ instanceUrl?: string /** @@ -157,6 +160,7 @@ const CLIENT_CREDENTIAL_ACCOUNT_MINTERS: Record< [ORACLE_EPM_SERVICE_ACCOUNT_PROVIDER_ID]: mintOracleEpmServiceAccountToken, [GREENHOUSE_SERVICE_ACCOUNT_PROVIDER_ID]: mintGreenhouseServiceAccountToken, [HELPSCOUT_SERVICE_ACCOUNT_PROVIDER_ID]: mintHelpScoutServiceAccountToken, + [DOCUSIGN_SERVICE_ACCOUNT_PROVIDER_ID]: mintDocuSignServiceAccountToken, } export function getClientCredentialAccountMinter( diff --git a/apps/sim/lib/credentials/google-workload-identity.server.test.ts b/apps/sim/lib/credentials/google-workload-identity.server.test.ts new file mode 100644 index 00000000000..88f8b8d8ca4 --- /dev/null +++ b/apps/sim/lib/credentials/google-workload-identity.server.test.ts @@ -0,0 +1,403 @@ +/** + * @vitest-environment node + */ + +import { jsonResponse } from '@sim/testing/helpers/http' +import { encryptionMock, encryptionMockFns } from '@sim/testing/mocks/encryption.mock' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { workloadIdentityConfigured } = vi.hoisted(() => ({ + workloadIdentityConfigured: { value: true }, +})) + +vi.mock('@/lib/core/security/encryption', () => encryptionMock) +vi.mock('@/lib/credentials/workload-identity/issuer', () => ({ + isWorkloadIdentityConfigured: async () => workloadIdentityConfigured.value, + mintWorkloadIdentityToken: async ({ subject, audience }: { subject: string; audience: string }) => + `sim-oidc|${audience}|${subject}`, +})) + +import { + resolveGoogleWorkloadIdentityToken, + verifyAndEncryptGoogleWorkloadIdentityCredential, +} from '@/lib/credentials/google-workload-identity.server' +import { issueWorkloadIdentitySubject } from '@/lib/credentials/workload-identity/subject' + +const PROJECT_NUMBER = '123456789012' +const POOL = 'sim-pool' +const PROVIDER = 'sim-oidc' +const SA_EMAIL = 'bq-runner@analytics-prod.iam.gserviceaccount.com' +const PROVIDER_NAME = `projects/${PROJECT_NUMBER}/locations/global/workloadIdentityPools/${POOL}/providers/${PROVIDER}` +const SUBJECT = 'sim:workspace:ws-1:credential:abcdef0123456789' +const IMPERSONATE_URL = `https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${encodeURIComponent(SA_EMAIL)}:generateAccessToken` +const CLOUD_PLATFORM = 'https://www.googleapis.com/auth/cloud-platform' +const BIGQUERY = 'https://www.googleapis.com/auth/bigquery' + +const owner = { workspaceId: 'ws-1', actorUserId: 'user-1' } +const storedConfig = { + projectNumber: PROJECT_NUMBER, + poolId: POOL, + providerId: PROVIDER, + serviceAccountEmail: SA_EMAIL, + subject: SUBJECT, +} +const reconnectOwner = { + ...owner, + storedSecret: { type: 'google_workload_identity_v1', config: storedConfig }, +} + +interface RecordedRequest { + url: string + headers: Record + body: Record + redirect: RequestRedirect | undefined +} + +/** + * A fake Google STS and IAM Credentials. STS accepts a Sim token + * only for the provider's own audience and for subjects `acceptSubject` + * allows, and returns a federated token naming the subject; IAM lets the + * subjects `canImpersonate` allows impersonate the service account. + */ +function fakeGoogle( + fetch: ReturnType, + options: { + acceptSubject?: (subject: string) => boolean + canImpersonate?: (subject: string) => boolean + stsError?: Response + iamError?: Response + } = {} +) { + const sts: RecordedRequest[] = [] + const iam: RecordedRequest[] = [] + fetch.mockImplementation(async (url: string, init: RequestInit = {}) => { + const record = () => ({ + url, + headers: Object.fromEntries(new Headers(init.headers).entries()), + body: init.body ? JSON.parse(String(init.body)) : {}, + redirect: init.redirect, + }) + if (url === 'https://sts.googleapis.com/v1/token') { + const request = record() + sts.push(request) + if (options.stsError) return options.stsError.clone() + const [, audience, subject] = String(request.body.subjectToken).split('|') + if ( + audience !== `https://iam.googleapis.com/${PROVIDER_NAME}` || + options.acceptSubject?.(subject) === false + ) { + return jsonResponse( + { error: 'invalid_grant', error_description: 'The audience in ID Token does not match' }, + 400 + ) + } + return jsonResponse({ + access_token: `fed:${subject}`, + issued_token_type: 'urn:ietf:params:oauth:token-type:access_token', + token_type: 'Bearer', + expires_in: 3600, + }) + } + if (url.startsWith('https://iamcredentials.googleapis.com/')) { + const request = record() + iam.push(request) + if (options.iamError) return options.iamError.clone() + const subject = (request.headers.authorization ?? '').replace('Bearer fed:', '') + if (options.canImpersonate && !options.canImpersonate(subject)) { + return jsonResponse( + { error: { code: 403, status: 'PERMISSION_DENIED', message: 'denied' } }, + 403 + ) + } + return jsonResponse({ + accessToken: `ya29.sa-token-for-${(request.body.scope as string[]).join(',')}`, + expireTime: new Date(Date.now() + 3600_000).toISOString(), + }) + } + return jsonResponse({}, 404) + }) + return { sts, iam } +} + +function save( + config: Record, + saver: Parameters[1] = reconnectOwner +) { + return verifyAndEncryptGoogleWorkloadIdentityCredential( + JSON.stringify({ + authType: 'workload_identity', + projectNumber: PROJECT_NUMBER, + poolId: POOL, + providerId: PROVIDER, + serviceAccountEmail: SA_EMAIL, + ...config, + }), + saver + ) +} + +describe('saving a keyless Google Cloud credential', () => { + const fetch = vi.fn() + + beforeEach(() => { + fetch.mockReset() + vi.stubGlobal('fetch', fetch) + workloadIdentityConfigured.value = true + encryptionMockFns.mockEncryptSecret.mockReset() + encryptionMockFns.mockEncryptSecret.mockResolvedValue({ encrypted: 'ciphertext', iv: 'iv' }) + }) + + it('exchanges a Sim token for the provider’s audience at STS, then impersonates the service account', async () => { + const google = fakeGoogle(fetch, { canImpersonate: (subject) => subject === SUBJECT }) + + await expect(save({})).resolves.toEqual({ + encryptedServiceAccountKey: 'ciphertext', + serviceAccountEmail: SA_EMAIL, + workloadIdentityProvider: PROVIDER_NAME, + }) + const exchange = google.sts.find((request) => + String(request.body.subjectToken).endsWith(`|${SUBJECT}`) + ) + expect(exchange).toEqual({ + url: 'https://sts.googleapis.com/v1/token', + redirect: 'error', + headers: { 'content-type': 'application/json', accept: 'application/json' }, + body: { + grantType: 'urn:ietf:params:oauth:grant-type:token-exchange', + audience: `//iam.googleapis.com/${PROVIDER_NAME}`, + scope: CLOUD_PLATFORM, + requestedTokenType: 'urn:ietf:params:oauth:token-type:access_token', + subjectTokenType: 'urn:ietf:params:oauth:token-type:jwt', + subjectToken: `sim-oidc|https://iam.googleapis.com/${PROVIDER_NAME}|${SUBJECT}`, + }, + }) + expect(google.iam).toContainEqual({ + url: IMPERSONATE_URL, + redirect: 'error', + headers: { + 'content-type': 'application/json', + accept: 'application/json', + authorization: `Bearer fed:${SUBJECT}`, + }, + body: { scope: [CLOUD_PLATFORM], lifetime: '3600s' }, + }) + expect(encryptionMockFns.mockEncryptSecret).toHaveBeenCalledWith( + JSON.stringify({ type: 'google_workload_identity_v1', config: storedConfig }) + ) + }) + + it('names the provider settings to check when STS refuses the token', async () => { + fakeGoogle(fetch, { acceptSubject: () => false }) + + await expect(save({})).rejects.toThrow( + /refused Sim’s token for this workload identity provider.*\(invalid_grant\)/ + ) + expect(encryptionMockFns.mockEncryptSecret).not.toHaveBeenCalled() + }) + + it('names the binding to add when the subject may not impersonate the service account', async () => { + fakeGoogle(fetch, { canImpersonate: () => false }) + + await expect(save({})).rejects.toThrow( + `Grant roles/iam.workloadIdentityUser on the service account to principal://iam.googleapis.com/projects/${PROJECT_NUMBER}/locations/global/workloadIdentityPools/${POOL}/subject/${SUBJECT}` + ) + }) + + it('refuses a service account that any Sim subject can impersonate', async () => { + fakeGoogle(fetch) + + await expect(save({})).rejects.toThrow(/also trusts other Sim credentials/) + expect(encryptionMockFns.mockEncryptSecret).not.toHaveBeenCalled() + }) + + it.each([ + { + label: 'STS is unavailable for the stray subject', + fail: (url: string, body: string) => + url.startsWith('https://sts.') && !body.includes(SUBJECT) + ? jsonResponse({ error: 'temporarily_unavailable' }, 503) + : undefined, + }, + { + label: 'IAM is unreachable for the stray subject', + fail: (url: string, _body: string, auth: string) => { + if (url.startsWith('https://iamcredentials.') && auth !== `Bearer fed:${SUBJECT}`) { + throw new TypeError('fetch failed') + } + return undefined + }, + }, + ])('refuses to save when it cannot confirm the subject is pinned: $label', async ({ fail }) => { + fakeGoogle(fetch, { canImpersonate: (subject) => subject === SUBJECT }) + const google = fetch.getMockImplementation() + fetch.mockImplementation(async (url: string, init: RequestInit = {}) => { + const auth = new Headers(init.headers).get('authorization') ?? '' + return fail(url, String(init.body ?? ''), auth) ?? google?.(url, init) + }) + + await expect(save({})).rejects.toThrow(/could not confirm this service account trusts only/) + expect(encryptionMockFns.mockEncryptSecret).not.toHaveBeenCalled() + }) + + it('saves when the provider’s attribute condition refuses every other subject', async () => { + const google = fakeGoogle(fetch, { acceptSubject: (subject) => subject === SUBJECT }) + + await expect(save({})).resolves.toMatchObject({ serviceAccountEmail: SA_EMAIL }) + expect(google.sts.some((request) => !String(request.body.subjectToken).endsWith(SUBJECT))).toBe( + true + ) + }) + + it('refuses a subject issued to another member, without contacting Google', async () => { + fakeGoogle(fetch) + const grant = issueWorkloadIdentitySubject('google', { workspaceId: 'ws-1' }, 'user-2') + + await expect( + save({ subject: grant.subject, subjectProof: grant.subjectProof }, owner) + ).rejects.toThrow(/belongs to someone else/) + expect(fetch).not.toHaveBeenCalled() + }) + + it('accepts a subject issued to the saving member', async () => { + const grant = issueWorkloadIdentitySubject('google', { workspaceId: 'ws-1' }, 'user-1') + fakeGoogle(fetch, { canImpersonate: (subject) => subject === grant.subject }) + + await expect( + save({ subject: grant.subject, subjectProof: grant.subjectProof }, owner) + ).resolves.toMatchObject({ serviceAccountEmail: SA_EMAIL, newSubject: grant.subject }) + }) + + it.each([ + { projectNumber: 'my-project' }, + { projectNumber: '123/locations/global/workloadIdentityPools/other' }, + { poolId: '../other-pool' }, + { poolId: 'pool/providers/other' }, + { poolId: 'gcp-reserved' }, + { poolId: 'Sim-Pool' }, + { providerId: 'p' }, + { providerId: 'prov?audience=x' }, + { serviceAccountEmail: 'someone@gmail.com' }, + { serviceAccountEmail: 'sa@evil.example.com/x.iam.gserviceaccount.com' }, + { serviceAccountEmail: 'sa@proj.iam.gserviceaccount.com:generateIdToken' }, + { serviceAccountEmail: `a@b@${SA_EMAIL}` }, + ])('refuses %o without contacting Google', async (field) => { + fakeGoogle(fetch) + + await expect(save(field)).rejects.toThrow(/Enter the/) + expect(fetch).not.toHaveBeenCalled() + }) + + it('refuses keyless setup on a deployment that cannot sign tokens', async () => { + workloadIdentityConfigured.value = false + fakeGoogle(fetch) + + await expect(save({})).rejects.toThrow(/not available on this deployment/) + expect(fetch).not.toHaveBeenCalled() + }) + + it('never repeats a token or Google’s description in a refusal', async () => { + const leaked = 'ya29.LEAKED-ACCESS-TOKEN' + for (const google of [ + { + stsError: jsonResponse( + { + error: 'invalid_grant', + error_description: `bad token sim-oidc|x|${SUBJECT} ${leaked}`, + }, + 400 + ), + }, + { iamError: jsonResponse({ error: { code: 403, message: `denied ${leaked}` } }, 403) }, + ]) { + fakeGoogle(fetch, google) + const error: Error = await save({}).catch((caught) => caught) + expect(error.message).toMatch(/Google Cloud|service account/) + expect(error.message).not.toContain(leaked) + expect(error.message).not.toContain('sim-oidc') + expect(error.message).not.toContain('fed:') + } + }) +}) + +describe('getting a keyless Google Cloud token for a run', () => { + const fetch = vi.fn() + const secret = JSON.stringify({ type: 'google_workload_identity_v1', config: storedConfig }) + + function resolve(overrides: Partial[0]>) { + return resolveGoogleWorkloadIdentityToken({ + credentialId: 'cred-1', + decrypted: secret, + secretVersion: 'v1', + owner: { workspaceId: 'ws-1' }, + scopes: [BIGQUERY], + service: 'google-bigquery', + ...overrides, + }) + } + + beforeEach(() => { + fetch.mockReset() + vi.stubGlobal('fetch', fetch) + }) + + it('mints a service account token for the tool’s scopes', async () => { + const google = fakeGoogle(fetch) + + await expect(resolve({ credentialId: 'cred-scopes' })).resolves.toBe( + `ya29.sa-token-for-${BIGQUERY}` + ) + expect(google.iam[0]?.body).toEqual({ scope: [BIGQUERY], lifetime: '3600s' }) + }) + + it('refuses domain-wide delegation before contacting Google', async () => { + fakeGoogle(fetch) + + await expect( + resolve({ credentialId: 'cred-dwd', impersonateEmail: 'alice@example.com' }) + ).rejects.toMatchObject({ code: 'unsupported_use' }) + expect(fetch).not.toHaveBeenCalled() + }) + + it.each(['google-drive', 'gmail', 'google-sheets', undefined])( + 'refuses the Workspace service %s before contacting Google', + async (service) => { + fakeGoogle(fetch) + + await expect(resolve({ credentialId: 'cred-workspace', service })).rejects.toMatchObject({ + code: 'unsupported_use', + }) + expect(fetch).not.toHaveBeenCalled() + } + ) + + it('refuses a request with no scopes in the shared validation shape', async () => { + fakeGoogle(fetch) + + await expect(resolve({ credentialId: 'cred-no-scopes', scopes: [] })).rejects.toMatchObject({ + code: 'invalid_credentials', + }) + expect(fetch).not.toHaveBeenCalled() + }) + + it('reuses a minted token until the stored secret changes', async () => { + const google = fakeGoogle(fetch) + await resolve({ credentialId: 'cred-cache' }) + await resolve({ credentialId: 'cred-cache', service: 'vertex-ai' }) + expect(google.iam).toHaveLength(1) + + await resolve({ credentialId: 'cred-cache', secretVersion: 'v2' }) + expect(google.iam).toHaveLength(2) + }) + + it('reports a refused impersonation as a bad credential and an outage as unavailable', async () => { + fakeGoogle(fetch, { canImpersonate: () => false }) + await expect(resolve({ credentialId: 'cred-refused' })).rejects.toMatchObject({ + code: 'invalid_credentials', + }) + + fakeGoogle(fetch, { stsError: jsonResponse({ error: 'quota_exceeded' }, 429) }) + await expect(resolve({ credentialId: 'cred-outage' })).rejects.toMatchObject({ + code: 'provider_unavailable', + }) + }) +}) diff --git a/apps/sim/lib/credentials/google-workload-identity.server.ts b/apps/sim/lib/credentials/google-workload-identity.server.ts new file mode 100644 index 00000000000..3a4f0ea89f4 --- /dev/null +++ b/apps/sim/lib/credentials/google-workload-identity.server.ts @@ -0,0 +1,487 @@ +import { getErrorMessage } from '@sim/utils/errors' +import { LRUCache } from 'lru-cache' +import { z } from 'zod' +import { coalesceLocally } from '@/lib/concurrency/singleflight' +import { encryptSecret } from '@/lib/core/security/encryption' +import { + GOOGLE_KEYLESS_SERVICES, + GOOGLE_WORKLOAD_IDENTITY_SECRET_TYPE, + googleStsAudience, + googleWorkloadIdentityAudience, + googleWorkloadIdentityPrincipal, + googleWorkloadIdentityProviderName, + isGoogleProjectNumber, + isGoogleServiceAccountEmail, + isGoogleWorkloadIdentityId, +} from '@/lib/credentials/google-workload-identity' +import { parseServiceAccountConfig } from '@/lib/credentials/service-account-config' +import { + providerFailureCode, + TokenServiceAccountValidationError, +} from '@/lib/credentials/token-service-accounts/errors' +import { + isWorkloadIdentityConfigured, + mintWorkloadIdentityToken, + type WorkloadIdentityOwner, +} from '@/lib/credentials/workload-identity/issuer' +import { + bindWorkloadIdentitySubject, + newWorkloadIdentitySubject, + type WorkloadIdentityCredentialOwner, + WorkloadIdentitySubjectError, +} from '@/lib/credentials/workload-identity/subject' + +/** + * Keyless Google Cloud credentials: Workload Identity Federation with service + * account impersonation. Sim signs a short-lived token for the credential's own + * subject, Google STS exchanges it for a federated token on the customer's + * workload identity provider, and the federated token calls + * `generateAccessToken` for the service account. + * + * Impersonation rather than direct federated access: some Google Cloud APIs + * don't accept federated tokens, and impersonation gives the same identity + * (the service account and its IAM roles) that JSON-key credentials use, so + * BigQuery and Vertex AI behave exactly as they do with a key. + * + * @see https://docs.cloud.google.com/iam/docs/workload-identity-federation-with-other-providers + * @see https://docs.cloud.google.com/iam/docs/reference/sts/rest/v1/TopLevel/token + * @see https://docs.cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateAccessToken + */ + +const SUBMITTED_AUTH_TYPE = 'workload_identity' as const + +const STS_TOKEN_URL = 'https://sts.googleapis.com/v1/token' +const IAM_CREDENTIALS_ORIGIN = 'https://iamcredentials.googleapis.com' +const CLOUD_PLATFORM_SCOPE = 'https://www.googleapis.com/auth/cloud-platform' +const TOKEN_EXCHANGE_GRANT = 'urn:ietf:params:oauth:grant-type:token-exchange' +const ACCESS_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token' +const JWT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:jwt' +/** generateAccessToken's default and, without an organization policy change, its maximum. */ +const SERVICE_ACCOUNT_TOKEN_LIFETIME = '3600s' +const REQUEST_TIMEOUT_MS = 15_000 +/** `google.subject` "Cannot exceed 127 bytes". */ +const MAX_GOOGLE_SUBJECT_BYTES = 127 + +/** Re-mint once less than this much of a token's lifetime remains. */ +const TOKEN_REUSE_MARGIN_MS = 5 * 60 * 1000 +const TOKEN_CACHE_MAX = 10_000 + +/** STS error codes safe to show; descriptions stay out of the message. */ +const STS_DIAGNOSTIC_ERRORS = new Set([ + 'invalid_grant', + 'invalid_request', + 'invalid_target', + 'unauthorized_client', + 'access_denied', +]) + +const refShape = { + projectNumber: z + .string() + .trim() + .refine( + isGoogleProjectNumber, + 'Enter the project number (digits only) of the project that holds the workload identity pool' + ), + poolId: z + .string() + .trim() + .refine( + isGoogleWorkloadIdentityId, + 'Enter the workload identity pool ID: 4-32 lowercase letters, digits, or hyphens' + ), + providerId: z + .string() + .trim() + .refine( + isGoogleWorkloadIdentityId, + 'Enter the workload identity provider ID: 4-32 lowercase letters, digits, or hyphens' + ), + serviceAccountEmail: z + .string() + .trim() + .toLowerCase() + .refine( + isGoogleServiceAccountEmail, + 'Enter the service account email, like name@project-id.iam.gserviceaccount.com' + ), +} + +const subjectSchema = z + .string() + .min(1) + .refine((value) => Buffer.byteLength(value, 'utf8') <= MAX_GOOGLE_SUBJECT_BYTES) + +const storedConfigSchema = z.object({ ...refShape, subject: subjectSchema }).strict() + +type GoogleWorkloadIdentityConfig = z.infer + +const submittedConfigSchema = z + .object({ + authType: z.literal(SUBMITTED_AUTH_TYPE), + ...refShape, + subject: z.string().min(1).max(512).optional(), + subjectProof: z.string().min(1).max(512).optional(), + }) + .strict() + +const storedSecretSchema = z + .object({ type: z.literal(GOOGLE_WORKLOAD_IDENTITY_SECRET_TYPE), config: storedConfigSchema }) + .strict() + +/** A configuration problem Sim can name the fix for; its message is shown to the person saving. */ +export class GoogleWorkloadIdentityError extends Error { + /** @param status The HTTP status Google answered with, when Google itself refused. */ + constructor( + message: string, + readonly status?: number + ) { + super(message) + this.name = 'GoogleWorkloadIdentityError' + } +} + +/** Whether a submitted Google service-account configuration is the keyless mode. */ +export function isGoogleWorkloadIdentitySubmission(serialized: string): boolean { + try { + const parsed: unknown = JSON.parse(serialized) + return ( + typeof parsed === 'object' && + parsed !== null && + (parsed as { authType?: unknown }).authType === SUBMITTED_AUTH_TYPE + ) + } catch { + return false + } +} + +async function postJson( + url: string, + body: Record, + headers: Record +): Promise<{ status: number; payload: Record }> { + let response: Response + try { + response = await fetch(url, { + method: 'POST', + headers: { 'Content-Type': 'application/json', Accept: 'application/json', ...headers }, + body: JSON.stringify(body), + // A token must never follow a redirect off the Google host it was meant for. + redirect: 'error', + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + }) + } catch { + throw new GoogleWorkloadIdentityError('Could not reach Google Cloud. Try again.') + } + const payload = (await response.json().catch(() => ({}))) as Record + return { status: response.status, payload: payload ?? {} } +} + +function isProviderOutage(status: number): boolean { + return providerFailureCode(status) === 'provider_unavailable' +} + +const STS_REFUSED_MESSAGE = + 'Google Cloud refused Sim’s token for this workload identity provider. Check the project number, pool ID, and provider ID; that the provider is enabled and is an OIDC provider for the issuer shown, with no allowed audiences and the attribute mapping google.subject=assertion.sub; and that its attribute condition allows this credential’s subject.' + +/** Copy for an STS refusal. Only Google's documented issuer-connection error is matched by text. */ +function stsFailureMessage(status: number, payload: Record): string { + if (isProviderOutage(status)) return 'Google Cloud STS is unavailable. Try again.' + const description = typeof payload.error_description === 'string' ? payload.error_description : '' + if (description.includes('Error connecting to the given credential')) { + return 'Google Cloud could not fetch the signing keys from Sim’s issuer. The issuer must be reachable over public HTTPS.' + } + const code = typeof payload.error === 'string' ? payload.error : '' + return STS_DIAGNOSTIC_ERRORS.has(code) ? `${STS_REFUSED_MESSAGE} (${code})` : STS_REFUSED_MESSAGE +} + +/** + * Exchanges a Sim token for this subject at Google STS. The audience is the + * credential's own provider; the subject token's `aud` is that provider's + * resource name, which a provider with no allowed audiences accepts. + */ +async function exchangeSubjectToken( + config: GoogleWorkloadIdentityConfig, + owner: WorkloadIdentityOwner +): Promise { + const subjectToken = await mintWorkloadIdentityToken({ + subject: config.subject, + audience: googleWorkloadIdentityAudience(config), + owner, + }) + // Google asks that this request carry no Authorization header. + const { status, payload } = await postJson( + STS_TOKEN_URL, + { + grantType: TOKEN_EXCHANGE_GRANT, + audience: googleStsAudience(config), + scope: CLOUD_PLATFORM_SCOPE, + requestedTokenType: ACCESS_TOKEN_TYPE, + subjectTokenType: JWT_TOKEN_TYPE, + subjectToken, + }, + {} + ) + if (status !== 200) { + throw new GoogleWorkloadIdentityError(stsFailureMessage(status, payload), status) + } + if (typeof payload.access_token !== 'string' || !payload.access_token) { + throw new GoogleWorkloadIdentityError('Google Cloud STS answered without a token.', 502) + } + return payload.access_token +} + +function impersonationFailureMessage(status: number, config: GoogleWorkloadIdentityConfig) { + if (isProviderOutage(status)) return 'Google Cloud IAM is unavailable. Try again.' + if (status === 403) { + return `The service account ${config.serviceAccountEmail} does not let this credential impersonate it. Grant roles/iam.workloadIdentityUser on the service account to ${googleWorkloadIdentityPrincipal(config, config.subject)}, and enable the IAM Service Account Credentials API. A new binding can take a few minutes to apply.` + } + if (status === 404) { + return `Google Cloud could not find the service account ${config.serviceAccountEmail}. Check the email.` + } + return `Google Cloud refused to impersonate ${config.serviceAccountEmail} (HTTP ${status}).` +} + +interface ServiceAccountAccessToken { + accessToken: string + expiresAtMs: number +} + +/** Impersonates the service account with the federated token, for the given scopes. */ +async function impersonateServiceAccount( + config: GoogleWorkloadIdentityConfig, + federatedToken: string, + scopes: string[] +): Promise { + // The `-` project wildcard is required; the email was validated when the credential was saved. + const url = `${IAM_CREDENTIALS_ORIGIN}/v1/projects/-/serviceAccounts/${encodeURIComponent(config.serviceAccountEmail)}:generateAccessToken` + const { status, payload } = await postJson( + url, + { scope: scopes, lifetime: SERVICE_ACCOUNT_TOKEN_LIFETIME }, + { Authorization: `Bearer ${federatedToken}` } + ) + if (status !== 200) { + throw new GoogleWorkloadIdentityError(impersonationFailureMessage(status, config), status) + } + if (typeof payload.accessToken !== 'string' || !payload.accessToken) { + throw new GoogleWorkloadIdentityError('Google Cloud IAM answered without a token.', 502) + } + const expiresAtMs = + typeof payload.expireTime === 'string' ? Date.parse(payload.expireTime) : Number.NaN + return { + accessToken: payload.accessToken, + expiresAtMs: Number.isFinite(expiresAtMs) ? expiresAtMs : Date.now() + 3600_000, + } +} + +async function mintServiceAccountToken( + config: GoogleWorkloadIdentityConfig, + owner: WorkloadIdentityOwner, + scopes: string[] +): Promise { + const federatedToken = await exchangeSubjectToken(config, owner) + return impersonateServiceAccount(config, federatedToken, scopes) +} + +function isRefusal(error: unknown): boolean { + return ( + error instanceof GoogleWorkloadIdentityError && + error.status !== undefined && + providerFailureCode(error.status) === 'invalid_credentials' + ) +} + +/** + * Google maps every valid token from Sim's issuer to a principal in the pool + * unless the provider's attribute condition says otherwise, so a subject no + * credential holds must not be able to impersonate the service account. If it + * can (a `principalSet` binding for the whole pool, say), every Sim credential + * could act as this service account, and saving is refused. + */ +async function assertSubjectPinned( + config: GoogleWorkloadIdentityConfig, + owner: WorkloadIdentityOwner +): Promise { + const stray = { ...config, subject: newWorkloadIdentitySubject(owner) } + try { + await mintServiceAccountToken(stray, owner, [CLOUD_PLATFORM_SCOPE]) + } catch (error) { + if (isRefusal(error)) return + throw new GoogleWorkloadIdentityError( + 'Sim could not confirm this service account trusts only this credential. Try again.' + ) + } + throw new GoogleWorkloadIdentityError( + 'This service account also trusts other Sim credentials. Grant roles/iam.workloadIdentityUser to this credential’s principal:// subject only (not a principalSet for the pool), and add the attribute condition shown so the provider accepts only this subject.' + ) +} + +function readStoredSubject(storedSecret: Record | null | undefined) { + const parsed = storedSecretSchema.safeParse(storedSecret) + return parsed.success ? parsed.data.config.subject : undefined +} + +function bindSubject( + subject: string | undefined, + subjectProof: string | undefined, + owner: WorkloadIdentityCredentialOwner +): string { + try { + return bindWorkloadIdentitySubject({ + provider: 'google', + owner, + storedSubject: readStoredSubject(owner.storedSecret), + subject, + subjectProof, + }) + } catch (error) { + if (error instanceof WorkloadIdentitySubjectError) { + throw new GoogleWorkloadIdentityError(error.message) + } + throw error + } +} + +export interface GoogleWorkloadIdentitySaveResult { + encryptedServiceAccountKey: string + serviceAccountEmail: string + /** The workload identity provider's resource name. */ + workloadIdentityProvider: string + /** A subject this save binds that the credential did not already hold. */ + newSubject?: string +} + +/** + * Validates the submitted configuration, then proves it end to end: Sim's + * token is exchanged at STS, the federated token impersonates the service + * account. Alongside, a subject no credential holds must be refused. Returns the encrypted blob. + */ +export async function verifyAndEncryptGoogleWorkloadIdentityCredential( + serialized: string, + owner: WorkloadIdentityCredentialOwner +): Promise { + const parsed = parseServiceAccountConfig( + serialized, + submittedConfigSchema, + 'Google Cloud keyless credential' + ) + if (!parsed.success) throw new GoogleWorkloadIdentityError(parsed.message) + if (!(await isWorkloadIdentityConfigured())) { + throw new GoogleWorkloadIdentityError( + 'Keyless connections are not available on this deployment. Use a JSON key.' + ) + } + const submitted = parsed.data + const config: GoogleWorkloadIdentityConfig = { + projectNumber: submitted.projectNumber, + poolId: submitted.poolId, + providerId: submitted.providerId, + serviceAccountEmail: submitted.serviceAccountEmail, + subject: bindSubject(submitted.subject, submitted.subjectProof, owner), + } + if (!subjectSchema.safeParse(config.subject).success) { + throw new GoogleWorkloadIdentityError('This credential’s subject is too long for Google Cloud.') + } + + // A token from generateAccessToken proves the provider accepted Sim's token and the + // service account lets this subject impersonate it. + const verify = () => mintServiceAccountToken(config, owner, [CLOUD_PLATFORM_SCOPE]) + // The pin probe is independent of the verification, so both run at once; a + // verification failure still reports first. + const [verified, pinned] = await Promise.allSettled([ + verify(), + assertSubjectPinned(config, owner), + ]) + if (verified.status === 'rejected') { + if (verified.reason instanceof GoogleWorkloadIdentityError) throw verified.reason + throw new GoogleWorkloadIdentityError( + `Could not verify the Google Cloud keyless credential: ${getErrorMessage(verified.reason, 'Unknown error')}` + ) + } + if (pinned.status === 'rejected') throw pinned.reason + + const { encrypted } = await encryptSecret( + JSON.stringify({ type: GOOGLE_WORKLOAD_IDENTITY_SECRET_TYPE, config }) + ) + return { + encryptedServiceAccountKey: encrypted, + serviceAccountEmail: config.serviceAccountEmail, + workloadIdentityProvider: googleWorkloadIdentityProviderName(config), + ...(config.subject !== readStoredSubject(owner.storedSecret) + ? { newSubject: config.subject } + : {}), + } +} + +/** + * Minted tokens per credential, stored-secret version, and scopes: a reconnect + * re-encrypts the secret and so never reuses the old configuration's token. + */ +const tokenCache = new LRUCache({ max: TOKEN_CACHE_MAX }) + +export interface ResolveGoogleWorkloadIdentityTokenInput { + credentialId: string + /** The credential's decrypted secret. */ + decrypted: string + /** Changes whenever the stored secret is re-encrypted. */ + secretVersion: string + owner: WorkloadIdentityOwner + scopes: string[] + /** A domain-wide-delegation subject, which a keyless credential refuses. */ + impersonateEmail?: string + /** The Google service the token is for, from server-side policy. */ + service?: string +} + +/** + * Resolves an authorized keyless Google credential to a service account token. + * It refuses domain-wide delegation and any service that is not a Google Cloud + * API before doing anything else: Workspace data needs a delegated user, which + * this mode cannot prove. + */ +export async function resolveGoogleWorkloadIdentityToken( + input: ResolveGoogleWorkloadIdentityTokenInput +): Promise { + if (input.impersonateEmail) { + throw new TokenServiceAccountValidationError('unsupported_use', 400, { + step: 'google_keyless_delegation', + reason: 'keyless Google Cloud credentials cannot impersonate a Workspace user', + }) + } + if (!input.service || !GOOGLE_KEYLESS_SERVICES.has(input.service)) { + throw new TokenServiceAccountValidationError('unsupported_use', 400, { + step: 'google_keyless_service', + reason: 'keyless Google Cloud credentials work only with Google Cloud APIs', + }) + } + if (input.scopes.length === 0) { + throw new TokenServiceAccountValidationError('invalid_credentials', 400, { + step: 'google_keyless_scopes', + reason: 'scopes are required for service account credentials', + }) + } + const scopeKey = [...new Set(input.scopes)].sort().join(' ') + const cacheKey = `${input.credentialId}:${input.secretVersion}:${scopeKey}` + const cached = tokenCache.get(cacheKey) + if (cached) return cached + + // Concurrent block runs share one mint, so it is not tied to any one caller's signal. + return coalesceLocally(`google-keyless:${cacheKey}`, async () => { + const { config } = storedSecretSchema.parse(JSON.parse(input.decrypted)) + let token: ServiceAccountAccessToken + try { + token = await mintServiceAccountToken(config, input.owner, scopeKey.split(' ')) + } catch (error) { + if (!(error instanceof GoogleWorkloadIdentityError)) throw error + // Report in the shared service-account codes: an outage is not a bad credential. + throw new TokenServiceAccountValidationError( + error.status === undefined ? 'provider_unavailable' : providerFailureCode(error.status), + error.status ?? 502, + { step: 'google_keyless_token' } + ) + } + const ttl = token.expiresAtMs - Date.now() - TOKEN_REUSE_MARGIN_MS + if (ttl > 0) tokenCache.set(cacheKey, token.accessToken, { ttl }) + return token.accessToken + }) +} diff --git a/apps/sim/lib/credentials/google-workload-identity.test.ts b/apps/sim/lib/credentials/google-workload-identity.test.ts new file mode 100644 index 00000000000..04e70bdccb3 --- /dev/null +++ b/apps/sim/lib/credentials/google-workload-identity.test.ts @@ -0,0 +1,50 @@ +/** + * @vitest-environment node + */ +import { describe, expect, it } from 'vitest' +import { googleKeylessOffer } from '@/lib/credentials/google-workload-identity' + +describe('keyless setup in the Google service account dialog', () => { + it.each(['google-drive', 'gmail', 'google-sheets'])( + 'never offers the keyless form when reconnecting a keyless credential from %s', + (oauthServiceId) => { + expect(googleKeylessOffer({ oauthServiceId, available: true, reconnectsKeyless: true })).toBe( + 'cloud_only' + ) + } + ) + + it('offers JSON keys only for a new connection from a Workspace service', () => { + expect( + googleKeylessOffer({ oauthServiceId: 'gmail', available: true, reconnectsKeyless: false }) + ).toBe('none') + }) + + it.each([true, false])( + 'offers keyless for BigQuery whether or not the reconnected credential is keyless (%s)', + (reconnectsKeyless) => { + expect( + googleKeylessOffer({ + oauthServiceId: 'google-bigquery', + available: true, + reconnectsKeyless, + }) + ).toBe('offer') + } + ) + + it('keeps a keyless credential keyless when reconnected from its own page', () => { + expect(googleKeylessOffer({ available: true, reconnectsKeyless: true })).toBe('offer') + expect(googleKeylessOffer({ available: true, reconnectsKeyless: false })).toBe('none') + }) + + it('offers nothing keyless where this deployment cannot sign tokens', () => { + expect( + googleKeylessOffer({ + oauthServiceId: 'google-bigquery', + available: false, + reconnectsKeyless: true, + }) + ).toBe('none') + }) +}) diff --git a/apps/sim/lib/credentials/google-workload-identity.ts b/apps/sim/lib/credentials/google-workload-identity.ts new file mode 100644 index 00000000000..42eeab2d59b --- /dev/null +++ b/apps/sim/lib/credentials/google-workload-identity.ts @@ -0,0 +1,186 @@ +/** + * Keyless Google Cloud credentials (Workload Identity Federation): the parts + * the connect dialog and the server share. A keyless credential is a mode of + * the `google-service-account` credential that stores no key: Sim's signed + * token is exchanged at Google STS against the customer's workload identity + * provider, and the federated token impersonates the service account. + * + * Every value here ends up in a Google URL or audience, so each one is checked + * against Google's documented format and nothing else can reach the request. + * + * @see https://docs.cloud.google.com/iam/docs/workload-identity-federation-with-other-providers + */ + +/** + * The Google services a keyless credential may mint for: Google Cloud APIs the + * service account calls as itself. Google Workspace services need domain-wide + * delegation, which keyless credentials do not support. + */ +export const GOOGLE_KEYLESS_SERVICES: ReadonlySet = new Set([ + 'google-bigquery', + 'vertex-ai', +]) + +/** + * What a Google service account connect dialog offers for keyless setup. + * + * - `offer`: a Google Cloud service (new or reconnect), or a keyless credential + * reconnected from a context that names no service (its own detail page). + * - `cloud_only`: a keyless credential reconnected from a Google Workspace + * service, which can never use it; the dialog explains instead of saving. + * - `none`: JSON key only. + */ +export function googleKeylessOffer(input: { + /** The OAuth service the dialog was opened for, when it was opened for one. */ + oauthServiceId?: string + /** This deployment can sign workload-identity tokens for this owner. */ + available: boolean + /** The credential being reconnected is keyless. */ + reconnectsKeyless: boolean +}): 'offer' | 'cloud_only' | 'none' { + if (!input.available) return 'none' + if (input.oauthServiceId && GOOGLE_KEYLESS_SERVICES.has(input.oauthServiceId)) return 'offer' + if (!input.reconnectsKeyless) return 'none' + return input.oauthServiceId ? 'cloud_only' : 'offer' +} + +/** The `type` of a keyless credential's stored secret; a JSON key's is `service_account`. */ +export const GOOGLE_WORKLOAD_IDENTITY_SECRET_TYPE = 'google_workload_identity_v1' as const + +/** Whether a decrypted `google-service-account` secret is a keyless one. */ +export function isGoogleWorkloadIdentitySecret(decrypted: string): boolean { + try { + const parsed: unknown = JSON.parse(decrypted) + return ( + typeof parsed === 'object' && + parsed !== null && + (parsed as { type?: unknown }).type === GOOGLE_WORKLOAD_IDENTITY_SECRET_TYPE + ) + } catch { + return false + } +} + +/** A project number is Google's numeric project identifier, not the project ID. */ +const PROJECT_NUMBER_PATTERN = /^[1-9][0-9]{0,19}$/ + +/** + * Pool and provider IDs: "4-32 characters, and may contain the characters + * [a-z0-9-]. The prefix `gcp-` is reserved for use by Google". + * @see https://docs.cloud.google.com/iam/docs/reference/rest/v1/projects.locations.workloadIdentityPools/create + */ +const POOL_OR_PROVIDER_ID_PATTERN = /^(?!gcp-)[a-z0-9-]{4,32}$/ + +/** + * A user-managed service account: an account ID of 6-30 characters matching + * `[a-z]([-a-z0-9]*[a-z0-9])`, in a project whose ID follows the same rule. + * @see https://docs.cloud.google.com/iam/docs/reference/rest/v1/projects.serviceAccounts/create + */ +const SERVICE_ACCOUNT_EMAIL_PATTERN = + /^[a-z][-a-z0-9]{4,28}[a-z0-9]@[a-z][-a-z0-9]{4,28}[a-z0-9]\.iam\.gserviceaccount\.com$/ + +/** + * A Google Cloud project number: digits only, no leading zero, up to 20 digits + * (`123456789012`). The project ID (`my-project`) is not accepted. + */ +export function isGoogleProjectNumber(value: string): boolean { + return PROJECT_NUMBER_PATTERN.test(value) +} + +/** + * A workload identity pool or provider ID: 4-32 lowercase letters, digits, or + * hyphens, not starting with the reserved `gcp-` prefix. + */ +export function isGoogleWorkloadIdentityId(value: string): boolean { + return POOL_OR_PROVIDER_ID_PATTERN.test(value) +} + +/** + * A user-managed service account email, `@.iam.gserviceaccount.com`, + * where both IDs are 6-30 characters of lowercase letters, digits, and hyphens, + * start with a letter, and end with a letter or digit. + */ +export function isGoogleServiceAccountEmail(value: string): boolean { + return SERVICE_ACCOUNT_EMAIL_PATTERN.test(value) +} + +/** The customer's workload identity provider, by the IDs that name it. */ +export interface GoogleWorkloadIdentityProviderRef { + projectNumber: string + poolId: string + providerId: string +} + +/** `projects//locations/global/workloadIdentityPools//providers/`. */ +export function googleWorkloadIdentityProviderName(ref: GoogleWorkloadIdentityProviderRef): string { + if ( + !isGoogleProjectNumber(ref.projectNumber) || + !isGoogleWorkloadIdentityId(ref.poolId) || + !isGoogleWorkloadIdentityId(ref.providerId) + ) { + throw new Error('Invalid Google workload identity provider') + } + return `projects/${ref.projectNumber}/locations/global/workloadIdentityPools/${ref.poolId}/providers/${ref.providerId}` +} + +/** + * The `aud` of Sim's token. A provider with no allowed audiences accepts "the + * full canonical resource name of the WorkloadIdentityPoolProvider, with or + * without the HTTPS prefix"; Google's setup guide shows the `https://` form. + * @see https://docs.cloud.google.com/iam/docs/reference/rest/v1/projects.locations.workloadIdentityPools.providers + */ +export function googleWorkloadIdentityAudience(ref: GoogleWorkloadIdentityProviderRef): string { + return `https://iam.googleapis.com/${googleWorkloadIdentityProviderName(ref)}` +} + +/** + * The STS `audience` parameter, in the form the token-exchange reference gives + * for workload identity pools. + * @see https://docs.cloud.google.com/iam/docs/reference/sts/rest/v1/TopLevel/token + */ +export function googleStsAudience(ref: GoogleWorkloadIdentityProviderRef): string { + return `//iam.googleapis.com/${googleWorkloadIdentityProviderName(ref)}` +} + +/** The federated principal Google maps a Sim token with this subject to. */ +export function googleWorkloadIdentityPrincipal( + ref: GoogleWorkloadIdentityProviderRef, + subject: string +): string { + googleWorkloadIdentityProviderName(ref) + return `principal://iam.googleapis.com/projects/${ref.projectNumber}/locations/global/workloadIdentityPools/${ref.poolId}/subject/${subject}` +} + +/** + * The gcloud commands that set up trust for one credential: the pool, an OIDC + * provider for Sim's issuer that accepts only this credential's subject, and + * the binding that lets that subject impersonate the service account. The + * provider sets no allowed audiences, so it accepts its own resource name. + */ +export function googleWorkloadIdentitySetupCommands(input: { + ref: GoogleWorkloadIdentityProviderRef + serviceAccountEmail: string + issuer: string + subject: string +}): string { + const { ref, serviceAccountEmail, issuer, subject } = input + return [ + `gcloud iam workload-identity-pools create ${ref.poolId} \\`, + ` --project="${ref.projectNumber}" \\`, + ' --location="global" \\', + ' --display-name="Sim"', + '', + `gcloud iam workload-identity-pools providers create-oidc ${ref.providerId} \\`, + ` --project="${ref.projectNumber}" \\`, + ' --location="global" \\', + ` --workload-identity-pool="${ref.poolId}" \\`, + ` --issuer-uri="${issuer}" \\`, + ' --attribute-mapping="google.subject=assertion.sub" \\', + ` --attribute-condition="assertion.sub=='${subject}'"`, + '', + `gcloud iam service-accounts add-iam-policy-binding ${serviceAccountEmail} \\`, + ` --project="${ref.projectNumber}" \\`, + ' --role="roles/iam.workloadIdentityUser" \\', + ` --member="${googleWorkloadIdentityPrincipal(ref, subject)}"`, + ].join('\n') +} diff --git a/apps/sim/lib/credentials/microsoft-app-service-account.server.test.ts b/apps/sim/lib/credentials/microsoft-app-service-account.server.test.ts new file mode 100644 index 00000000000..7dc2a6a40fe --- /dev/null +++ b/apps/sim/lib/credentials/microsoft-app-service-account.server.test.ts @@ -0,0 +1,461 @@ +/** + * @vitest-environment node + */ + +import { + createHash, + createPublicKey, + createSign, + generateKeyPairSync, + X509Certificate, +} from 'node:crypto' +import { queueTableRows, resetDbChainMock } from '@sim/testing' +import { jsonResponse } from '@sim/testing/helpers/http' +import { encryptionMock, encryptionMockFns } from '@sim/testing/mocks/encryption.mock' +import { decodeProtectedHeader, jwtVerify } from 'jose' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@/lib/core/security/encryption', () => encryptionMock) +vi.mock('@/lib/credentials/workload-identity/issuer', () => ({ + isWorkloadIdentityConfigured: async () => true, + mintWorkloadIdentityToken: async ({ subject, audience }: { subject: string; audience: string }) => + `sim-oidc|${audience}|${subject}`, +})) + +import { credential } from '@sim/db/schema' +import { + resolveMicrosoftAppCredentialToken, + verifyAndEncryptMicrosoftAppCredential, +} from '@/lib/credentials/microsoft-app-service-account.server' +import { issueWorkloadIdentitySubject } from '@/lib/credentials/workload-identity/subject' +import { MICROSOFT_APP_SERVICE_ACCOUNT_PROVIDER_ID } from '@/lib/oauth/types' + +/** DER type-length-value, for the one self-signed certificate below. */ +function der(tag: number, ...parts: Buffer[]): Buffer { + const content = Buffer.concat(parts) + const length = + content.length < 0x80 + ? Buffer.from([content.length]) + : content.length < 0x100 + ? Buffer.from([0x81, content.length]) + : Buffer.from([0x82, content.length >> 8, content.length & 0xff]) + return Buffer.concat([Buffer.from([tag]), length, content]) +} + +function derOid(oid: string): Buffer { + const [first, second, ...rest] = oid.split('.').map(Number) + const bytes = [first * 40 + second] + for (const arc of rest) { + const septets = [arc & 0x7f] + for (let value = arc >> 7; value > 0; value >>= 7) septets.unshift((value & 0x7f) | 0x80) + bytes.push(...septets) + } + return der(0x06, Buffer.from(bytes)) +} + +function derUtcTime(date: Date): Buffer { + const text = date.toISOString().replace(/[-:T]/g, '').slice(2, 14) + return der(0x17, Buffer.from(`${text}Z`)) +} + +/** + * A self-signed RSA certificate (CN=sim-test-app) generated for this test run, + * so no key material is committed. + */ +function generateTestCertificate(): { certificate: string; privateKey: string } { + const { privateKey, publicKey } = generateKeyPairSync('rsa', { modulusLength: 2048 }) + const sha256WithRsa = der(0x30, derOid('1.2.840.113549.1.1.11'), der(0x05)) + const name = der( + 0x30, + der(0x31, der(0x30, derOid('2.5.4.3'), der(0x0c, Buffer.from('sim-test-app')))) + ) + const now = Date.now() + const tbs = der( + 0x30, + der(0xa0, der(0x02, Buffer.from([0x02]))), + der(0x02, Buffer.from([0x01])), + sha256WithRsa, + name, + der(0x30, derUtcTime(new Date(now - 86_400_000)), derUtcTime(new Date(now + 365 * 86_400_000))), + name, + publicKey.export({ type: 'spki', format: 'der' }) + ) + const signature = createSign('sha256').update(tbs).sign(privateKey) + const certificate = der(0x30, tbs, sha256WithRsa, der(0x03, Buffer.from([0x00]), signature)) + const pem = (label: string, body: Buffer) => + `-----BEGIN ${label}-----\n${body + .toString('base64') + .match(/.{1,64}/g) + ?.join('\n')}\n-----END ${label}-----` + return { + certificate: pem('CERTIFICATE', certificate), + privateKey: privateKey.export({ type: 'pkcs8', format: 'pem' }).toString(), + } +} + +const { certificate: TEST_CERTIFICATE, privateKey: TEST_PRIVATE_KEY } = generateTestCertificate() + +const TENANT = '11111111-2222-3333-4444-555555555555' +const CLIENT_ID = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee' +const SECRET = 'entra-secret-value~123' +const TOKEN_URL = `https://login.microsoftonline.com/${TENANT}/oauth2/v2.0/token` +const ENVIRONMENT = 'https://contoso.api.crm.dynamics.com' +const owner = { workspaceId: 'ws-1', actorUserId: 'user-1' } + +interface TokenRequest { + url: string + form: Record + redirect: RequestRedirect | undefined +} + +/** + * A fake Entra token endpoint plus Graph and Dataverse. `acceptAssertion` + * decides whether a client assertion is trusted; every other request succeeds. + */ +function fakeMicrosoft( + fetch: ReturnType, + options: { acceptAssertion?: (assertion: string) => boolean; tokenError?: Response } = {} +) { + const tokenRequests: TokenRequest[] = [] + fetch.mockImplementation(async (url: string, init: RequestInit = {}) => { + if (url.startsWith('https://login.microsoftonline.com/')) { + const form = Object.fromEntries(new URLSearchParams(String(init.body))) + tokenRequests.push({ url, form, redirect: init.redirect }) + if (options.tokenError) return options.tokenError.clone() + if (form.client_assertion && options.acceptAssertion?.(form.client_assertion) === false) { + return jsonResponse( + { error: 'invalid_client', error_codes: [700213], error_description: 'AADSTS700213: …' }, + 400 + ) + } + return jsonResponse({ + token_type: 'Bearer', + expires_in: 3599, + access_token: `at:${form.scope}`, + }) + } + if (url.startsWith('https://graph.microsoft.com/')) { + return jsonResponse({ id: 'sp-object-id', appId: CLIENT_ID, displayName: 'Sim workflows' }) + } + if (url.endsWith('/api/data/v9.2/WhoAmI')) return jsonResponse({ UserId: 'app-user' }) + return jsonResponse({}, 404) + }) + return tokenRequests +} + +function save(config: Record, saver = owner) { + return verifyAndEncryptMicrosoftAppCredential( + JSON.stringify({ tenantId: TENANT, clientId: CLIENT_ID, ...config }), + saver + ) +} + +describe('saving a Microsoft app credential', () => { + const fetch = vi.fn() + + beforeEach(() => { + fetch.mockReset() + vi.stubGlobal('fetch', fetch) + encryptionMockFns.mockEncryptSecret.mockReset() + encryptionMockFns.mockEncryptSecret.mockResolvedValue({ encrypted: 'ciphertext', iv: 'iv' }) + }) + + it('exchanges a client secret at the tenant’s token endpoint and reads the app’s own service principal', async () => { + const tokens = fakeMicrosoft(fetch) + + await expect(save({ authType: 'client_secret', clientSecret: SECRET })).resolves.toMatchObject({ + displayName: 'Sim workflows', + servicePrincipalId: 'sp-object-id', + }) + expect(tokens).toEqual([ + { + url: TOKEN_URL, + redirect: 'error', + form: { + client_id: CLIENT_ID, + scope: 'https://graph.microsoft.com/.default', + grant_type: 'client_credentials', + client_secret: SECRET, + }, + }, + ]) + expect(fetch).toHaveBeenCalledWith( + `https://graph.microsoft.com/v1.0/servicePrincipals(appId='${CLIENT_ID}')?$select=id,appId,displayName`, + expect.objectContaining({ redirect: 'error' }) + ) + }) + + it('signs a PS256 certificate assertion Entra can verify with the uploaded certificate', async () => { + const tokens = fakeMicrosoft(fetch) + + await save({ + authType: 'certificate', + certificate: TEST_CERTIFICATE, + privateKey: TEST_PRIVATE_KEY, + }) + + const assertion = tokens[0]?.form.client_assertion ?? '' + expect(tokens[0]?.form).toMatchObject({ + client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer', + }) + expect(tokens[0]?.form.client_secret).toBeUndefined() + const certificate = new X509Certificate(TEST_CERTIFICATE) + expect(decodeProtectedHeader(assertion)).toEqual({ + alg: 'PS256', + typ: 'JWT', + 'x5t#S256': createHash('sha256').update(certificate.raw).digest('base64url'), + }) + const { payload } = await jwtVerify(assertion, createPublicKey(TEST_CERTIFICATE), { + algorithms: ['PS256'], + audience: TOKEN_URL, + issuer: CLIENT_ID, + subject: CLIENT_ID, + }) + expect(payload.jti).toEqual(expect.any(String)) + expect((payload.exp ?? 0) - (payload.nbf ?? 0)).toBeLessThanOrEqual(600) + }) + + it('refuses a private key that does not belong to the certificate before contacting Entra', async () => { + fakeMicrosoft(fetch) + const otherKey = generateKeyPairSync('rsa', { modulusLength: 2048 }) + .privateKey.export({ type: 'pkcs8', format: 'pem' }) + .toString() + + await expect( + save({ authType: 'certificate', certificate: TEST_CERTIFICATE, privateKey: otherKey }) + ).rejects.toThrow(/does not belong to this certificate/) + expect(fetch).not.toHaveBeenCalled() + expect(encryptionMockFns.mockEncryptSecret).not.toHaveBeenCalled() + }) + + describe('keyless', () => { + const SUBJECT = 'sim:workspace:ws-1:credential:abcdef0123456789' + const reconnectOwner = { + ...owner, + storedSecret: { + type: 'microsoft_app_credential_v1', + config: { authType: 'federated', tenantId: TENANT, clientId: CLIENT_ID, subject: SUBJECT }, + }, + } + + it('presents a Sim token for this credential’s subject with the Entra exchange audience', async () => { + const tokens = fakeMicrosoft(fetch, { + acceptAssertion: (assertion) => assertion.endsWith(`|${SUBJECT}`), + }) + + await expect(save({ authType: 'federated' }, reconnectOwner)).resolves.toMatchObject({ + displayName: 'Sim workflows', + }) + const used = tokens.map((request) => request.form.client_assertion) + expect(used).toContain(`sim-oidc|api://AzureADTokenExchange|${SUBJECT}`) + }) + + it('reports a newly issued subject so the save can check no other credential holds it', async () => { + const grant = issueWorkloadIdentitySubject('microsoft', { workspaceId: 'ws-1' }, 'user-1') + fakeMicrosoft(fetch, { + acceptAssertion: (assertion) => + assertion.endsWith(`|${grant.subject}`) || assertion.endsWith(`|${SUBJECT}`), + }) + + await expect( + save({ authType: 'federated', subject: grant.subject, subjectProof: grant.subjectProof }) + ).resolves.toMatchObject({ newSubject: grant.subject }) + await expect(save({ authType: 'federated' }, reconnectOwner)).resolves.not.toHaveProperty( + 'newSubject' + ) + }) + + it('refuses an app that also accepts a subject no credential holds', async () => { + fakeMicrosoft(fetch, { acceptAssertion: () => true }) + + await expect(save({ authType: 'federated' }, reconnectOwner)).rejects.toThrow( + /also trusts other Sim credentials/ + ) + expect(encryptionMockFns.mockEncryptSecret).not.toHaveBeenCalled() + }) + + it('refuses a subject issued to another member, without contacting Entra', async () => { + fakeMicrosoft(fetch) + const grant = issueWorkloadIdentitySubject('microsoft', { workspaceId: 'ws-1' }, 'user-2') + + await expect( + save({ authType: 'federated', subject: grant.subject, subjectProof: grant.subjectProof }) + ).rejects.toThrow(/belongs to someone else/) + expect(fetch).not.toHaveBeenCalled() + }) + + it('names the federated credential mismatch when Entra rejects the subject', async () => { + fakeMicrosoft(fetch, { acceptAssertion: () => false }) + + await expect(save({ authType: 'federated' }, reconnectOwner)).rejects.toThrow( + /No federated credential on this app matches/ + ) + }) + }) + + it('verifies the Dataverse environment with its own token and WhoAmI', async () => { + const tokens = fakeMicrosoft(fetch) + + await save({ + authType: 'client_secret', + clientSecret: SECRET, + environmentUrl: 'https://contoso.crm.dynamics.com/', + }) + + expect(tokens.map((request) => request.form.scope)).toEqual([ + 'https://graph.microsoft.com/.default', + `${ENVIRONMENT}/.default`, + ]) + expect(fetch).toHaveBeenCalledWith( + `${ENVIRONMENT}/api/data/v9.2/WhoAmI`, + expect.objectContaining({ + headers: expect.objectContaining({ Authorization: `Bearer at:${ENVIRONMENT}/.default` }), + }) + ) + }) + + it.each([ + 'https://evil.example.com', + 'https://contoso.crm.dynamics.com.evil.example.com', + 'https://contoso.crm.dynamics.com/api/data', + 'http://contoso.crm.dynamics.com', + 'https://user@contoso.crm.dynamics.com', + ])('refuses the environment %s without sending a token anywhere', async (environmentUrl) => { + fakeMicrosoft(fetch) + + await expect( + save({ authType: 'client_secret', clientSecret: SECRET, environmentUrl }) + ).rejects.toThrow(/Dataverse environment URL/) + expect(fetch).not.toHaveBeenCalled() + }) + + it.each(['common', 'organizations', '../evil', 'contoso.onmicrosoft.com/x'])( + 'refuses the tenant %s', + async (tenantId) => { + await expect( + verifyAndEncryptMicrosoftAppCredential( + JSON.stringify({ + tenantId, + clientId: CLIENT_ID, + authType: 'client_secret', + clientSecret: SECRET, + }), + owner + ) + ).rejects.toThrow(/tenant/) + expect(fetch).not.toHaveBeenCalled() + } + ) + + it('never repeats the secret, key, or assertion in a refusal', async () => { + fakeMicrosoft(fetch, { + tokenError: jsonResponse( + { + error: 'invalid_client', + error_codes: [7000215], + error_description: `AADSTS7000215: bad secret ${SECRET} ${TEST_PRIVATE_KEY}`, + }, + 401 + ), + }) + + for (const config of [ + { authType: 'client_secret', clientSecret: SECRET }, + { authType: 'certificate', certificate: TEST_CERTIFICATE, privateKey: TEST_PRIVATE_KEY }, + ]) { + const error: Error = await save(config).catch((caught) => caught) + expect(error.message).toMatch(/Microsoft Entra/) + expect(error.message).not.toContain(SECRET) + expect(error.message).not.toContain('PRIVATE KEY') + expect(error.message).not.toContain('eyJ') + } + }) +}) + +describe('getting a Microsoft app token for a run', () => { + const fetch = vi.fn() + + function storeCredential(config: Record, encrypted = 'ciphertext-a') { + resetDbChainMock() + queueTableRows(credential, [ + { + workspaceId: 'ws-1', + organizationId: null, + type: 'service_account', + providerId: MICROSOFT_APP_SERVICE_ACCOUNT_PROVIDER_ID, + revokedAt: null, + encryptedServiceAccountKey: encrypted, + }, + ]) + encryptionMockFns.mockDecryptSecret.mockResolvedValueOnce({ + decrypted: JSON.stringify({ + type: 'microsoft_app_credential_v1', + config: { tenantId: TENANT, clientId: CLIENT_ID, ...config }, + }), + }) + } + + beforeEach(() => { + fetch.mockReset() + vi.stubGlobal('fetch', fetch) + encryptionMockFns.mockDecryptSecret.mockReset() + }) + + it.each(['outlook', 'onedrive', 'microsoft-teams', undefined])( + 'refuses to mint for %s before reading the credential', + async (service) => { + await expect(resolveMicrosoftAppCredentialToken('cred-1', service)).rejects.toMatchObject({ + code: 'invalid_credentials', + }) + expect(encryptionMockFns.mockDecryptSecret).not.toHaveBeenCalled() + expect(fetch).not.toHaveBeenCalled() + } + ) + + it('mints a Dataverse token for the stored environment and returns that environment', async () => { + const tokens = fakeMicrosoft(fetch) + storeCredential( + { authType: 'client_secret', clientSecret: SECRET, environmentUrl: ENVIRONMENT }, + 'ciphertext-dataverse' + ) + + await expect( + resolveMicrosoftAppCredentialToken('cred-dataverse', 'microsoft-dataverse') + ).resolves.toEqual({ accessToken: `at:${ENVIRONMENT}/.default`, instanceUrl: ENVIRONMENT }) + expect(tokens.map((request) => request.form.scope)).toEqual([`${ENVIRONMENT}/.default`]) + }) + + it('refuses Dataverse for a credential saved without an environment', async () => { + fakeMicrosoft(fetch) + storeCredential({ authType: 'client_secret', clientSecret: SECRET }, 'ciphertext-graph-only') + + await expect( + resolveMicrosoftAppCredentialToken('cred-graph-only', 'microsoft-dataverse') + ).rejects.toMatchObject({ code: 'invalid_credentials' }) + expect(fetch).not.toHaveBeenCalled() + }) + + it('reuses a minted Graph token until the stored secret changes', async () => { + const tokens = fakeMicrosoft(fetch) + storeCredential({ authType: 'client_secret', clientSecret: SECRET }, 'ciphertext-v1') + await resolveMicrosoftAppCredentialToken('cred-cache', 'microsoft-ad') + storeCredential({ authType: 'client_secret', clientSecret: SECRET }, 'ciphertext-v1') + await resolveMicrosoftAppCredentialToken('cred-cache', 'sharepoint') + expect(tokens).toHaveLength(1) + encryptionMockFns.mockDecryptSecret.mockReset() + + storeCredential({ authType: 'client_secret', clientSecret: 'rotated' }, 'ciphertext-v2') + await resolveMicrosoftAppCredentialToken('cred-cache', 'sharepoint') + expect(tokens).toHaveLength(2) + expect(tokens[1]?.form.client_secret).toBe('rotated') + }) + + it('reports an Entra outage as the provider being unavailable, not a bad credential', async () => { + fakeMicrosoft(fetch, { tokenError: jsonResponse({ error: 'temporarily_unavailable' }, 503) }) + storeCredential({ authType: 'client_secret', clientSecret: SECRET }, 'ciphertext-outage') + + await expect( + resolveMicrosoftAppCredentialToken('cred-outage', 'microsoft-ad') + ).rejects.toMatchObject({ code: 'provider_unavailable' }) + }) +}) diff --git a/apps/sim/lib/credentials/microsoft-app-service-account.server.ts b/apps/sim/lib/credentials/microsoft-app-service-account.server.ts new file mode 100644 index 00000000000..239bb95c64f --- /dev/null +++ b/apps/sim/lib/credentials/microsoft-app-service-account.server.ts @@ -0,0 +1,708 @@ +import { createHash, createPrivateKey, type KeyObject, X509Certificate } from 'node:crypto' +import { db } from '@sim/db' +import { credential } from '@sim/db/schema' +import { getErrorMessage } from '@sim/utils/errors' +import { generateId } from '@sim/utils/id' +import { eq } from 'drizzle-orm' +import { SignJWT } from 'jose' +import { LRUCache } from 'lru-cache' +import { z } from 'zod' +import { coalesceLocally } from '@/lib/concurrency/singleflight' +import { decryptSecret, encryptSecret } from '@/lib/core/security/encryption' +import { parseServiceAccountConfig } from '@/lib/credentials/service-account-config' +import { + providerFailureCode, + TokenServiceAccountValidationError, +} from '@/lib/credentials/token-service-accounts/errors' +import { WORKLOAD_IDENTITY_AUDIENCES } from '@/lib/credentials/workload-identity/audiences' +import { + isWorkloadIdentityConfigured, + mintWorkloadIdentityToken, + type WorkloadIdentityOwner, +} from '@/lib/credentials/workload-identity/issuer' +import { + bindWorkloadIdentitySubject, + newWorkloadIdentitySubject, + type WorkloadIdentityCredentialOwner, + WorkloadIdentitySubjectError, +} from '@/lib/credentials/workload-identity/subject' +import { normalizeMicrosoftDataverseEnvironmentUrl } from '@/lib/oauth/microsoft-dataverse' +import { MICROSOFT_APP_SERVICE_ACCOUNT_PROVIDER_ID } from '@/lib/oauth/types' + +/** + * Saved Microsoft Entra app-only credentials (OAuth 2.0 client credentials). + * + * One app registration serves every Microsoft service that runs without a + * signed-in user: Microsoft Graph for Entra ID and SharePoint, and the + * credential's own Dataverse environment for Dataverse and Dynamics 365. The + * app's application permissions and the environment's application user decide + * what it can do; Sim stores no permission list of its own. + * + * - `client_secret`: the app's client secret. + * - `certificate`: a PEM private key and its certificate. Sim signs a PS256 + * client assertion carrying the certificate's `x5t#S256` thumbprint. + * - `federated`: no stored secret. Sim signs a short-lived token for this + * credential's own subject and presents it as the client assertion, which a + * federated identity credential on the app trusts. + * + * @see https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-client-creds-grant-flow + * @see https://learn.microsoft.com/en-us/entra/identity-platform/certificate-credentials + */ + +const SECRET_TYPE = 'microsoft_app_credential_v1' as const +const LOGIN_ORIGIN = 'https://login.microsoftonline.com' +const GRAPH_RESOURCE = 'https://graph.microsoft.com' +const CLIENT_ASSERTION_TYPE = 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer' +const REQUEST_TIMEOUT_MS = 15_000 +/** Microsoft asks for an assertion that expires "5-10 minutes after nbf at most". */ +const CERTIFICATE_ASSERTION_TTL_SECONDS = 300 +const MIN_RSA_MODULUS_BITS = 2048 +const MAX_RSA_MODULUS_BITS = 4096 +const MAX_PEM_LENGTH = 16_384 + +/** Re-mint once less than this much of a token's lifetime remains. */ +const TOKEN_REUSE_MARGIN_MS = 5 * 60 * 1000 +const TOKEN_CACHE_MAX = 10_000 + +const GUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i +/** A verified domain (`contoso.onmicrosoft.com`); `common` and friends have no dot. */ +const TENANT_DOMAIN_PATTERN = + /^(?=.{4,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/ + +/** The Microsoft services that may use this credential, and the resource each one calls. */ +type MicrosoftAppService = 'microsoft-ad' | 'sharepoint' | 'microsoft-dataverse' + +const tenantSchema = z + .string() + .trim() + .toLowerCase() + .refine( + (value) => GUID_PATTERN.test(value) || TENANT_DOMAIN_PATTERN.test(value), + 'Enter the Directory (tenant) ID, a GUID like 00000000-0000-0000-0000-000000000000' + ) + +const clientIdSchema = z + .string() + .trim() + .toLowerCase() + .regex(GUID_PATTERN, 'Enter the Application (client) ID, a GUID') + +const environmentUrlSchema = z + .string() + .trim() + .max(255) + .transform((value, context) => { + try { + return normalizeMicrosoftDataverseEnvironmentUrl(value) + } catch { + context.addIssue({ + code: 'custom', + message: + 'Enter the Dataverse environment URL, like https://contoso.crm.dynamics.com, with no path', + }) + return z.NEVER + } + }) + +const baseShape = { + tenantId: tenantSchema, + clientId: clientIdSchema, + environmentUrl: environmentUrlSchema.optional(), +} + +const pemSchema = (label: string) => + z.string().trim().min(1, `${label} is required`).max(MAX_PEM_LENGTH, `${label} is too large`) + +const clientSecretSchema = z + .object({ + ...baseShape, + authType: z.literal('client_secret'), + clientSecret: z + .string() + .min(1, 'Client secret is required') + .max(1024) + .refine((value) => value.trim().length > 0, 'Client secret is required'), + }) + .strict() + +const certificateSchema = z + .object({ + ...baseShape, + authType: z.literal('certificate'), + privateKey: pemSchema('Private key'), + certificate: pemSchema('Certificate'), + }) + .strict() + +const federatedShape = { + ...baseShape, + authType: z.literal('federated'), + subject: z.string().min(1).max(512), +} + +const storedConfigSchema = z.discriminatedUnion('authType', [ + clientSecretSchema, + certificateSchema, + z.object(federatedShape).strict(), +]) + +type MicrosoftAppConfig = z.infer + +const submittedConfigSchema = z.discriminatedUnion('authType', [ + clientSecretSchema, + certificateSchema, + z + .object({ + ...federatedShape, + subject: federatedShape.subject.optional(), + subjectProof: z.string().min(1).max(512).optional(), + }) + .strict(), +]) + +const storedSecretSchema = z + .object({ type: z.literal(SECRET_TYPE), config: storedConfigSchema }) + .strict() + +/** A configuration problem Sim can name the fix for; its message is shown to the person saving. */ +export class MicrosoftAppCredentialError extends Error { + /** + * @param status The HTTP status Microsoft answered with, when Microsoft itself refused. + * @param aadsts The Entra `AADSTS` error code, when Entra reported one. + */ + constructor( + message: string, + readonly status?: number, + readonly aadsts?: number + ) { + super(message) + this.name = 'MicrosoftAppCredentialError' + } +} + +const FEDERATION_MISMATCH_MESSAGE = + 'No federated credential on this app matches the issuer, subject, and audience Sim presents. Add it with the exact values shown (matching is case-sensitive). A new federated credential can take a few minutes to take effect.' + +/** + * Actionable copy for the Entra errors a person saving the credential can fix. + * AADSTS70021 (no matching federated identity record) is documented in the + * workload identity federation considerations, and AADSTS700213 (no matching + * record for the presented subject, issuer, or audience) in the August 2024 + * breaking-changes entry; any other keyless refusal still names the mismatch. + * @see https://learn.microsoft.com/en-us/entra/identity-platform/reference-error-codes + * @see https://learn.microsoft.com/en-us/entra/workload-id/workload-identity-federation-considerations + * @see https://learn.microsoft.com/en-us/entra/identity-platform/reference-breaking-changes + */ +function entraFailureMessage(aadsts: number | undefined, config: MicrosoftAppConfig): string { + switch (aadsts) { + case 90002: + return 'Microsoft Entra could not find this tenant. Check the Directory (tenant) ID.' + case 700016: + return 'No app with this Application (client) ID exists in the tenant. Check both IDs on the app registration’s Overview page.' + case 7000215: + return 'Microsoft Entra rejected the client secret. Copy the secret’s Value (not its Secret ID) from Certificates & secrets.' + case 7000222: + return 'This client secret has expired. Create a new one under Certificates & secrets.' + case 700027: + return 'Microsoft Entra could not verify the signed assertion. Upload this certificate (the .cer or .pem public part) to the app registration’s Certificates tab.' + case 7000112: + return 'This app registration is disabled in the tenant.' + case 500011: + return config.environmentUrl + ? 'Microsoft Entra does not recognize this Dataverse environment in the tenant. Check the environment URL.' + : 'Microsoft Entra does not recognize the requested resource in this tenant.' + case 70021: + case 700213: + return FEDERATION_MISMATCH_MESSAGE + default: + return config.authType === 'federated' + ? `Microsoft Entra refused the keyless sign-in${aadsts ? ` (AADSTS${aadsts})` : ''}. ${FEDERATION_MISMATCH_MESSAGE}` + : `Microsoft Entra refused the token request${aadsts ? ` (AADSTS${aadsts})` : ''}. Check the tenant ID, client ID, and credential.` + } +} + +function readAadstsCode(payload: { error_codes?: unknown; error_description?: unknown }) { + if (Array.isArray(payload.error_codes) && typeof payload.error_codes[0] === 'number') { + return payload.error_codes[0] + } + const match = + typeof payload.error_description === 'string' + ? /AADSTS(\d+)/.exec(payload.error_description) + : null + return match ? Number(match[1]) : undefined +} + +interface CertificateMaterial { + key: KeyObject + thumbprintS256: string +} + +/** + * Loads the certificate and its private key, refusing a pair Entra would + * reject anyway so the person sees what to fix before anything is sent. + */ +function loadCertificateMaterial( + privateKeyPem: string, + certificatePem: string +): CertificateMaterial { + let certificate: X509Certificate + try { + certificate = new X509Certificate(certificatePem) + } catch { + throw new MicrosoftAppCredentialError( + 'The certificate is not a readable PEM certificate (-----BEGIN CERTIFICATE-----).' + ) + } + let key: KeyObject + try { + key = createPrivateKey(privateKeyPem) + } catch { + throw new MicrosoftAppCredentialError( + 'The private key is not a readable, unencrypted PEM private key.' + ) + } + if (key.asymmetricKeyType !== 'rsa') { + throw new MicrosoftAppCredentialError( + 'Microsoft Entra certificate credentials need an RSA key.' + ) + } + const bits = key.asymmetricKeyDetails?.modulusLength ?? 0 + if (bits < MIN_RSA_MODULUS_BITS || bits > MAX_RSA_MODULUS_BITS) { + throw new MicrosoftAppCredentialError( + `The RSA key is ${bits}-bit; use a 2048- to 4096-bit key.` + ) + } + if (!certificate.checkPrivateKey(key)) { + throw new MicrosoftAppCredentialError('The private key does not belong to this certificate.') + } + if (Date.parse(certificate.validTo) <= Date.now()) { + throw new MicrosoftAppCredentialError( + 'This certificate has expired. Upload a new one to the app registration and save it here.' + ) + } + return { + key, + thumbprintS256: createHash('sha256').update(certificate.raw).digest('base64url'), + } +} + +function tokenEndpoint(tenantId: string): string { + return `${LOGIN_ORIGIN}/${encodeURIComponent(tenantId)}/oauth2/v2.0/token` +} + +/** The PS256 client assertion Microsoft documents for certificate credentials. */ +async function signCertificateAssertion( + config: Extract +): Promise { + const { key, thumbprintS256 } = loadCertificateMaterial(config.privateKey, config.certificate) + const now = Math.floor(Date.now() / 1000) + return new SignJWT({}) + .setProtectedHeader({ alg: 'PS256', typ: 'JWT', 'x5t#S256': thumbprintS256 }) + .setIssuer(config.clientId) + .setSubject(config.clientId) + .setAudience(tokenEndpoint(config.tenantId)) + .setJti(generateId()) + .setIssuedAt(now) + .setNotBefore(now) + .setExpirationTime(now + CERTIFICATE_ASSERTION_TTL_SECONDS) + .sign(key) +} + +function mintFederatedAssertion(subject: string, owner: WorkloadIdentityOwner): Promise { + return mintWorkloadIdentityToken({ + subject, + audience: WORKLOAD_IDENTITY_AUDIENCES.microsoft, + owner, + }) +} + +async function clientAuthentication( + config: MicrosoftAppConfig, + owner: WorkloadIdentityOwner +): Promise> { + if (config.authType === 'client_secret') return { client_secret: config.clientSecret } + const assertion = + config.authType === 'certificate' + ? await signCertificateAssertion(config) + : await mintFederatedAssertion(config.subject, owner) + return { client_assertion_type: CLIENT_ASSERTION_TYPE, client_assertion: assertion } +} + +interface EntraToken { + accessToken: string + expiresInSeconds: number +} + +/** + * Requests an app-only token for one resource (`/.default`) from the + * credential's own tenant. The token endpoint is fixed; only the tenant segment + * comes from the credential, and it was validated when the credential was saved. + */ +async function requestEntraToken( + config: MicrosoftAppConfig, + resource: string, + owner: WorkloadIdentityOwner, + signal?: AbortSignal +): Promise { + const body = new URLSearchParams({ + client_id: config.clientId, + scope: `${resource}/.default`, + grant_type: 'client_credentials', + ...(await clientAuthentication(config, owner)), + }) + const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS) + let response: Response + try { + response = await fetch(tokenEndpoint(config.tenantId), { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' }, + body, + // A secret or assertion must never follow a redirect off the Entra host. + redirect: 'error', + signal: signal ? AbortSignal.any([signal, timeout]) : timeout, + }) + } catch { + signal?.throwIfAborted() + throw new MicrosoftAppCredentialError('Could not reach Microsoft Entra. Try again.') + } + const payload = (await response.json().catch(() => ({}))) as { + access_token?: unknown + expires_in?: unknown + error_codes?: unknown + error_description?: unknown + } + if (!response.ok) { + const aadsts = readAadstsCode(payload) + throw new MicrosoftAppCredentialError( + providerFailureCode(response.status) === 'invalid_credentials' + ? entraFailureMessage(aadsts, config) + : 'Microsoft Entra is unavailable. Try again.', + response.status, + aadsts + ) + } + if (typeof payload.access_token !== 'string' || !payload.access_token) { + throw new MicrosoftAppCredentialError('Microsoft Entra answered without an access token.', 502) + } + const expiresIn = Number(payload.expires_in) + return { + accessToken: payload.access_token, + expiresInSeconds: Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : 3600, + } +} + +async function getJson(url: string, token: string): Promise<{ status: number; body: unknown }> { + const response = await fetch(url, { + headers: { + Authorization: `Bearer ${token}`, + Accept: 'application/json', + 'OData-MaxVersion': '4.0', + 'OData-Version': '4.0', + }, + redirect: 'error', + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + }) + return { status: response.status, body: await response.json().catch(() => ({})) } +} + +/** + * Reads the app's own service principal. Microsoft documents that "a service + * principal can retrieve its own application and service principal details + * without being granted any application permissions", so this proves the + * token without asking for a permission the tools may not need (a SharePoint + * app on Sites.Selected, say). + * @see https://learn.microsoft.com/en-us/graph/api/serviceprincipal-get + */ +async function readOwnServicePrincipal(config: MicrosoftAppConfig, token: string) { + const { status, body } = await getJson( + `${GRAPH_RESOURCE}/v1.0/servicePrincipals(appId='${config.clientId}')?$select=id,appId,displayName`, + token + ) + if (status !== 200) { + throw new MicrosoftAppCredentialError( + status >= 500 + ? 'Microsoft Graph is unavailable. Try again.' + : `Microsoft Graph did not accept the app’s token (HTTP ${status}).`, + status + ) + } + const principal = body as { id?: unknown; displayName?: unknown } + return { + id: typeof principal.id === 'string' ? principal.id : config.clientId, + displayName: typeof principal.displayName === 'string' ? principal.displayName : undefined, + } +} + +/** + * Calls Dataverse `WhoAmI` as the app. A 401/403 means the environment has no + * application user for this app (or it lacks a security role). + * @see https://learn.microsoft.com/en-us/power-platform/admin/manage-application-users + */ +async function verifyDataverseApplicationUser(environmentUrl: string, token: string) { + const { status } = await getJson(`${environmentUrl}/api/data/v9.2/WhoAmI`, token) + if (status === 200) return + if (status === 401 || status === 403) { + throw new MicrosoftAppCredentialError( + 'The app signed in, but the Dataverse environment did not accept it. In the Power Platform admin center, add this app as an application user of the environment and assign it a security role.', + status + ) + } + throw new MicrosoftAppCredentialError( + status >= 500 + ? 'The Dataverse environment is unavailable. Try again.' + : `The Dataverse environment refused the request (HTTP ${status}). Check the environment URL.`, + status + ) +} + +/** Whether a decrypted Microsoft app credential secret is a keyless (federated) one. */ +export function isKeylessMicrosoftAppSecret(decrypted: string): boolean { + try { + const parsed = storedSecretSchema.safeParse(JSON.parse(decrypted)) + return parsed.success && parsed.data.config.authType === 'federated' + } catch { + return false + } +} + +function readStoredSubject(storedSecret: Record | null | undefined) { + const parsed = storedSecretSchema.safeParse(storedSecret) + return parsed.success && parsed.data.config.authType === 'federated' + ? parsed.data.config.subject + : undefined +} + +/** + * Entra matches a federated credential on issuer, subject, and audience, so a + * subject no credential holds must be refused. If it is accepted, the app + * trusts every Sim credential (a flexible federated credential matching on a + * looser claim, say), and saving would let other Sim tenants act as the app. + */ +async function assertFederationPinsSubject( + config: Extract, + owner: WorkloadIdentityOwner +): Promise { + try { + await requestEntraToken( + { ...config, subject: newWorkloadIdentitySubject(owner) }, + GRAPH_RESOURCE, + owner + ) + } catch (error) { + const refused = + error instanceof MicrosoftAppCredentialError && + error.status !== undefined && + providerFailureCode(error.status) === 'invalid_credentials' + if (refused) return + throw new MicrosoftAppCredentialError( + 'Sim could not confirm this app trusts only this credential. Try again.' + ) + } + throw new MicrosoftAppCredentialError( + 'This app also trusts other Sim credentials. Use a federated credential whose subject is exactly the one shown, so only this credential can use it.' + ) +} + +function bindSubject( + subject: string | undefined, + subjectProof: string | undefined, + owner: WorkloadIdentityCredentialOwner +): string { + try { + return bindWorkloadIdentitySubject({ + provider: 'microsoft', + owner, + storedSubject: readStoredSubject(owner.storedSecret), + subject, + subjectProof, + }) + } catch (error) { + if (error instanceof WorkloadIdentitySubjectError) { + throw new MicrosoftAppCredentialError(error.message) + } + throw error + } +} + +export interface MicrosoftAppCredentialSaveResult { + encryptedServiceAccountKey: string + /** The app's service principal display name, or its client ID. */ + displayName: string + /** The app's service principal object ID in the tenant. */ + servicePrincipalId: string + tenantId: string + /** A subject this save binds that the credential did not already hold. */ + newSubject?: string +} + +/** + * Validates the submitted configuration, mints a Microsoft Graph token and + * reads the app's own service principal with it, and, when an environment is + * set, mints a Dataverse token and calls `WhoAmI`. Returns the encrypted blob. + */ +export async function verifyAndEncryptMicrosoftAppCredential( + serialized: string, + owner: WorkloadIdentityCredentialOwner +): Promise { + const parsed = parseServiceAccountConfig( + serialized, + submittedConfigSchema, + 'Microsoft app credential' + ) + if (!parsed.success) throw new MicrosoftAppCredentialError(parsed.message) + const submitted = parsed.data + let config: MicrosoftAppConfig + if (submitted.authType === 'federated') { + if (!(await isWorkloadIdentityConfigured())) { + throw new MicrosoftAppCredentialError( + 'Keyless connections are not available on this deployment. Use a client secret or certificate.' + ) + } + const { subject, subjectProof, ...rest } = submitted + config = { ...rest, subject: bindSubject(subject, subjectProof, owner) } + } else { + config = submitted + } + if (config.authType === 'certificate') { + loadCertificateMaterial(config.privateKey, config.certificate) + } + + const verify = async () => { + const graphToken = await requestEntraToken(config, GRAPH_RESOURCE, owner) + const principal = await readOwnServicePrincipal(config, graphToken.accessToken) + if (config.environmentUrl) { + const dataverseToken = await requestEntraToken(config, config.environmentUrl, owner) + await verifyDataverseApplicationUser(config.environmentUrl, dataverseToken.accessToken) + } + return principal + } + // The subject-pin probe is independent of the verification, so both run at + // once; a verification failure still reports first. + const [verified, pinned] = await Promise.allSettled([ + verify(), + config.authType === 'federated' ? assertFederationPinsSubject(config, owner) : undefined, + ]) + if (verified.status === 'rejected') { + if (verified.reason instanceof MicrosoftAppCredentialError) throw verified.reason + throw new MicrosoftAppCredentialError( + `Could not verify the Microsoft app credential: ${getErrorMessage(verified.reason, 'Unknown error')}` + ) + } + if (pinned.status === 'rejected') throw pinned.reason + + const { encrypted } = await encryptSecret(JSON.stringify({ type: SECRET_TYPE, config })) + return { + encryptedServiceAccountKey: encrypted, + displayName: verified.value.displayName ?? config.clientId, + servicePrincipalId: verified.value.id, + tenantId: config.tenantId, + ...(config.authType === 'federated' && config.subject !== readStoredSubject(owner.storedSecret) + ? { newSubject: config.subject } + : {}), + } +} + +interface CachedToken { + accessToken: string + instanceUrl?: string +} + +/** + * Minted tokens per credential, resource, and stored-secret version: a + * reconnect re-encrypts the secret and so never reuses the old app's token. + */ +const tokenCache = new LRUCache({ max: TOKEN_CACHE_MAX }) + +export interface MicrosoftAppCredentialToken { + accessToken: string + /** The credential's Dataverse environment, for Dataverse and Dynamics 365 tools. */ + instanceUrl?: string +} + +function isMicrosoftAppService(value: string | undefined): value is MicrosoftAppService { + return value === 'microsoft-ad' || value === 'sharepoint' || value === 'microsoft-dataverse' +} + +/** + * Resolves an executor-authorized Microsoft app credential (the executor + * already checked the caller may use it) to a token for the service the tool + * belongs to. The resource is decided by the tool's service, never by caller + * params: Graph for Entra ID and SharePoint, the stored environment for + * Dataverse. Any other service is refused, so a Microsoft block that needs a + * signed-in user can never receive an app-only token. + */ +export async function resolveMicrosoftAppCredentialToken( + credentialId: string, + service: string | undefined, + signal?: AbortSignal +): Promise { + if (!isMicrosoftAppService(service)) { + throw new TokenServiceAccountValidationError('invalid_credentials', 400, { + step: 'microsoft_app_service', + reason: 'this Microsoft service needs a signed-in user, not an app-only credential', + }) + } + const [row] = await db + .select({ + workspaceId: credential.workspaceId, + organizationId: credential.organizationId, + type: credential.type, + providerId: credential.providerId, + revokedAt: credential.revokedAt, + encryptedServiceAccountKey: credential.encryptedServiceAccountKey, + }) + .from(credential) + .where(eq(credential.id, credentialId)) + .limit(1) + if ( + !row || + row.type !== 'service_account' || + row.providerId !== MICROSOFT_APP_SERVICE_ACCOUNT_PROVIDER_ID || + row.revokedAt !== null || + !row.encryptedServiceAccountKey + ) { + throw new MicrosoftAppCredentialError('Microsoft app credential is unavailable') + } + const encryptedKey = row.encryptedServiceAccountKey + const cacheKey = `${credentialId}:${service === 'microsoft-dataverse' ? 'dataverse' : 'graph'}:${encryptedKey.slice(0, 32)}` + const cached = tokenCache.get(cacheKey) + if (cached) return cached + signal?.throwIfAborted() + + // Concurrent block runs share one mint, so it is not tied to any one caller's signal. + return coalesceLocally(`microsoft-app:${cacheKey}`, async () => { + const { decrypted } = await decryptSecret(encryptedKey) + const { config } = storedSecretSchema.parse(JSON.parse(decrypted)) + let resource = GRAPH_RESOURCE + let instanceUrl: string | undefined + if (service === 'microsoft-dataverse') { + if (!config.environmentUrl) { + throw new TokenServiceAccountValidationError('invalid_credentials', 400, { + step: 'microsoft_app_environment', + reason: 'credential has no Dataverse environment; reconnect it with one', + }) + } + resource = config.environmentUrl + instanceUrl = config.environmentUrl + } + const owner: WorkloadIdentityOwner = row.workspaceId + ? { workspaceId: row.workspaceId } + : { organizationId: row.organizationId ?? undefined } + let token: EntraToken + try { + token = await requestEntraToken(config, resource, owner) + } catch (error) { + if (!(error instanceof MicrosoftAppCredentialError)) throw error + // Report in the shared service-account codes: an outage is not a bad credential. + throw new TokenServiceAccountValidationError( + error.status === undefined ? 'provider_unavailable' : providerFailureCode(error.status), + error.status ?? 502, + { step: 'microsoft_app_token', reason: error.aadsts ? `AADSTS${error.aadsts}` : undefined } + ) + } + const value: CachedToken = { accessToken: token.accessToken, instanceUrl } + const ttl = token.expiresInSeconds * 1000 - TOKEN_REUSE_MARGIN_MS + if (ttl > 0) tokenCache.set(cacheKey, value, { ttl }) + return value + }) +} diff --git a/apps/sim/lib/credentials/orchestration/index.ts b/apps/sim/lib/credentials/orchestration/index.ts index 59c45b85677..53e71d79ba1 100644 --- a/apps/sim/lib/credentials/orchestration/index.ts +++ b/apps/sim/lib/credentials/orchestration/index.ts @@ -37,6 +37,7 @@ import { deletePersonalEnvCredentialForUser, deleteWorkspaceEnvCredentials, } from '@/lib/credentials/environment' +import { GOOGLE_WORKLOAD_IDENTITY_SECRET_TYPE } from '@/lib/credentials/google-workload-identity' import { OciCredentialVerificationError } from '@/lib/credentials/oci-api-key-service-account.server' import type { AtlassianProduct, @@ -46,6 +47,7 @@ import { ServiceAccountSecretError, verifyAndBuildServiceAccountSecret, } from '@/lib/credentials/service-account-secret' +import { SNOWFLAKE_SERVICE_ACCOUNT_PROVIDER_ID } from '@/lib/credentials/token-service-accounts/descriptors' import { TokenServiceAccountValidationError } from '@/lib/credentials/token-service-accounts/errors' import { assertReconnectedSubjectUnclaimed, @@ -58,6 +60,7 @@ import { AWS_SERVICE_ACCOUNT_PROVIDER_ID, DATABRICKS_SERVICE_ACCOUNT_PROVIDER_ID, GOOGLE_SERVICE_ACCOUNT_PROVIDER_ID, + MICROSOFT_APP_SERVICE_ACCOUNT_PROVIDER_ID, SLACK_CUSTOM_BOT_PROVIDER_ID, SLACK_CUSTOM_BOT_SECRET_TYPE, } from '@/lib/oauth/types' @@ -175,6 +178,12 @@ function deriveStoredDisplayName(blob: Record | null): string | if (blob.type === GOOGLE_SERVICE_ACCOUNT_KEY_TYPE && typeof blob.client_email === 'string') { return blob.client_email || undefined } + if (blob.type === GOOGLE_WORKLOAD_IDENTITY_SECRET_TYPE) { + const config = blob.config as { serviceAccountEmail?: unknown } | undefined + return typeof config?.serviceAccountEmail === 'string' + ? config.serviceAccountEmail || undefined + : undefined + } return undefined } @@ -345,10 +354,15 @@ export async function updateCredentialRecord( providerId === ATLASSIAN_SERVICE_ACCOUNT_PROVIDER_ID && params.atlassianProduct === undefined const needsStoredUsername = params.username === undefined && isMultiGrantProvider - // A keyless AWS role or Databricks principal keeps its trusted subject across reconnects. + // A keyless AWS role, Databricks principal, Microsoft app, Google service account, or + // Snowflake service user keeps its trusted subject across reconnects. const needsStoredBoundSubject = providerId === AWS_SERVICE_ACCOUNT_PROVIDER_ID || - providerId === DATABRICKS_SERVICE_ACCOUNT_PROVIDER_ID + providerId === GOOGLE_SERVICE_ACCOUNT_PROVIDER_ID || + providerId === DATABRICKS_SERVICE_ACCOUNT_PROVIDER_ID || + providerId === MICROSOFT_APP_SERVICE_ACCOUNT_PROVIDER_ID || + (providerId === SNOWFLAKE_SERVICE_ACCOUNT_PROVIDER_ID && + params.serviceAccountJson !== undefined) // Rotating to a key that belongs to a different principal makes an // identity-derived label (a Google `client_email`, a Slack team name) diff --git a/apps/sim/lib/credentials/service-account-fields.test.ts b/apps/sim/lib/credentials/service-account-fields.test.ts new file mode 100644 index 00000000000..379241cbc17 --- /dev/null +++ b/apps/sim/lib/credentials/service-account-fields.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from 'vitest' +import { getMissingServiceAccountFields } from '@/lib/credentials/service-account-fields' + +describe('required fields for a service-account create', () => { + it('accepts a keyless Snowflake configuration in place of the token and host', () => { + expect( + getMissingServiceAccountFields('snowflake-service-account', { serviceAccountJson: '{}' }) + ).toEqual([]) + }) + + it('still asks a Snowflake create with neither mode for the token and host', () => { + expect(getMissingServiceAccountFields('snowflake-service-account', {})).toEqual( + expect.arrayContaining(['apiToken', 'domain']) + ) + }) + + it('does not let a JSON configuration stand in for another token provider’s token', () => { + expect( + getMissingServiceAccountFields('hubspot-service-account', { serviceAccountJson: '{}' }) + ).toEqual(['apiToken']) + }) +}) diff --git a/apps/sim/lib/credentials/service-account-fields.ts b/apps/sim/lib/credentials/service-account-fields.ts index 62678c4b20a..ea3ae647725 100644 --- a/apps/sim/lib/credentials/service-account-fields.ts +++ b/apps/sim/lib/credentials/service-account-fields.ts @@ -1,10 +1,14 @@ import { CLIENT_CREDENTIAL_ACCOUNT_REQUIRED_FIELDS } from '@/lib/credentials/client-credential-accounts/descriptors' -import { TOKEN_SERVICE_ACCOUNT_REQUIRED_FIELDS } from '@/lib/credentials/token-service-accounts/descriptors' +import { + SNOWFLAKE_SERVICE_ACCOUNT_PROVIDER_ID, + TOKEN_SERVICE_ACCOUNT_REQUIRED_FIELDS, +} from '@/lib/credentials/token-service-accounts/descriptors' import { ATLASSIAN_SERVICE_ACCOUNT_PROVIDER_ID, AWS_SERVICE_ACCOUNT_PROVIDER_ID, DATABRICKS_SERVICE_ACCOUNT_PROVIDER_ID, GOOGLE_SERVICE_ACCOUNT_PROVIDER_ID, + MICROSOFT_APP_SERVICE_ACCOUNT_PROVIDER_ID, OCI_API_KEY_SERVICE_ACCOUNT_PROVIDER_ID, ORACLE_DATABASE_SERVICE_ACCOUNT_PROVIDER_ID, SLACK_CUSTOM_BOT_PROVIDER_ID, @@ -51,6 +55,7 @@ export const SERVICE_ACCOUNT_REQUIRED_FIELDS: Record = { + [SNOWFLAKE_SERVICE_ACCOUNT_PROVIDER_ID]: ['serviceAccountJson'], +} + +function getServiceAccountRequiredFields( providerId: string | null | undefined ): readonly ServiceAccountFieldId[] { return providerId && Object.hasOwn(SERVICE_ACCOUNT_REQUIRED_FIELDS, providerId) ? SERVICE_ACCOUNT_REQUIRED_FIELDS[providerId] : FALLBACK_SERVICE_ACCOUNT_REQUIRED_FIELDS } + +/** + * The required create-body fields a submission is missing: none when it + * completes the provider's keyless alternative, otherwise the provider's own + * required fields that are empty. + */ +export function getMissingServiceAccountFields( + providerId: string | null | undefined, + provided: Partial> +): ServiceAccountFieldId[] { + const keyless = + providerId && Object.hasOwn(KEYLESS_ALTERNATIVE_REQUIRED_FIELDS, providerId) + ? KEYLESS_ALTERNATIVE_REQUIRED_FIELDS[providerId] + : undefined + if (keyless?.every((field) => provided[field])) return [] + return getServiceAccountRequiredFields(providerId).filter((field) => !provided[field]) +} diff --git a/apps/sim/lib/credentials/service-account-provider-ids.ts b/apps/sim/lib/credentials/service-account-provider-ids.ts index dde9710d8b7..918b2525551 100644 --- a/apps/sim/lib/credentials/service-account-provider-ids.ts +++ b/apps/sim/lib/credentials/service-account-provider-ids.ts @@ -11,6 +11,7 @@ import { AWS_SERVICE_ACCOUNT_PROVIDER_ID, DATABRICKS_SERVICE_ACCOUNT_PROVIDER_ID, GOOGLE_SERVICE_ACCOUNT_PROVIDER_ID, + MICROSOFT_APP_SERVICE_ACCOUNT_PROVIDER_ID, OCI_API_KEY_SERVICE_ACCOUNT_PROVIDER_ID, ORACLE_DATABASE_SERVICE_ACCOUNT_PROVIDER_ID, SLACK_CUSTOM_BOT_PROVIDER_ID, @@ -37,6 +38,7 @@ export function asServiceAccountProviderId( value === ORACLE_DATABASE_SERVICE_ACCOUNT_PROVIDER_ID || value === AWS_SERVICE_ACCOUNT_PROVIDER_ID || value === DATABRICKS_SERVICE_ACCOUNT_PROVIDER_ID || + value === MICROSOFT_APP_SERVICE_ACCOUNT_PROVIDER_ID || isTokenServiceAccountProviderId(value) || isClientCredentialAccountProviderId(value) ) { @@ -82,6 +84,7 @@ export function getServiceAccountConnectNoun(providerId: string): string { if (providerId === ORACLE_DATABASE_SERVICE_ACCOUNT_PROVIDER_ID) return 'database connection' if (providerId === AWS_SERVICE_ACCOUNT_PROVIDER_ID) return 'AWS credential' if (providerId === DATABRICKS_SERVICE_ACCOUNT_PROVIDER_ID) return 'Databricks connection' + if (providerId === MICROSOFT_APP_SERVICE_ACCOUNT_PROVIDER_ID) return 'Microsoft app credential' const descriptor = getTokenServiceAccountDescriptor(providerId) ?? getClientCredentialAccountDescriptor(providerId) return descriptor?.connectNoun ?? 'service account' diff --git a/apps/sim/lib/credentials/service-account-secret.ts b/apps/sim/lib/credentials/service-account-secret.ts index e218a5ed9c8..0faaf52a32c 100644 --- a/apps/sim/lib/credentials/service-account-secret.ts +++ b/apps/sim/lib/credentials/service-account-secret.ts @@ -28,6 +28,15 @@ import { verifyAndEncryptDatabricksCredential, } from '@/lib/credentials/databricks-service-account.server' import { slackCustomBotDisplayName } from '@/lib/credentials/display-name' +import { + GoogleWorkloadIdentityError, + isGoogleWorkloadIdentitySubmission, + verifyAndEncryptGoogleWorkloadIdentityCredential, +} from '@/lib/credentials/google-workload-identity.server' +import { + MicrosoftAppCredentialError, + verifyAndEncryptMicrosoftAppCredential, +} from '@/lib/credentials/microsoft-app-service-account.server' import { verifyAndEncryptOciApiKeyCredential } from '@/lib/credentials/oci-api-key-service-account.server' import { verifyAndEncryptOracleDatabaseCredential } from '@/lib/credentials/oracledb-service-account.server' import { @@ -35,9 +44,14 @@ import { serviceAccountPrincipalMetadata, } from '@/lib/credentials/principal' import type { AtlassianProduct } from '@/lib/credentials/service-account-fields' +import { + SnowflakeCredentialError, + verifyAndEncryptSnowflakeKeylessCredential, +} from '@/lib/credentials/snowflake-service-account.server' import { getTokenServiceAccountDescriptor, isTokenServiceAccountProviderId, + SNOWFLAKE_SERVICE_ACCOUNT_PROVIDER_ID, TOKEN_SERVICE_ACCOUNT_SECRET_TYPE, } from '@/lib/credentials/token-service-accounts/descriptors' import { @@ -52,6 +66,7 @@ import { AWS_SERVICE_ACCOUNT_PROVIDER_ID, DATABRICKS_SERVICE_ACCOUNT_PROVIDER_ID, GOOGLE_SERVICE_ACCOUNT_PROVIDER_ID, + MICROSOFT_APP_SERVICE_ACCOUNT_PROVIDER_ID, OCI_API_KEY_SERVICE_ACCOUNT_PROVIDER_ID, ORACLE_DATABASE_SERVICE_ACCOUNT_PROVIDER_ID, SLACK_CUSTOM_BOT_PROVIDER_ID, @@ -105,8 +120,8 @@ export interface ServiceAccountSecretResult { /** Slack custom bot: the derived bot user id (for reaction self-drop). */ botUserId?: string /** - * Keyless AWS or Databricks: a subject this save binds that the credential did - * not already hold, which must not belong to another credential of the owner. + * Keyless AWS, Databricks, Snowflake, Microsoft app, or Google: a subject this save binds that + * the credential did not already hold, which must not belong to another credential of the owner. */ newWorkloadIdentitySubject?: string } @@ -229,6 +244,9 @@ async function buildGoogleServiceAccountSecret( 'serviceAccountJson is required for service account credentials' ) } + if (isGoogleWorkloadIdentitySubmission(serviceAccountJson)) { + return buildGoogleWorkloadIdentitySecret(serviceAccountJson, fields.owner) + } const jsonParseResult = serviceAccountJsonSchema.safeParse(serviceAccountJson) if (!jsonParseResult.success) { throw new ServiceAccountSecretError( @@ -255,6 +273,38 @@ async function buildGoogleServiceAccountSecret( } } +/** A keyless Google Cloud credential: Workload Identity Federation, no stored key. */ +async function buildGoogleWorkloadIdentitySecret( + serviceAccountJson: string, + owner: ServiceAccountSecretFields['owner'] +): Promise { + if (!owner) throw new ServiceAccountSecretError('Google Cloud credential owner is required') + let result + try { + result = await verifyAndEncryptGoogleWorkloadIdentityCredential(serviceAccountJson, owner) + } catch (error) { + if (error instanceof GoogleWorkloadIdentityError) { + throw new ServiceAccountSecretError(error.message) + } + throw new ServiceAccountSecretError( + `Could not verify the Google Cloud keyless credential: ${getErrorMessage(error, 'Unknown error')}` + ) + } + const principal: ServiceAccountPrincipal = { kind: 'user', id: result.serviceAccountEmail } + return { + providerId: GOOGLE_SERVICE_ACCOUNT_PROVIDER_ID, + encryptedServiceAccountKey: result.encryptedServiceAccountKey, + displayName: result.serviceAccountEmail, + auditMetadata: { + googleClientEmail: result.serviceAccountEmail, + googleWorkloadIdentityProvider: result.workloadIdentityProvider, + ...serviceAccountPrincipalMetadata(principal), + }, + principal, + newWorkloadIdentitySubject: result.newSubject, + } +} + async function buildAwsServiceAccountSecret( fields: ServiceAccountSecretFields ): Promise { @@ -309,6 +359,43 @@ async function buildDatabricksServiceAccountSecret( } } +async function buildMicrosoftAppServiceAccountSecret( + fields: ServiceAccountSecretFields +): Promise { + if (!fields.serviceAccountJson) + throw new ServiceAccountSecretError('Microsoft app credential configuration is required') + if (!fields.owner) + throw new ServiceAccountSecretError('Microsoft app credential owner is required') + let result + try { + result = await verifyAndEncryptMicrosoftAppCredential(fields.serviceAccountJson, fields.owner) + } catch (error) { + if (error instanceof MicrosoftAppCredentialError) { + throw new ServiceAccountSecretError(error.message) + } + throw new ServiceAccountSecretError( + `Could not verify the Microsoft app credential: ${getErrorMessage(error, 'Unknown error')}` + ) + } + // The app's service principal is the identity every app-only token acts as. + const principal: ServiceAccountPrincipal = { + kind: 'user', + id: result.servicePrincipalId, + label: result.displayName, + } + return { + providerId: MICROSOFT_APP_SERVICE_ACCOUNT_PROVIDER_ID, + encryptedServiceAccountKey: result.encryptedServiceAccountKey, + displayName: result.displayName, + auditMetadata: { + microsoftTenantId: result.tenantId, + ...serviceAccountPrincipalMetadata(principal), + }, + principal, + newWorkloadIdentitySubject: result.newSubject, + } +} + async function buildOracleDatabaseServiceAccountSecret( fields: ServiceAccountSecretFields ): Promise { @@ -410,6 +497,38 @@ async function buildTokenServiceAccountSecret( } } +/** + * Builds a Snowflake secret. A JSON configuration is the keyless mode (no + * stored secret); otherwise the pasted programmatic access token goes through + * the token-paste builder exactly as before. Snowflake's own refusals keep the + * shared validation codes so callers report them like any token check. + */ +async function buildSnowflakeServiceAccountSecret( + fields: ServiceAccountSecretFields +): Promise { + if (!fields.serviceAccountJson) { + return buildTokenServiceAccountSecret(SNOWFLAKE_SERVICE_ACCOUNT_PROVIDER_ID, fields) + } + if (fields.apiToken) { + throw new ServiceAccountSecretError( + 'Send either a programmatic access token or a keyless configuration, not both' + ) + } + if (!fields.owner) throw new ServiceAccountSecretError('Snowflake credential owner is required') + try { + const result = await verifyAndEncryptSnowflakeKeylessCredential( + fields.serviceAccountJson, + fields.owner + ) + return { providerId: SNOWFLAKE_SERVICE_ACCOUNT_PROVIDER_ID, ...result } + } catch (error) { + if (error instanceof SnowflakeCredentialError) { + throw new ServiceAccountSecretError(error.message) + } + throw error + } +} + /** * Builds a client-credential service-account secret for any provider registered * in `CLIENT_CREDENTIAL_ACCOUNT_DESCRIPTORS`: verifies the provider-specific @@ -507,6 +626,8 @@ const SERVICE_ACCOUNT_SECRET_BUILDERS: Record encryptionMock) +vi.mock('@/lib/core/security/input-validation.server', () => inputValidationMock) + +import { credential } from '@sim/db/schema' +import { env } from '@/lib/core/config/env' +import { + resolveSnowflakeCredentialToken, + verifyAndEncryptSnowflakeKeylessCredential, +} from '@/lib/credentials/snowflake-service-account.server' +import { + SNOWFLAKE_SERVICE_ACCOUNT_PROVIDER_ID, + TOKEN_SERVICE_ACCOUNT_SECRET_TYPE, +} from '@/lib/credentials/token-service-accounts/descriptors' +import { + getWorkloadIdentityIssuer, + getWorkloadIdentityJwks, +} from '@/lib/credentials/workload-identity/issuer' +import { issueWorkloadIdentitySubject } from '@/lib/credentials/workload-identity/subject' + +const HOST = 'myorg-myaccount.snowflakecomputing.com' +const owner = { workspaceId: 'ws-1', actorUserId: 'user-1' } +const secureFetch = inputValidationMockFns.mockSecureFetchWithValidation + +function setEnv(key: string, value: string | undefined) { + Reflect.set(env, key, value) +} + +/** + * Snowflake's side of workload identity federation: the SQL API accepts a + * request only when it carries `WIF.OIDC.` with the federation token type, + * and the JWT verifies against Sim's published keys with Snowflake's audience, + * Sim's issuer, an `iat`, and the subject a service user was created with. + */ +function snowflakeAccountTrusting(trustedSubject: string) { + secureFetch.mockImplementation( + async (_url: string, init: { headers: Record }) => { + const authorization = init.headers.Authorization ?? '' + const isFederation = + init.headers['X-Snowflake-Authorization-Token-Type'] === 'WORKLOAD_IDENTITY_FEDERATION' && + authorization.startsWith('Bearer WIF.OIDC.') + if (!isFederation) return jsonResponse({ message: 'Invalid token type' }, 401) + try { + const { payload } = await jwtVerify( + authorization.slice('Bearer WIF.OIDC.'.length), + createLocalJWKSet(await getWorkloadIdentityJwks()), + { + issuer: getWorkloadIdentityIssuer(), + audience: 'snowflakecomputing.com', + requiredClaims: ['iat'], + } + ) + if (payload.sub !== trustedSubject) throw new Error('no user for this issuer and subject') + } catch { + return jsonResponse({ code: '390144', message: 'Incorrect username or password' }, 401) + } + return jsonResponse({ data: [['SIM_WORKFLOWS', 'MYORG-MYACCOUNT', 'ANALYST']] }) + } + ) +} + +function keylessConfig(fields: Record) { + return JSON.stringify({ authType: 'workload_identity', host: HOST, ...fields }) +} + +async function codeOf(promise: Promise) { + return promise.then( + () => 'saved', + (error: { code?: string; message?: string }) => error.code ?? error.message + ) +} + +beforeAll(() => { + setEnv( + 'WORKLOAD_IDENTITY_SIGNING_KEY', + generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey.export({ + type: 'pkcs8', + format: 'pem', + }) as string + ) + setEnv('WORKLOAD_IDENTITY_ISSUER', 'https://sim.example.com/oidc/workload') +}) + +afterAll(() => { + setEnv('WORKLOAD_IDENTITY_SIGNING_KEY', undefined) + setEnv('WORKLOAD_IDENTITY_ISSUER', undefined) +}) + +beforeEach(() => { + secureFetch.mockReset() + vi.stubGlobal('fetch', vi.fn()) + encryptionMockFns.mockEncryptSecret.mockReset() + encryptionMockFns.mockEncryptSecret.mockResolvedValue({ encrypted: 'ciphertext', iv: 'iv' }) +}) + +describe('saving a keyless Snowflake connection', () => { + it('signs in as the service user created with Sim’s issuer and this credential’s subject', async () => { + const grant = issueWorkloadIdentitySubject('snowflake', owner, owner.actorUserId) + snowflakeAccountTrusting(grant.subject) + + const saved = await verifyAndEncryptSnowflakeKeylessCredential( + keylessConfig({ subject: grant.subject, subjectProof: grant.subjectProof }), + owner + ) + + expect(saved.displayName).toBe('SIM_WORKFLOWS (MYORG-MYACCOUNT)') + expect(saved.newWorkloadIdentitySubject).toBe(grant.subject) + expect(secureFetch.mock.calls[0][0]).toBe(`https://${HOST}/api/v2/statements`) + expect(secureFetch.mock.calls[0][1]).toMatchObject({ maxRedirects: 0 }) + expect(fetch).not.toHaveBeenCalled() + const stored = JSON.parse(encryptionMockFns.mockEncryptSecret.mock.calls[0][0]) + expect(stored.config).toEqual({ + authType: 'workload_identity', + host: HOST, + subject: grant.subject, + }) + }) + + it('reports an account with no user for this issuer and subject as a rejected credential', async () => { + const grant = issueWorkloadIdentitySubject('snowflake', owner, owner.actorUserId) + snowflakeAccountTrusting('sim:workspace:ws-1:credential:someoneelse0000') + + const outcome = await codeOf( + verifyAndEncryptSnowflakeKeylessCredential( + keylessConfig({ subject: grant.subject, subjectProof: grant.subjectProof }), + owner + ) + ) + + expect(outcome).toBe('invalid_credentials') + expect(encryptionMockFns.mockEncryptSecret).not.toHaveBeenCalled() + }) + + it('reports a mistyped account as a bad host, not a rejected credential', async () => { + const grant = issueWorkloadIdentitySubject('snowflake', owner, owner.actorUserId) + secureFetch.mockResolvedValue(new Response('File not Found', { status: 404 })) + + const outcome = await codeOf( + verifyAndEncryptSnowflakeKeylessCredential( + keylessConfig({ subject: grant.subject, subjectProof: grant.subjectProof }), + owner + ) + ) + + expect(outcome).toBe('site_not_found') + }) + + it('does not save when the egress guard refuses the account host', async () => { + const grant = issueWorkloadIdentitySubject('snowflake', owner, owner.actorUserId) + secureFetch.mockRejectedValue(new Error('URL resolves to a blocked address')) + + const outcome = await codeOf( + verifyAndEncryptSnowflakeKeylessCredential( + keylessConfig({ subject: grant.subject, subjectProof: grant.subjectProof }), + owner + ) + ) + + expect(outcome).toBe('provider_unavailable') + expect(fetch).not.toHaveBeenCalled() + expect(encryptionMockFns.mockEncryptSecret).not.toHaveBeenCalled() + }) + + it.each([ + ['no host', { host: '' }], + ['a host outside Snowflake', { host: 'attacker.example.com' }], + ['a lookalike host', { host: `${HOST}.attacker.example.com` }], + ])('refuses %s before sending a token anywhere', async (_case, fields) => { + const grant = issueWorkloadIdentitySubject('snowflake', owner, owner.actorUserId) + + await expect( + verifyAndEncryptSnowflakeKeylessCredential( + keylessConfig({ subject: grant.subject, subjectProof: grant.subjectProof, ...fields }), + owner + ) + ).rejects.toThrow() + expect(secureFetch).not.toHaveBeenCalled() + }) + + it('refuses a subject issued to someone else, so a member cannot borrow another credential’s trust', async () => { + const grant = issueWorkloadIdentitySubject('snowflake', owner, 'another-user') + + await expect( + verifyAndEncryptSnowflakeKeylessCredential( + keylessConfig({ subject: grant.subject, subjectProof: grant.subjectProof }), + owner + ) + ).rejects.toThrow(/belongs to someone else/) + expect(secureFetch).not.toHaveBeenCalled() + }) +}) + +describe('getting a Snowflake token for a run', () => { + function storedCredential(secret: Record) { + resetDbChainMock() + queueTableRows(credential, [ + { workspaceId: 'ws-1', organizationId: null, encryptedServiceAccountKey: 'ciphertext' }, + ]) + encryptionMockFns.mockDecryptSecret.mockResolvedValueOnce({ decrypted: JSON.stringify(secret) }) + } + + it('mints a federation token for a keyless credential’s own subject and host', async () => { + const subject = 'sim:workspace:ws-1:credential:abcdef0123456789' + storedCredential({ + type: 'snowflake_workload_identity_v1', + config: { authType: 'workload_identity', host: HOST, subject }, + }) + + const resolved = await resolveSnowflakeCredentialToken('cred-1') + + expect(resolved).toMatchObject({ domain: HOST, authStyle: 'snowflake-workload-identity' }) + const { payload } = await jwtVerify( + resolved.accessToken, + createLocalJWKSet(await getWorkloadIdentityJwks()), + { issuer: getWorkloadIdentityIssuer(), audience: 'snowflakecomputing.com' } + ) + expect(payload.sub).toBe(subject) + }) + + it('resolves a programmatic access token exactly as before, with no token type', async () => { + storedCredential({ + type: TOKEN_SERVICE_ACCOUNT_SECRET_TYPE, + providerId: SNOWFLAKE_SERVICE_ACCOUNT_PROVIDER_ID, + apiToken: 'pat-secret', + domain: HOST, + }) + + await expect(resolveSnowflakeCredentialToken('cred-1')).resolves.toEqual({ + accessToken: 'pat-secret', + domain: HOST, + providerWorkspaceId: undefined, + }) + }) +}) diff --git a/apps/sim/lib/credentials/snowflake-service-account.server.ts b/apps/sim/lib/credentials/snowflake-service-account.server.ts new file mode 100644 index 00000000000..ab3527283e7 --- /dev/null +++ b/apps/sim/lib/credentials/snowflake-service-account.server.ts @@ -0,0 +1,252 @@ +import { db } from '@sim/db' +import { credential } from '@sim/db/schema' +import { eq } from 'drizzle-orm' +import { z } from 'zod' +import { decryptSecret, encryptSecret } from '@/lib/core/security/encryption' +import { + type ServiceAccountPrincipal, + serviceAccountPrincipalMetadata, +} from '@/lib/credentials/principal' +import { parseServiceAccountConfig } from '@/lib/credentials/service-account-config' +import { SNOWFLAKE_SERVICE_ACCOUNT_PROVIDER_ID } from '@/lib/credentials/token-service-accounts/descriptors' +import { parseTokenServiceAccountSecretBlob } from '@/lib/credentials/token-service-accounts/server' +import { validateSnowflakeWorkloadIdentity } from '@/lib/credentials/token-service-accounts/validators/snowflake' +import { WORKLOAD_IDENTITY_AUDIENCES } from '@/lib/credentials/workload-identity/audiences' +import { + isWorkloadIdentityConfigured, + mintWorkloadIdentityToken, + type WorkloadIdentityOwner, +} from '@/lib/credentials/workload-identity/issuer' +import { + bindWorkloadIdentitySubject, + type WorkloadIdentityCredentialOwner, + WorkloadIdentitySubjectError, +} from '@/lib/credentials/workload-identity/subject' +import { + normalizeSnowflakeHost, + SNOWFLAKE_WORKLOAD_IDENTITY_AUTH_STYLE, +} from '@/tools/snowflake/utils' + +/** + * Keyless Snowflake connections: no secret is stored. Sim signs a short-lived + * OIDC token for the credential's own subject, and the account's service user + * (created with `WORKLOAD_IDENTITY = (TYPE = OIDC ISSUER = … SUBJECT = …)`) + * accepts it through workload identity federation on every SQL API request. + * + * Snowflake matches the exact `ISSUER` + `SUBJECT` pair, unique per account + * (https://docs.snowflake.com/en/user-guide/workload-identity-federation), so + * unlike a Databricks federation policy there is no looser claim match that + * could let another Sim credential's subject in. + * + * Programmatic-access-token credentials share the provider and keep their + * token-paste blob; only the blob type tells the two modes apart. + */ + +const SNOWFLAKE_KEYLESS_SECRET_TYPE = 'snowflake_workload_identity_v1' as const +const SNOWFLAKE_WORKLOAD_IDENTITY_AUDIENCE = WORKLOAD_IDENTITY_AUDIENCES.snowflake + +/** + * Snowflake validates the token on each request, so it only has to outlive one + * tool call. Cortex Analyst reuses it for the SQL it generates after the + * answer, which can take longer than the issuer's five-minute default. + */ +const SNOWFLAKE_TOKEN_TTL_SECONDS = 600 + +const hostSchema = z + .string() + .trim() + .min(1, 'Snowflake account host is required') + .max(255) + .transform((value, context) => { + try { + return new URL(normalizeSnowflakeHost(value)).hostname + } catch { + context.addIssue({ + code: 'custom', + message: 'Enter the account host, like myorg-myaccount.snowflakecomputing.com', + }) + return z.NEVER + } + }) + +const submittedConfigSchema = z + .object({ + authType: z.literal('workload_identity'), + host: hostSchema, + subject: z.string().min(1).max(512).optional(), + subjectProof: z.string().min(1).max(512).optional(), + }) + .strict() + +const storedSecretSchema = z + .object({ + type: z.literal(SNOWFLAKE_KEYLESS_SECRET_TYPE), + config: z + .object({ + authType: z.literal('workload_identity'), + host: z.string().min(1), + subject: z.string().min(1), + }) + .strict(), + metadata: z.record(z.string(), z.string()).optional(), + }) + .strict() + +type StoredConfig = z.infer['config'] + +/** A keyless Snowflake configuration Sim can name the fix for; surfaced to the user as-is. */ +export class SnowflakeCredentialError extends Error { + constructor(message: string) { + super(message) + this.name = 'SnowflakeCredentialError' + } +} + +/** Whether a decrypted Snowflake secret is a keyless configuration rather than a token. */ +export function isKeylessSnowflakeSecret(decrypted: string): boolean { + try { + return storedSecretSchema.safeParse(JSON.parse(decrypted)).success + } catch { + return false + } +} + +function readStoredSubject(storedSecret: Record | null | undefined) { + const parsed = storedSecretSchema.safeParse(storedSecret) + return parsed.success ? parsed.data.config.subject : undefined +} + +function mintSnowflakeToken(subject: string, owner: WorkloadIdentityOwner): Promise { + return mintWorkloadIdentityToken({ + subject, + audience: SNOWFLAKE_WORKLOAD_IDENTITY_AUDIENCE, + owner, + ttlSeconds: SNOWFLAKE_TOKEN_TTL_SECONDS, + }) +} + +export interface SnowflakeKeylessSecret { + encryptedServiceAccountKey: string + displayName: string + auditMetadata: Record + principal: ServiceAccountPrincipal | null + /** A subject this save binds that the credential did not already hold. */ + newWorkloadIdentitySubject?: string +} + +/** + * Validates a keyless configuration, binds its subject to the person saving + * it, proves the account's service user trusts that subject by running the + * identity statement with a freshly minted token, and returns the encrypted + * blob. Snowflake's refusals keep the shared validation codes + * (`invalid_credentials`, `site_not_found`, `provider_unavailable`); only + * configuration Sim itself rejects throws {@link SnowflakeCredentialError}. + */ +export async function verifyAndEncryptSnowflakeKeylessCredential( + serialized: string, + owner: WorkloadIdentityCredentialOwner +): Promise { + const parsed = parseServiceAccountConfig( + serialized, + submittedConfigSchema, + 'Snowflake connection' + ) + if (!parsed.success) throw new SnowflakeCredentialError(parsed.message) + if (!(await isWorkloadIdentityConfigured())) { + throw new SnowflakeCredentialError( + 'Keyless connections are not available on this deployment. Use a programmatic access token.' + ) + } + const { host, subject: submittedSubject, subjectProof } = parsed.data + let subject: string + try { + subject = bindWorkloadIdentitySubject({ + provider: 'snowflake', + owner, + storedSubject: readStoredSubject(owner.storedSecret), + subject: submittedSubject, + subjectProof, + }) + } catch (error) { + if (error instanceof WorkloadIdentitySubjectError) { + throw new SnowflakeCredentialError(error.message) + } + throw error + } + + const validation = await validateSnowflakeWorkloadIdentity({ + domain: host, + subjectToken: await mintSnowflakeToken(subject, owner), + }) + const config: StoredConfig = { + authType: 'workload_identity', + host: validation.normalizedDomain ?? host, + subject, + } + const principalMetadata = serviceAccountPrincipalMetadata(validation.principal) + const { encrypted } = await encryptSecret( + JSON.stringify({ + type: SNOWFLAKE_KEYLESS_SECRET_TYPE, + config, + metadata: { ...validation.storedMetadata, ...principalMetadata }, + }) + ) + return { + encryptedServiceAccountKey: encrypted, + displayName: validation.displayName, + auditMetadata: { ...validation.auditMetadata, ...principalMetadata }, + principal: validation.principal, + ...(subject !== readStoredSubject(owner.storedSecret) + ? { newWorkloadIdentitySubject: subject } + : {}), + } +} + +/** + * Resolves an executor-authorized Snowflake credential (the executor already + * checked the caller may use it) to the token and account host the tools send. + * A programmatic access token resolves exactly as every token-paste credential + * does; a keyless credential mints a token for its own subject and says so in + * `authStyle`, which is the only thing that switches the tools' token type. + */ +export async function resolveSnowflakeCredentialToken(credentialId: string): Promise<{ + accessToken: string + domain?: string + providerWorkspaceId?: string + authStyle?: typeof SNOWFLAKE_WORKLOAD_IDENTITY_AUTH_STYLE +}> { + const [row] = await db + .select({ + workspaceId: credential.workspaceId, + organizationId: credential.organizationId, + encryptedServiceAccountKey: credential.encryptedServiceAccountKey, + }) + .from(credential) + .where(eq(credential.id, credentialId)) + .limit(1) + if (!row?.encryptedServiceAccountKey) { + throw new Error('Token service account secret not found') + } + const { decrypted } = await decryptSecret(row.encryptedServiceAccountKey) + const keyless = storedSecretSchema.safeParse(JSON.parse(decrypted)) + if (!keyless.success) { + const secret = parseTokenServiceAccountSecretBlob( + decrypted, + SNOWFLAKE_SERVICE_ACCOUNT_PROVIDER_ID + ) + return { + accessToken: secret.apiToken, + domain: secret.domain, + providerWorkspaceId: secret.providerWorkspaceId, + } + } + const { host, subject } = keyless.data.config + const owner: WorkloadIdentityOwner = row.workspaceId + ? { workspaceId: row.workspaceId } + : { organizationId: row.organizationId ?? undefined } + return { + accessToken: await mintSnowflakeToken(subject, owner), + domain: host, + authStyle: SNOWFLAKE_WORKLOAD_IDENTITY_AUTH_STYLE, + } +} diff --git a/apps/sim/lib/credentials/token-service-accounts/descriptors.ts b/apps/sim/lib/credentials/token-service-accounts/descriptors.ts index 808684be2ba..d0a55b27403 100644 --- a/apps/sim/lib/credentials/token-service-accounts/descriptors.ts +++ b/apps/sim/lib/credentials/token-service-accounts/descriptors.ts @@ -112,6 +112,8 @@ export const CONVEX_SERVICE_ACCOUNT_PROVIDER_ID = 'convex-service-account' as co export const JUPYTER_SERVICE_ACCOUNT_PROVIDER_ID = 'jupyter-service-account' as const export const GRAFANA_SERVICE_ACCOUNT_PROVIDER_ID = 'grafana-service-account' as const export const GITLAB_SERVICE_ACCOUNT_PROVIDER_ID = 'gitlab-service-account' as const +export const GITHUB_SERVICE_ACCOUNT_PROVIDER_ID = 'github-service-account' as const +export const BITBUCKET_SERVICE_ACCOUNT_PROVIDER_ID = 'bitbucket-service-account' as const export const WHATSAPP_SERVICE_ACCOUNT_PROVIDER_ID = 'whatsapp-service-account' as const export const VERCEL_SERVICE_ACCOUNT_PROVIDER_ID = 'vercel-service-account' as const export const TYPEFORM_SERVICE_ACCOUNT_PROVIDER_ID = 'typeform-service-account' as const @@ -239,6 +241,8 @@ export type TokenServiceAccountProviderId = | typeof JUPYTER_SERVICE_ACCOUNT_PROVIDER_ID | typeof GRAFANA_SERVICE_ACCOUNT_PROVIDER_ID | typeof GITLAB_SERVICE_ACCOUNT_PROVIDER_ID + | typeof GITHUB_SERVICE_ACCOUNT_PROVIDER_ID + | typeof BITBUCKET_SERVICE_ACCOUNT_PROVIDER_ID | typeof WHATSAPP_SERVICE_ACCOUNT_PROVIDER_ID | typeof VERCEL_SERVICE_ACCOUNT_PROVIDER_ID | typeof TYPEFORM_SERVICE_ACCOUNT_PROVIDER_ID @@ -1834,6 +1838,53 @@ export const TOKEN_SERVICE_ACCOUNT_DESCRIPTORS: Record< invalidCredentialsHelp: 'GitLab rejected this token. Check that it is active, has the api or read_api scope, and belongs to the host you entered.', }, + [GITHUB_SERVICE_ACCOUNT_PROVIDER_ID]: { + providerId: GITHUB_SERVICE_ACCOUNT_PROVIDER_ID, + serviceLabel: 'GitHub', + tokenNoun: 'personal access token', + connectNoun: 'personal access token', + fields: [ + { + id: 'apiToken', + label: 'Personal access token', + placeholder: 'github_pat_... or ghp_...', + secret: true, + }, + ], + docsUrl: 'https://docs.sim.ai/integrations/github', + helpText: + 'Use a fine-grained personal access token limited to the repositories the workflow needs, or a classic token with the repo scope. GitHub Enterprise Server hosts are not supported.', + invalidCredentialsHelp: + 'GitHub rejected this token. Check that it has not expired or been revoked, and that it is a personal access token for github.com rather than a GitHub App or Enterprise Server token.', + }, + [BITBUCKET_SERVICE_ACCOUNT_PROVIDER_ID]: { + providerId: BITBUCKET_SERVICE_ACCOUNT_PROVIDER_ID, + serviceLabel: 'Bitbucket', + tokenNoun: 'access token', + connectNoun: 'access token', + fields: [ + { + id: 'apiToken', + label: 'Access token', + placeholder: 'Paste a workspace, project, or repository access token', + secret: true, + }, + { + id: 'providerWorkspaceId', + label: 'Repository', + placeholder: 'my-workspace/my-repository', + secret: false, + hintPattern: /^[A-Za-z0-9][A-Za-z0-9_-]*\/[A-Za-z0-9_-][A-Za-z0-9._-]*$/, + hintMessage: + 'Enter a repository the token can read as workspace/repository, as in bitbucket.org/my-workspace/my-repository.', + }, + ], + docsUrl: 'https://docs.sim.ai/integrations/bitbucket-service-account', + helpText: + 'Use a Bitbucket Cloud workspace, project, or repository access token with at least the repository scope. Enter any repository the token can read, as workspace/repository; Sim reads it once to verify the token.', + invalidCredentialsHelp: + 'Bitbucket rejected this token. Check that it has not expired or been revoked, has the repository scope, and can read the repository you entered.', + }, [GRAFANA_SERVICE_ACCOUNT_PROVIDER_ID]: { providerId: GRAFANA_SERVICE_ACCOUNT_PROVIDER_ID, serviceLabel: 'Grafana', diff --git a/apps/sim/lib/credentials/token-service-accounts/errors.test.ts b/apps/sim/lib/credentials/token-service-accounts/errors.test.ts index 6fbe00ecf22..f12b7bae6e6 100644 --- a/apps/sim/lib/credentials/token-service-accounts/errors.test.ts +++ b/apps/sim/lib/credentials/token-service-accounts/errors.test.ts @@ -1,6 +1,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { fetchProvider, + isHostNotFound, parseProviderJson, readProviderErrorSnippet, TokenServiceAccountValidationError, @@ -64,6 +65,25 @@ describe('token service-account error helpers', () => { }) }) + describe('isHostNotFound', () => { + it('reads ENOTFOUND on the cause even when the outer error carries another code', () => { + const error = Object.assign(new TypeError('fetch failed'), { + code: 'UND_ERR_CONNECT', + cause: Object.assign(new Error('getaddrinfo ENOTFOUND'), { code: 'ENOTFOUND' }), + }) + + expect(isHostNotFound(error)).toBe(true) + }) + + it('does not treat a transient resolver failure as a missing host', () => { + const error = Object.assign(new TypeError('fetch failed'), { + cause: Object.assign(new Error('getaddrinfo EAI_AGAIN'), { code: 'EAI_AGAIN' }), + }) + + expect(isHostNotFound(error)).toBe(false) + }) + }) + describe('parseProviderJson', () => { it('maps a non-JSON body to provider_unavailable 502', async () => { const res = new Response('502 Bad Gateway', { status: 200 }) diff --git a/apps/sim/lib/credentials/token-service-accounts/errors.ts b/apps/sim/lib/credentials/token-service-accounts/errors.ts index e334edb966c..71f1d5255ac 100644 --- a/apps/sim/lib/credentials/token-service-accounts/errors.ts +++ b/apps/sim/lib/credentials/token-service-accounts/errors.ts @@ -15,6 +15,15 @@ export type TokenServiceAccountValidationCode = | 'permission_conflict' | 'site_not_found' | 'provider_unavailable' + /** The provider requires a one-time user consent before it issues tokens (DocuSign JWT Grant). */ + | 'consent_required' + /** The credential authenticated, but the account it pins is not one its user belongs to. */ + | 'account_not_found' + /** + * The credential works, but not for this service or option: a keyless Google Cloud credential + * asked for a Workspace service or to impersonate a user (domain-wide delegation). + */ + | 'unsupported_use' export class TokenServiceAccountValidationError extends Error { constructor( @@ -116,7 +125,7 @@ const PROVIDER_FETCH_TIMEOUT_MS = 10_000 */ export function isHostNotFound(error: unknown): boolean { const failure = error as { code?: unknown; cause?: { code?: unknown } } | undefined - return (failure?.code ?? failure?.cause?.code) === 'ENOTFOUND' + return failure?.code === 'ENOTFOUND' || failure?.cause?.code === 'ENOTFOUND' } export async function fetchProvider( @@ -151,7 +160,10 @@ export async function fetchProvider( * error pages, truncated responses) to `provider_unavailable` instead of an * unhandled SyntaxError that would surface as a generic 500. */ -export async function parseProviderJson(res: Response, step: string): Promise { +export async function parseProviderJson( + res: { json(): Promise }, + step: string +): Promise { try { return (await res.json()) as T } catch { diff --git a/apps/sim/lib/credentials/token-service-accounts/server.ts b/apps/sim/lib/credentials/token-service-accounts/server.ts index 1fbaa9bbce1..e935ef4331c 100644 --- a/apps/sim/lib/credentials/token-service-accounts/server.ts +++ b/apps/sim/lib/credentials/token-service-accounts/server.ts @@ -12,6 +12,7 @@ import { ASHBY_SERVICE_ACCOUNT_PROVIDER_ID, ATTIO_SERVICE_ACCOUNT_PROVIDER_ID, AZURE_DEVOPS_SERVICE_ACCOUNT_PROVIDER_ID, + BITBUCKET_SERVICE_ACCOUNT_PROVIDER_ID, BREX_SERVICE_ACCOUNT_PROVIDER_ID, BRIGHTDATA_SERVICE_ACCOUNT_PROVIDER_ID, BROWSER_USE_SERVICE_ACCOUNT_PROVIDER_ID, @@ -43,6 +44,7 @@ import { FLOW_SERVICE_ACCOUNT_PROVIDER_ID, GAMMA_SERVICE_ACCOUNT_PROVIDER_ID, GAUGE_SERVICE_ACCOUNT_PROVIDER_ID, + GITHUB_SERVICE_ACCOUNT_PROVIDER_ID, GITLAB_SERVICE_ACCOUNT_PROVIDER_ID, GRAFANA_SERVICE_ACCOUNT_PROVIDER_ID, GRAIN_SERVICE_ACCOUNT_PROVIDER_ID, @@ -149,6 +151,7 @@ import { validateApolloServiceAccount, validateAshbyServiceAccount, validateAzureDevOpsServiceAccount, + validateBitbucketServiceAccount, validateBrexServiceAccount, validateBrightDataServiceAccount, validateBrowserUseServiceAccount, @@ -174,6 +177,7 @@ import { validateFirefliesServiceAccount, validateFlintServiceAccount, validateGammaServiceAccount, + validateGitHubServiceAccount, validateGitLabServiceAccount, validateGrafanaServiceAccount, validateGrainServiceAccount, @@ -360,6 +364,7 @@ const TOKEN_SERVICE_ACCOUNT_VALIDATORS: Record< [BUFFER_SERVICE_ACCOUNT_PROVIDER_ID]: validateBufferServiceAccount, [BROWSER_USE_SERVICE_ACCOUNT_PROVIDER_ID]: validateBrowserUseServiceAccount, [BRIGHTDATA_SERVICE_ACCOUNT_PROVIDER_ID]: validateBrightDataServiceAccount, + [BITBUCKET_SERVICE_ACCOUNT_PROVIDER_ID]: validateBitbucketServiceAccount, [BREX_SERVICE_ACCOUNT_PROVIDER_ID]: validateBrexServiceAccount, [APOLLO_SERVICE_ACCOUNT_PROVIDER_ID]: validateApolloServiceAccount, [APIFY_SERVICE_ACCOUNT_PROVIDER_ID]: validateApifyServiceAccount, @@ -378,6 +383,7 @@ const TOKEN_SERVICE_ACCOUNT_VALIDATORS: Record< [DYNATRACE_SERVICE_ACCOUNT_PROVIDER_ID]: validateDynatraceServiceAccount, [EMAILBISON_SERVICE_ACCOUNT_PROVIDER_ID]: validateEmailBisonServiceAccount, [FATHOM_SERVICE_ACCOUNT_PROVIDER_ID]: validateFathomServiceAccount, + [GITHUB_SERVICE_ACCOUNT_PROVIDER_ID]: validateGitHubServiceAccount, [GITLAB_SERVICE_ACCOUNT_PROVIDER_ID]: validateGitLabServiceAccount, [GRAFANA_SERVICE_ACCOUNT_PROVIDER_ID]: validateGrafanaServiceAccount, [GRAIN_SERVICE_ACCOUNT_PROVIDER_ID]: validateGrainServiceAccount, diff --git a/apps/sim/lib/credentials/token-service-accounts/validators/bitbucket.test.ts b/apps/sim/lib/credentials/token-service-accounts/validators/bitbucket.test.ts new file mode 100644 index 00000000000..108e51eed2c --- /dev/null +++ b/apps/sim/lib/credentials/token-service-accounts/validators/bitbucket.test.ts @@ -0,0 +1,80 @@ +/** + * @vitest-environment node + */ +import { jsonResponse } from '@sim/testing/helpers/http' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { validateBitbucketServiceAccount } from '@/lib/credentials/token-service-accounts/validators/token-checks' + +const TOKEN = 'ATCTT3xFfGN0secretvalue' +const repository = { full_name: 'acme/api', slug: 'api' } + +describe('Bitbucket saved access token verification', () => { + const fetch = vi.fn() + + beforeEach(() => { + fetch.mockReset() + vi.stubGlobal('fetch', fetch) + }) + + it("reads the typed repository at Bitbucket's fixed API host", async () => { + fetch.mockResolvedValue(jsonResponse(repository)) + + await expect( + validateBitbucketServiceAccount({ apiToken: TOKEN, providerWorkspaceId: ' acme/api ' }) + ).resolves.toMatchObject({ + displayName: 'Bitbucket (acme/api)', + auditMetadata: { accountId: 'acme/api' }, + }) + expect(fetch).toHaveBeenCalledWith( + 'https://api.bitbucket.org/2.0/repositories/acme/api', + expect.objectContaining({ + redirect: 'error', + headers: expect.objectContaining({ Authorization: `Bearer ${TOKEN}` }), + }) + ) + }) + + it.each([ + ['a repository that climbs out of the workspace', 'acme/..'], + ['a path that climbs further', 'acme/../../user'], + ['a query that rewrites the request', 'acme/api?role=owner'], + ['another host', 'evil.example.com/api'], + ['an encoded separator', 'acme/api%2F..'], + ['a workspace without a repository', 'acme'], + ['nothing at all', ' '], + ])('refuses %s as the repository without calling Bitbucket', async (_, workspace) => { + await expect( + validateBitbucketServiceAccount({ apiToken: TOKEN, providerWorkspaceId: workspace }) + ).rejects.toMatchObject({ code: 'invalid_credentials' }) + expect(fetch).not.toHaveBeenCalled() + }) + + it.each([ + ['a bad, expired, or revoked token', 401], + ['a token without the repository scope', 403], + ['a repository that does not exist or the token cannot reach', 404], + ])('rejects %s as invalid credentials, never echoing the token', async (_, status) => { + fetch.mockResolvedValue( + jsonResponse({ type: 'error', error: { message: 'Token is invalid' } }, status) + ) + + const error = await validateBitbucketServiceAccount({ + apiToken: TOKEN, + providerWorkspaceId: 'acme/api', + }).catch((e) => e) + + expect(error).toMatchObject({ code: 'invalid_credentials' }) + expect(JSON.stringify(error.logDetail)).not.toContain(TOKEN) + }) + + it.each([ + ['an outage', new Response('', { status: 502 })], + ['a reply that is not a repository', jsonResponse({ values: [] })], + ])('reports %s as Bitbucket being unavailable, not as a bad token', async (_, reply) => { + fetch.mockResolvedValue(reply) + + await expect( + validateBitbucketServiceAccount({ apiToken: TOKEN, providerWorkspaceId: 'acme/api' }) + ).rejects.toMatchObject({ code: 'provider_unavailable' }) + }) +}) diff --git a/apps/sim/lib/credentials/token-service-accounts/validators/github.test.ts b/apps/sim/lib/credentials/token-service-accounts/validators/github.test.ts new file mode 100644 index 00000000000..65948808e2a --- /dev/null +++ b/apps/sim/lib/credentials/token-service-accounts/validators/github.test.ts @@ -0,0 +1,64 @@ +/** + * @vitest-environment node + */ +import { jsonResponse } from '@sim/testing/helpers/http' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { validateGitHubServiceAccount } from '@/lib/credentials/token-service-accounts/validators/token-checks' + +const TOKEN = 'github_pat_11ABCDEFG0secretvalue' + +describe('GitHub saved personal access token verification', () => { + const fetch = vi.fn() + + beforeEach(() => { + fetch.mockReset() + vi.stubGlobal('fetch', fetch) + }) + + it('verifies the token against api.github.com as the tools send it and names it by login', async () => { + fetch.mockResolvedValue(jsonResponse({ login: 'octo-bot', id: 1 })) + + await expect(validateGitHubServiceAccount({ apiToken: TOKEN })).resolves.toMatchObject({ + displayName: 'octo-bot (GitHub)', + }) + expect(fetch).toHaveBeenCalledWith( + 'https://api.github.com/user', + expect.objectContaining({ + redirect: 'error', + headers: expect.objectContaining({ + Authorization: `Bearer ${TOKEN}`, + 'User-Agent': 'Sim', + }), + }) + ) + }) + + it.each([ + ['a bad or revoked token', 401, { message: 'Bad credentials' }], + [ + 'a GitHub App installation token, which cannot act as a user', + 403, + { message: 'Resource not accessible by integration' }, + ], + ])('rejects %s as invalid credentials, never echoing the token', async (_, status, body) => { + fetch.mockResolvedValue(jsonResponse(body, status)) + + const error = await validateGitHubServiceAccount({ apiToken: TOKEN }).catch((e) => e) + + expect(error).toMatchObject({ code: 'invalid_credentials' }) + expect(JSON.stringify(error.logDetail)).not.toContain(TOKEN) + expect(error.message).not.toContain(TOKEN) + }) + + it.each([ + ['a rate limit', jsonResponse({ message: 'API rate limit exceeded' }, 429)], + ['an outage', new Response('unicorn', { status: 503 })], + ['a reply that is not a user', jsonResponse({ ok: true })], + ])('reports %s as GitHub being unavailable, not as a bad token', async (_, reply) => { + fetch.mockResolvedValue(reply) + + await expect(validateGitHubServiceAccount({ apiToken: TOKEN })).rejects.toMatchObject({ + code: 'provider_unavailable', + }) + }) +}) diff --git a/apps/sim/lib/credentials/token-service-accounts/validators/snowflake.ts b/apps/sim/lib/credentials/token-service-accounts/validators/snowflake.ts index 1b7a0271cdc..b2de01b700f 100644 --- a/apps/sim/lib/credentials/token-service-accounts/validators/snowflake.ts +++ b/apps/sim/lib/credentials/token-service-accounts/validators/snowflake.ts @@ -1,6 +1,9 @@ +import { secureFetchWithValidation } from '@/lib/core/security/input-validation.server' import { tenantPrincipal, userPrincipal } from '@/lib/credentials/principal' import { fetchProvider, + isHostNotFound, + type ProviderResponse, parseProviderJson, readProviderErrorSnippet, TokenServiceAccountValidationError, @@ -10,7 +13,11 @@ import type { TokenServiceAccountFields, TokenServiceAccountValidationResult, } from '@/lib/credentials/token-service-accounts/server' -import { buildSnowflakeAuthHeaders, normalizeSnowflakeHost } from '@/tools/snowflake/utils' +import { + buildSnowflakeAuthHeaders, + normalizeSnowflakeHost, + SNOWFLAKE_WORKLOAD_IDENTITY_AUTH_STYLE, +} from '@/tools/snowflake/utils' /** * Context functions only — they resolve from the session the token opens and @@ -25,6 +32,9 @@ const IDENTITY_STATEMENT = 'SELECT CURRENT_USER(), CURRENT_ACCOUNT(), CURRENT_RO * the user sees a statement error rather than "network error reaching provider". */ const IDENTITY_STATEMENT_TIMEOUT_SECONDS = 5 +/** Matches `fetchProvider`'s abort on the PAT path. */ +const IDENTITY_FETCH_TIMEOUT_MS = 10_000 +const IDENTITY_MAX_RESPONSE_BYTES = 1024 * 1024 interface SnowflakeStatementApiResponse { message?: string @@ -37,49 +47,49 @@ function cell(row: Array | undefined, index: number): string | un return typeof value === 'string' && value.trim() ? value.trim() : undefined } -/** - * Validates a Snowflake programmatic access token by running a context-only - * statement against the account's SQL API — the same endpoint, headers, and - * host normalization every Sim Snowflake tool uses, so a passing validation - * proves the credential works with the tools as written. - * - * `normalizeSnowflakeHost` is the SSRF guard: it rejects anything that is not - * a bare `*.snowflakecomputing.com`/`.cn` hostname before any outbound fetch. - * - * Snowflake wildcard-resolves `*.snowflakecomputing.com`, so an account that - * does not exist still resolves and answers **404** rather than failing DNS — - * that 404 is what identifies a mistyped host, and without the branch below it - * would be blamed on the provider forever. The DNS mapping is kept only as a - * defensive fallback for hosts outside the wildcard. - */ -export async function validateSnowflakeServiceAccount( - fields: TokenServiceAccountFields -): Promise { - let baseUrl: string +/** Sends the identity statement to the account; the PAT and keyless paths differ only here. */ +type SendIdentityStatement = ( + url: string, + init: { headers: Record; body: string } +) => Promise }> + +/** The account origin, or `site_not_found` before any request when the host is not a Snowflake account host. */ +function accountBaseUrl(domain: string | undefined): string { try { - baseUrl = normalizeSnowflakeHost(fields.domain ?? '') + return normalizeSnowflakeHost(domain ?? '') } catch { throw new TokenServiceAccountValidationError('site_not_found', 400, { step: 'host_validation', - domain: fields.domain, + domain, reason: 'host is not a Snowflake account hostname', }) } +} + +/** + * Runs the context-only identity statement and reads who the token signed in + * as. Shared by both credential modes so they classify Snowflake's answers the + * same way. + * + * Snowflake wildcard-resolves `*.snowflakecomputing.com`, so an account that + * does not exist still resolves and answers **404** rather than failing DNS — + * that 404 is what identifies a mistyped host, and without the branch below it + * would be blamed on the provider forever. + */ +async function verifySnowflakeIdentity( + baseUrl: string, + headers: Record, + send: SendIdentityStatement +): Promise { const domain = new URL(baseUrl).hostname - const res = await fetchProvider( - `${baseUrl}/api/v2/statements`, - { - method: 'POST', - headers: buildSnowflakeAuthHeaders(fields.apiToken), - body: JSON.stringify({ - statement: IDENTITY_STATEMENT, - timeout: IDENTITY_STATEMENT_TIMEOUT_SECONDS, - }), - }, - 'identity_statement', - { dnsFailureCode: 'site_not_found', dnsFailureReason: 'account host does not resolve' } - ) + const res = await send(`${baseUrl}/api/v2/statements`, { + headers, + body: JSON.stringify({ + statement: IDENTITY_STATEMENT, + timeout: IDENTITY_STATEMENT_TIMEOUT_SECONDS, + }), + }) // A wrong account host resolves through Snowflake's wildcard DNS and answers // 404, so it must be reported as a bad host rather than a provider outage. @@ -125,7 +135,7 @@ export async function validateSnowflakeServiceAccount( const metadata = { account, ...(role ? { role } : {}) } return { displayName: user ? `${user} (${account})` : account, - // A PAT belongs to one Snowflake user, so the user is the finest identity + // A token belongs to one Snowflake user, so the user is the finest identity // available; accounts that mask it fall back to the account itself. The // account is carried in metadata rather than the principal's label slot, // which names the human actor. @@ -135,3 +145,68 @@ export async function validateSnowflakeServiceAccount( normalizedDomain: domain, } } + +/** + * Validates a Snowflake programmatic access token by running a context-only + * statement against the account's SQL API — the same endpoint, headers, and + * host normalization every Sim Snowflake tool uses, so a passing validation + * proves the credential works with the tools as written. + * + * `normalizeSnowflakeHost` is the SSRF guard: it rejects anything that is not + * a bare `*.snowflakecomputing.com`/`.cn` hostname before any outbound fetch. + * The DNS mapping is kept only as a defensive fallback for hosts outside + * Snowflake's wildcard. + */ +export async function validateSnowflakeServiceAccount( + fields: TokenServiceAccountFields +): Promise { + return verifySnowflakeIdentity( + accountBaseUrl(fields.domain), + buildSnowflakeAuthHeaders(fields.apiToken), + (url, init) => + fetchProvider(url, { method: 'POST', ...init }, 'identity_statement', { + dnsFailureCode: 'site_not_found', + dnsFailureReason: 'account host does not resolve', + }) + ) +} + +/** + * Verifies a keyless Snowflake connection: the token Sim signed for the + * credential's subject is presented as workload identity federation at the + * account host the credential pins, through the guarded egress path, so it can + * neither be redirected nor reach a private address. + */ +export async function validateSnowflakeWorkloadIdentity(input: { + domain: string + subjectToken: string +}): Promise { + return verifySnowflakeIdentity( + accountBaseUrl(input.domain), + buildSnowflakeAuthHeaders(input.subjectToken, SNOWFLAKE_WORKLOAD_IDENTITY_AUTH_STYLE), + async (url, init) => { + try { + return await secureFetchWithValidation(url, { + profile: 'configuredEndpoint', + method: 'POST', + headers: init.headers, + body: init.body, + timeout: IDENTITY_FETCH_TIMEOUT_MS, + maxRedirects: 0, + maxResponseBytes: IDENTITY_MAX_RESPONSE_BYTES, + logUrlValidationDetails: false, + }) + } catch (error) { + const notFound = isHostNotFound(error) + throw new TokenServiceAccountValidationError( + notFound ? 'site_not_found' : 'provider_unavailable', + notFound ? 400 : 502, + { + step: 'identity_statement', + reason: notFound ? 'account host does not resolve' : 'account host unreachable', + } + ) + } + } + ) +} diff --git a/apps/sim/lib/credentials/token-service-accounts/validators/token-checks.ts b/apps/sim/lib/credentials/token-service-accounts/validators/token-checks.ts index a6c30664cdd..e4f57a094e4 100644 --- a/apps/sim/lib/credentials/token-service-accounts/validators/token-checks.ts +++ b/apps/sim/lib/credentials/token-service-accounts/validators/token-checks.ts @@ -18,6 +18,7 @@ import { } from '@/lib/credentials/token-service-accounts/validators/http' import { buildJupyterAuthHeaders, normalizeJupyterServerUrl } from '@/lib/internal/jupyter/protocol' import { ashbyAuthHeaders } from '@/tools/ashby/utils' +import { BITBUCKET_API_BASE, bitbucketHeaders } from '@/tools/bitbucket/utils' import { checkrHeaders } from '@/tools/checkr/utils' import { convexApiUrl, convexAuthHeaders } from '@/tools/convex/utils' import { buildDynatraceUrl, dynatraceHeaders } from '@/tools/dynatrace/utils' @@ -577,6 +578,74 @@ export const validateGammaServiceAccount = tokenCheckValidator({ }), }) +/** + * GitHub's authenticated-user endpoint is available to fine-grained and classic personal + * access tokens alike (fine-grained tokens need no permission for it): 200 with the token + * owner for a valid token, 401 for a bad one, and 403 for a token that cannot act as a user + * (a GitHub App installation token). Sent with the same host, scheme, and headers as the + * GitHub tools; Enterprise Server hosts are deliberately not offered. + * https://docs.github.com/en/rest/authentication/endpoints-available-for-fine-grained-personal-access-tokens + */ +export const validateGitHubServiceAccount = tokenCheckValidator({ + serviceLabel: 'GitHub', + request: ({ apiToken }) => ({ + url: 'https://api.github.com/user', + headers: { + Authorization: `Bearer ${apiToken}`, + Accept: 'application/vnd.github+json', + 'X-GitHub-Api-Version': '2022-11-28', + 'User-Agent': 'Sim', + }, + }), + acceptsBody: (body) => { + const { login } = toRecord(body) + if (typeof login !== 'string' || !login.trim()) { + throw new TokenServiceAccountValidationError('provider_unavailable', 502, { + step: 'verify', + reason: 'GitHub returned an unexpected user lookup', + }) + } + return { displayName: `${login.trim()} (GitHub)` } + }, +}) + +/** + * A repository as `workspace/repository`: a workspace slug, then a repository slug that + * cannot be `.` or `..`, so neither half can climb out of the request path. + */ +const BITBUCKET_REPOSITORY = /^[A-Za-z0-9][A-Za-z0-9_-]{0,254}\/[A-Za-z0-9_-][A-Za-z0-9._-]{0,61}$/ + +/** + * Bitbucket access tokens belong to a workspace, project, or repository rather than a user, + * so the user endpoints refuse them, and a repository token reaches only its repository. + * Reading one repository the token can see is the request Atlassian documents for all + * three kinds (`GET /2.0/repositories/{workspace}/{repository}` with the `repository` + * scope): 200 with the repository, 401 for a bad token, 403 without the scope, and 404 for + * a repository that does not exist or that the token cannot reach. + * https://support.atlassian.com/bitbucket-cloud/docs/using-access-tokens/ + */ +export const validateBitbucketServiceAccount = tokenCheckValidator({ + serviceLabel: 'Bitbucket', + workspaceId: ({ providerWorkspaceId }) => { + const repository = (providerWorkspaceId ?? '').trim() + if (!BITBUCKET_REPOSITORY.test(repository)) throw new Error('invalid repository') + return repository + }, + request: ({ apiToken, providerWorkspaceId = '' }) => ({ + url: `${BITBUCKET_API_BASE}/repositories/${providerWorkspaceId}`, + headers: bitbucketHeaders(apiToken), + }), + acceptsBody: (body) => { + if (typeof toRecord(body).full_name !== 'string') { + throw new TokenServiceAccountValidationError('provider_unavailable', 502, { + step: 'verify', + reason: 'Bitbucket returned an unexpected repository', + }) + } + return true + }, +}) + /** Scopes that let the GitLab tools call the REST API. */ const GITLAB_API_SCOPES = new Set(['api', 'read_api']) diff --git a/apps/sim/lib/credentials/workload-identity/audiences.ts b/apps/sim/lib/credentials/workload-identity/audiences.ts index 92d5adf1f05..561f9f99e22 100644 --- a/apps/sim/lib/credentials/workload-identity/audiences.ts +++ b/apps/sim/lib/credentials/workload-identity/audiences.ts @@ -1,14 +1,41 @@ /** Relying parties that trust Sim's workload-identity issuer. */ -export const WORKLOAD_IDENTITY_PROVIDERS = ['aws', 'databricks'] as const +export const WORKLOAD_IDENTITY_PROVIDERS = [ + 'aws', + 'databricks', + 'snowflake', + 'microsoft', + 'google', +] as const export type WorkloadIdentityProvider = (typeof WORKLOAD_IDENTITY_PROVIDERS)[number] +/** + * Relying parties that expect one audience for every credential. Google expects + * each credential's own workload identity provider as its audience (see + * `googleWorkloadIdentityAudience`), so it has no entry here. + */ +type FixedAudienceWorkloadIdentityProvider = Exclude + /** * The `aud` claim each relying party expects. AWS STS requires its own client * ID; Databricks federation policies list whatever audience the customer - * enters, so Sim publishes one fixed value for them to paste. + * enters, so Sim publishes one fixed value for them to paste. Snowflake accepts + * `snowflakecomputing.com` without any `OIDC_AUDIENCE_LIST` on the user, so the + * customer's `CREATE USER` names only the issuer and subject. Microsoft Entra + * federated identity credentials take one audience, and Microsoft recommends + * `api://AzureADTokenExchange` + * (https://learn.microsoft.com/en-us/entra/workload-id/workload-identity-federation-create-trust). */ -export const WORKLOAD_IDENTITY_AUDIENCES: Record = { +export const WORKLOAD_IDENTITY_AUDIENCES: Record = { aws: 'sts.amazonaws.com', databricks: 'sim-databricks', + snowflake: 'snowflakecomputing.com', + microsoft: 'api://AzureADTokenExchange', +} + +/** The provider's fixed audience, or undefined when each credential has its own (Google). */ +export function fixedWorkloadIdentityAudience( + provider: WorkloadIdentityProvider +): string | undefined { + return provider === 'google' ? undefined : WORKLOAD_IDENTITY_AUDIENCES[provider] } diff --git a/apps/sim/lib/credentials/workload-identity/subject.test.ts b/apps/sim/lib/credentials/workload-identity/subject.test.ts index 2327ca5a016..bf194a9460a 100644 --- a/apps/sim/lib/credentials/workload-identity/subject.test.ts +++ b/apps/sim/lib/credentials/workload-identity/subject.test.ts @@ -1,13 +1,20 @@ /** * @vitest-environment node */ -import { describe, expect, it } from 'vitest' +import { flattenMockConditions } from '@sim/testing' +import { encryptionMock, encryptionMockFns } from '@sim/testing/mocks/encryption.mock' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@/lib/core/security/encryption', () => encryptionMock) + import { + assertWorkloadIdentitySubjectUnclaimed, bindWorkloadIdentitySubject, issueWorkloadIdentitySubject, verifyWorkloadIdentitySubject, WorkloadIdentitySubjectError, } from '@/lib/credentials/workload-identity/subject' +import type { DbTransaction } from '@/lib/db/types' const owner = { workspaceId: 'ws-1' } const now = Date.UTC(2026, 10, 6) @@ -170,3 +177,112 @@ describe('binding a subject to a saved credential', () => { ).toThrow(WorkloadIdentitySubjectError) }) }) + +describe('keyless subject uniqueness across providers', () => { + const SUBJECT = 'sim:workspace:ws-1:credential:abcdef0123456789' + + interface StoredCredential { + id: string + providerId: string + secret: object + } + + /** + * A transaction whose credential query returns only the rows its provider + * filter admits, so a provider missing from the scan is never checked. + */ + function transactionWith(rows: StoredCredential[]): DbTransaction { + encryptionMockFns.mockDecryptSecret.mockImplementation(async (encrypted: string) => ({ + decrypted: JSON.stringify(rows.find((row) => row.id === encrypted)?.secret), + })) + const tx = { + execute: async () => [], + select: () => ({ + from: () => ({ + where: async (condition: unknown) => { + const providerFilter = flattenMockConditions(condition).find( + (node) => node.type === 'inArray' + ) + const admitted = Array.isArray(providerFilter?.values) ? providerFilter.values : [] + return rows + .filter((row) => admitted.includes(row.providerId)) + .map((row) => ({ + id: row.id, + displayName: row.id, + encryptedServiceAccountKey: row.id, + })) + }, + }), + }), + } + return tx as unknown as DbTransaction + } + + function claim(rows: StoredCredential[]) { + return assertWorkloadIdentitySubjectUnclaimed(transactionWith(rows), { + subject: SUBJECT, + scope: { kind: 'workspace', workspaceId: 'ws-1' }, + }) + } + + beforeEach(() => { + encryptionMockFns.mockDecryptSecret.mockReset() + }) + + it.each([ + { + providerId: 'snowflake-service-account', + secret: { + type: 'snowflake_workload_identity_v1', + config: { + authType: 'workload_identity', + host: 'org-acct.snowflakecomputing.com', + subject: SUBJECT, + }, + }, + }, + { + providerId: 'microsoft-app-service-account', + secret: { + type: 'microsoft_app_credential_v1', + config: { authType: 'federated', tenantId: 't', clientId: 'c', subject: SUBJECT }, + }, + }, + { + providerId: 'google-service-account', + secret: { + type: 'google_workload_identity_v1', + config: { projectNumber: '1', poolId: 'pool', providerId: 'prov', subject: SUBJECT }, + }, + }, + ])( + 'refuses a subject a live $providerId credential already holds', + async ({ providerId, secret }) => { + await expect(claim([{ id: 'held', providerId, secret }])).rejects.toThrow( + /already uses this trust setup/ + ) + } + ) + + it('is not blocked by key-based Google and Snowflake credentials, which hold no subject', async () => { + await expect( + claim([ + { + id: 'json-key', + providerId: 'google-service-account', + secret: { type: 'service_account', client_email: 'sa@p.iam.gserviceaccount.com' }, + }, + { + id: 'pat', + providerId: 'snowflake-service-account', + secret: { type: 'token_service_account', apiToken: 'pat', domain: 'x' }, + }, + { + id: 'client-secret', + providerId: 'microsoft-app-service-account', + secret: { type: 'microsoft_app_credential_v1', config: { authType: 'client_secret' } }, + }, + ]) + ).resolves.toBeUndefined() + }) +}) diff --git a/apps/sim/lib/credentials/workload-identity/subject.ts b/apps/sim/lib/credentials/workload-identity/subject.ts index 63294be40f5..bdc7f1a351f 100644 --- a/apps/sim/lib/credentials/workload-identity/subject.ts +++ b/apps/sim/lib/credentials/workload-identity/subject.ts @@ -9,6 +9,10 @@ import { env } from '@/lib/core/config/env' import type { ResourceScope } from '@/lib/core/resource-scope' import { resourceScopeCondition } from '@/lib/core/resource-scope.server' import { decryptSecret } from '@/lib/core/security/encryption' +import { + SNOWFLAKE_SERVICE_ACCOUNT_PROVIDER_ID, + TOKEN_SERVICE_ACCOUNT_SECRET_TYPE, +} from '@/lib/credentials/token-service-accounts/descriptors' import type { WorkloadIdentityProvider } from '@/lib/credentials/workload-identity/audiences' import type { WorkloadIdentityOwner } from '@/lib/credentials/workload-identity/issuer' import { acquireAdvisoryXactLock } from '@/lib/db/advisory-locks' @@ -16,10 +20,15 @@ import type { DbTransaction } from '@/lib/db/types' import { AWS_SERVICE_ACCOUNT_PROVIDER_ID, DATABRICKS_SERVICE_ACCOUNT_PROVIDER_ID, + GOOGLE_SERVICE_ACCOUNT_PROVIDER_ID, + MICROSOFT_APP_SERVICE_ACCOUNT_PROVIDER_ID, } from '@/lib/oauth/types' const logger = createLogger('WorkloadIdentitySubject') +/** The `type` of a Google JSON key, stored verbatim. */ +const GOOGLE_SERVICE_ACCOUNT_KEY_TYPE = 'service_account' + /** * Credential-scoped workload-identity subjects. * @@ -179,18 +188,31 @@ export function bindWorkloadIdentitySubject(input: { const KEYLESS_PROVIDER_IDS = [ AWS_SERVICE_ACCOUNT_PROVIDER_ID, DATABRICKS_SERVICE_ACCOUNT_PROVIDER_ID, + SNOWFLAKE_SERVICE_ACCOUNT_PROVIDER_ID, + MICROSOFT_APP_SERVICE_ACCOUNT_PROVIDER_ID, + GOOGLE_SERVICE_ACCOUNT_PROVIDER_ID, ] -/** The part of an AWS or Databricks stored secret that can hold a bound subject. */ +/** The part of a keyless provider's stored secret that can hold a bound subject. */ const storedSubjectSchema = z.object({ config: z.object({ subject: z.string().optional() }), }) +/** + * Keyed secrets of those providers that have no `config` at all: a Google JSON + * key and a Snowflake programmatic access token. They hold no subject. + */ +const keyedSecretSchema = z.object({ + type: z.enum([GOOGLE_SERVICE_ACCOUNT_KEY_TYPE, TOKEN_SERVICE_ACCOUNT_SECRET_TYPE]), +}) + /** The subject a stored secret holds, `undefined` for a keyed mode, or `null` when unreadable. */ async function readStoredSubject(encrypted: string): Promise { try { const { decrypted } = await decryptSecret(encrypted) - const parsed = storedSubjectSchema.safeParse(JSON.parse(decrypted)) + const blob: unknown = JSON.parse(decrypted) + if (keyedSecretSchema.safeParse(blob).success) return undefined + const parsed = storedSubjectSchema.safeParse(blob) return parsed.success ? parsed.data.config.subject : null } catch { return null diff --git a/apps/sim/lib/integrations/availability.server.oauth-configured.test.ts b/apps/sim/lib/integrations/availability.server.oauth-configured.test.ts index 89498c2d0ad..b350ea85153 100644 --- a/apps/sim/lib/integrations/availability.server.oauth-configured.test.ts +++ b/apps/sim/lib/integrations/availability.server.oauth-configured.test.ts @@ -14,12 +14,12 @@ setEnv({ afterAll(resetEnvMock) describe('OAuth service availability projection', () => { - it('uses the repository App while the workflow block keeps its API-key path', () => { + it('uses the repository App while the workflow block keeps its saved-token path', () => { expect( getOAuthServiceAvailability([{ providerId: 'github-repositories', authType: 'oauth' }]) ).toEqual([{ providerId: 'github-repositories', available: true }]) - expect(getIntegrationAvailability().find((item) => item.type === 'github_v2')).toMatchObject({ - state: 'ready', + expect(getIntegrationAvailability().find((item) => item.type === 'github_v3')).toMatchObject({ + state: 'limited', oauthAvailable: false, }) }) diff --git a/apps/sim/lib/integrations/availability.server.test.ts b/apps/sim/lib/integrations/availability.server.test.ts index c491cb07a33..35568c9d02a 100644 --- a/apps/sim/lib/integrations/availability.server.test.ts +++ b/apps/sim/lib/integrations/availability.server.test.ts @@ -44,8 +44,12 @@ function availabilityFor( } describe('integration availability', () => { - it('does not infer GitHub repository OAuth readiness from its API-key workflow block', () => { - expect(availabilityFor('github_v2')).toMatchObject({ state: 'ready', oauthAvailable: false }) + it('does not infer GitHub repository OAuth readiness from its saved-token workflow block', () => { + expect(availabilityFor('github_v3')).toMatchObject({ + state: 'limited', + oauthAvailable: false, + serviceAccountAvailable: true, + }) expect( getOAuthServiceAvailability([{ providerId: 'github-repositories', authType: 'oauth' }]) ).toEqual([{ providerId: 'github-repositories', available: false }]) diff --git a/apps/sim/lib/integrations/credential-display.test.ts b/apps/sim/lib/integrations/credential-display.test.ts index b05aae0889f..73ea26193ba 100644 --- a/apps/sim/lib/integrations/credential-display.test.ts +++ b/apps/sim/lib/integrations/credential-display.test.ts @@ -40,8 +40,11 @@ const EXPECTED_COVERAGE: Record = { 'claude-platform-service-account': ['claude-managed-agents'], 'clickup-service-account': ['clickup'], 'coda-service-account': ['coda'], + 'docusign-service-account': ['docusign'], 'fivetran-service-account': ['fivetran'], + 'bitbucket-service-account': ['bitbucket'], 'github-app-installation': ['github'], + 'github-service-account': ['github'], 'google-service-account': [ 'gmail', 'google-bigquery', @@ -99,19 +102,21 @@ const REGISTERED_SERVICE_ACCOUNT_IDS = [ describe('GitHub Search credentials', () => { it('applies GitHub integration policy without changing workflow token authentication', () => { - expect(getIntegrationTypesForOAuthServiceId('github-repositories')).toEqual(['github_v2']) - expect(getIntegrationTypesForOAuthServiceId('GITHUB-REPOSITORIES')).toEqual(['github_v2']) + expect(getIntegrationTypesForOAuthServiceId('github-repositories')).toEqual(['github_v3']) + expect(getIntegrationTypesForOAuthServiceId('GITHUB-REPOSITORIES')).toEqual(['github_v3']) expect(isOAuthServiceAllowedByIntegrationTypes('github-repositories', new Set(['slack']))).toBe( false ) expect( - isOAuthServiceAllowedByIntegrationTypes('github-repositories', new Set(['github_v2'])) + isOAuthServiceAllowedByIntegrationTypes('github-repositories', new Set(['github_v3'])) ).toBe(true) expect(isOAuthServiceAllowedByIntegrationTypes('github-repositories', null)).toBe(true) expect(getIntegrationsForCredentialProvider('github-repositories')).toEqual([ - expect.objectContaining({ slug: 'github', type: 'github_v2', authType: 'api-key' }), + expect.objectContaining({ slug: 'github', type: 'github_v3', authType: 'oauth' }), + ]) + expect(getIntegrationsForCredentialProvider('github-service-account')).toEqual([ + expect.objectContaining({ slug: 'github', type: 'github_v3' }), ]) - expect(getIntegrationsForCredentialProvider('github')).toEqual([]) }) }) @@ -134,6 +139,9 @@ describe('service-account coverage', () => { */ it('agrees with the predicate the Connected list actually filters on', () => { for (const providerId of REGISTERED_SERVICE_ACCOUNT_IDS) { + // GitHub App installations authorize Search, not workflows: they carry GitHub's + // brand and policy but are managed from Search, never the block's Connected list. + if (providerId === 'github-app-installation') continue const covered = new Set(getIntegrationsForCredentialProvider(providerId).map((i) => i.slug)) for (const integration of INTEGRATIONS) { diff --git a/apps/sim/lib/integrations/icon-mapping.ts b/apps/sim/lib/integrations/icon-mapping.ts index 46cbc2ed32f..c9665b70362 100644 --- a/apps/sim/lib/integrations/icon-mapping.ts +++ b/apps/sim/lib/integrations/icon-mapping.ts @@ -429,7 +429,7 @@ export const blockTypeToIconMap: Record = { gauge: GaugeIcon, generic: WebhookIcon, github: GithubIcon, - github_v2: GithubIcon, + github_v3: GithubIcon, gitlab: GitLabIcon, gitlab_v2: GitLabIcon, gmail: GmailIcon, diff --git a/apps/sim/lib/integrations/oauth-service.test.ts b/apps/sim/lib/integrations/oauth-service.test.ts index 0f7e18b5621..e648dd6e776 100644 --- a/apps/sim/lib/integrations/oauth-service.test.ts +++ b/apps/sim/lib/integrations/oauth-service.test.ts @@ -104,7 +104,7 @@ describe('resolveServiceAccountIntegration', () => { it.concurrent('returns null rather than inventing a link for unsupported input', () => { // The handler turns null into "use oauth_get_auth_link instead"; a wrong // match here would send the user to a modal that cannot take their key. - expect(resolveServiceAccountIntegration('github')).toBeNull() + expect(resolveServiceAccountIntegration('spotify')).toBeNull() expect(resolveServiceAccountIntegration('dropbox')).toBeNull() expect(resolveServiceAccountIntegration('')).toBeNull() expect(resolveServiceAccountIntegration(' ')).toBeNull() diff --git a/apps/sim/lib/internal/docusign/client.test.ts b/apps/sim/lib/internal/docusign/client.test.ts new file mode 100644 index 00000000000..a81ae3e772c --- /dev/null +++ b/apps/sim/lib/internal/docusign/client.test.ts @@ -0,0 +1,36 @@ +import { jsonResponse } from '@sim/testing/helpers/http' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { DocuSignClient } from '@/lib/internal/docusign/client' + +const ACCOUNT_BASE = + 'https://na3.docusign.net/restapi/v2.1/accounts/99999999-0000-0000-0000-000000000001' + +const mockFetch = vi.fn() + +describe('DocuSignClient.create', () => { + beforeEach(() => { + vi.stubGlobal('fetch', mockFetch) + }) + + it('uses a credential-bound account base without asking the deployment host for userinfo', async () => { + mockFetch.mockResolvedValueOnce(jsonResponse({ envelopeId: 'env-1' })) + + const client = await DocuSignClient.create('jwt-token', undefined, ACCOUNT_BASE) + await client.json('/envelopes/env-1', { method: 'GET' }, 'label', 'fallback') + + expect(mockFetch).toHaveBeenCalledTimes(1) + expect(mockFetch.mock.calls[0][0]).toBe(`${ACCOUNT_BASE}/envelopes/env-1`) + }) + + it.each([ + 'https://evil.example.com/restapi/v2.1/accounts/99999999-0000-0000-0000-000000000001', + 'https://na3.docusign.net.evil.example.com/restapi/v2.1/accounts/99999999-0000-0000-0000-000000000001', + 'http://na3.docusign.net/restapi/v2.1/accounts/99999999-0000-0000-0000-000000000001', + 'https://na3.docusign.net/restapi/v2.1/accounts/99999999-0000-0000-0000-000000000001/../x', + ])('never sends the token to an account base of the wrong shape: %s', async (base) => { + await expect(DocuSignClient.create('jwt-token', undefined, base)).rejects.toMatchObject({ + status: 400, + }) + expect(mockFetch).not.toHaveBeenCalled() + }) +}) diff --git a/apps/sim/lib/internal/docusign/client.ts b/apps/sim/lib/internal/docusign/client.ts index 3e8894c5950..372762da549 100644 --- a/apps/sim/lib/internal/docusign/client.ts +++ b/apps/sim/lib/internal/docusign/client.ts @@ -5,7 +5,7 @@ import { readResponseToBufferWithLimit, } from '@/lib/core/utils/stream-limits' import { DocuSignOperationError } from '@/lib/internal/docusign/errors' -import { getDocusignOAuthUrl } from '@/lib/oauth/docusign' +import { getDocusignOAuthUrl, parseDocuSignAccountApiBase } from '@/lib/oauth/docusign' const MAX_DOCUSIGN_JSON_BYTES = 2 * 1024 * 1024 export const MAX_DOCUSIGN_DOCUMENT_BYTES = 25 * 1024 * 1024 @@ -60,7 +60,23 @@ export class DocuSignClient { private readonly apiBase: string ) {} - static async create(accessToken: string, signal?: AbortSignal): Promise { + /** + * Binds a client to one account. A JWT Grant credential arrives with + * `accountApiBase` already resolved from its own environment at mint time; an + * OAuth token resolves the user's default account through `/oauth/userinfo` + * on the deployment's DocuSign host. + */ + static async create( + accessToken: string, + signal?: AbortSignal, + accountApiBase?: string + ): Promise { + if (accountApiBase) { + if (!parseDocuSignAccountApiBase(accountApiBase)) { + throw new DocuSignOperationError('DocuSign credential account URL is invalid', 400) + } + return new DocuSignClient(accessToken, accountApiBase) + } const response = await fetchDocusign( getDocusignOAuthUrl('/oauth/userinfo'), { headers: { Authorization: `Bearer ${accessToken}` } }, diff --git a/apps/sim/lib/internal/docusign/execute-tool.ts b/apps/sim/lib/internal/docusign/execute-tool.ts index 5ed0366b6dd..efb75859e48 100644 --- a/apps/sim/lib/internal/docusign/execute-tool.ts +++ b/apps/sim/lib/internal/docusign/execute-tool.ts @@ -19,7 +19,10 @@ import type { InternalToolOperationHandler, } from '@/lib/internal/tool-operations/types' -const auth = { accessToken: z.string().min(1, 'Access token is required') } +const auth = { + accessToken: z.string().min(1, 'Access token is required'), + instanceUrl: z.string().optional(), +} const schemas = { docusign_create_from_template: z.object({ ...auth, diff --git a/apps/sim/lib/internal/docusign/operations.ts b/apps/sim/lib/internal/docusign/operations.ts index 156a92bbf86..e525b66da99 100644 --- a/apps/sim/lib/internal/docusign/operations.ts +++ b/apps/sim/lib/internal/docusign/operations.ts @@ -37,8 +37,11 @@ function jsonBody(data: Record): RequestInit { return { method: 'POST', body: JSON.stringify(data) } } -async function client(accessToken: string, signal?: AbortSignal): Promise { - return DocuSignClient.create(accessToken, signal) +async function client( + input: { accessToken: string; instanceUrl?: string }, + signal?: AbortSignal +): Promise { + return DocuSignClient.create(input.accessToken, signal, input.instanceUrl) } export async function executeDocuSignCreateFromTemplate( @@ -61,7 +64,7 @@ export async function executeDocuSignCreateFromTemplate( } if (input.emailSubject) body.emailSubject = input.emailSubject if (input.emailBody) body.emailBlurb = input.emailBody - const provider = await client(input.accessToken, context.signal) + const provider = await client(input, context.signal) return provider.json( '/envelopes', jsonBody(body), @@ -174,7 +177,7 @@ export async function executeDocuSignSendEnvelope( }, ] } - const provider = await client(input.accessToken, context.signal) + const provider = await client(input, context.signal) return provider.json( '/envelopes', jsonBody(envelope), @@ -188,7 +191,7 @@ export async function executeDocuSignGetEnvelope( input: DocuSignGetEnvelopeParams, context: DocuSignOperationContext ) { - const provider = await client(input.accessToken, context.signal) + const provider = await client(input, context.signal) return provider.json( `/envelopes/${input.envelopeId.trim()}?include=recipients,documents`, {}, @@ -213,7 +216,7 @@ export async function executeDocuSignListEnvelopes( if (input.envelopeStatus) query.append('status', input.envelopeStatus) if (input.searchText) query.append('search_text', input.searchText) if (input.count) query.append('count', input.count) - const provider = await client(input.accessToken, context.signal) + const provider = await client(input, context.signal) return provider.json( `/envelopes?${query}`, {}, @@ -227,7 +230,7 @@ export async function executeDocuSignVoidEnvelope( input: DocuSignVoidEnvelopeParams, context: DocuSignOperationContext ) { - const provider = await client(input.accessToken, context.signal) + const provider = await client(input, context.signal) await provider.json( `/envelopes/${input.envelopeId.trim()}`, { method: 'PUT', body: JSON.stringify({ status: 'voided', voidedReason: input.voidedReason }) }, @@ -243,7 +246,7 @@ export async function executeDocuSignDownloadDocument( context: DocuSignOperationContext ) { const documentId = input.documentId || 'combined' - const provider = await client(input.accessToken, context.signal) + const provider = await client(input, context.signal) const { buffer, contentType, fileName } = await provider.document( input.envelopeId.trim(), documentId, @@ -279,7 +282,7 @@ export async function executeDocuSignListTemplates( if (input.searchText) query.append('search_text', input.searchText) if (input.count) query.append('count', input.count) const suffix = query.size ? `?${query}` : '' - const provider = await client(input.accessToken, context.signal) + const provider = await client(input, context.signal) return provider.json( `/templates${suffix}`, {}, @@ -293,7 +296,7 @@ export async function executeDocuSignListRecipients( input: DocuSignListRecipientsParams, context: DocuSignOperationContext ) { - const provider = await client(input.accessToken, context.signal) + const provider = await client(input, context.signal) return provider.json( `/envelopes/${input.envelopeId.trim()}/recipients`, {}, diff --git a/apps/sim/lib/internal/llm/credentials.ts b/apps/sim/lib/internal/llm/credentials.ts index 4c450190600..a6b5f09a7d4 100644 --- a/apps/sim/lib/internal/llm/credentials.ts +++ b/apps/sim/lib/internal/llm/credentials.ts @@ -21,9 +21,12 @@ export async function resolveVertexAccessToken( if (!resolved) throw new Error(`Vertex AI credential not found: ${credentialId}`) if (resolved.credentialType === 'service_account' && resolved.credentialId) { - const accessToken = await getServiceAccountToken(resolved.credentialId, [ - 'https://www.googleapis.com/auth/cloud-platform', - ]) + const accessToken = await getServiceAccountToken( + resolved.credentialId, + ['https://www.googleapis.com/auth/cloud-platform'], + undefined, + { service: 'vertex-ai' } + ) logger.info('Resolved Vertex AI service account credential', { requestId }) return accessToken } diff --git a/apps/sim/lib/knowledge/application/connectors.test.ts b/apps/sim/lib/knowledge/application/connectors.test.ts index 630893c5e51..2156453d5a2 100644 --- a/apps/sim/lib/knowledge/application/connectors.test.ts +++ b/apps/sim/lib/knowledge/application/connectors.test.ts @@ -388,7 +388,8 @@ describe('knowledge connector application use cases', () => { 'https://www.googleapis.com/auth/admin.directory.domain.readonly', ] : ['https://www.googleapis.com/auth/drive.readonly'], - 'admin@corp.com' + 'admin@corp.com', + { service: 'google-drive' } ) } ) @@ -993,7 +994,8 @@ describe('organization connector credential authorization', () => { googleDriveConnectorMeta.auth.mode === 'oauth' ? googleDriveConnectorMeta.auth.adminServiceAccountScopes : undefined, - 'admin@corp.com' + 'admin@corp.com', + { service: 'google-drive' } ) }) diff --git a/apps/sim/lib/knowledge/connectors/access-token.test.ts b/apps/sim/lib/knowledge/connectors/access-token.test.ts index 00414a3dcd1..0674996d174 100644 --- a/apps/sim/lib/knowledge/connectors/access-token.test.ts +++ b/apps/sim/lib/knowledge/connectors/access-token.test.ts @@ -53,6 +53,29 @@ describe('resolveConnectorAccessToken', () => { mockResolveTokenBundle.mockResolvedValue({ accessToken: 'access-token' }) }) + it("seeds a minted credential's bound account into the sync context, and nothing for OAuth", async () => { + const bound = + 'https://na3.docusign.net/restapi/v2.1/accounts/99999999-0000-0000-0000-000000000002' + const resolveDocuSign = () => + resolveConnectorAccessToken({ + auth: { mode: 'oauth', provider: 'docusign', requiredScopes: ['signature'] }, + connector: credentialConnector('docusign-credential'), + userId: 'user-1', + requestId: 'req-1', + sourceConfig: {}, + }) + + mockResolveTokenBundle.mockResolvedValueOnce({ accessToken: 'jwt-token', instanceUrl: bound }) + const jwtToken = await resolveDocuSign() + if (!jwtToken) throw new Error('Expected a JWT Grant connector token') + expect(syncContextForToken(jwtToken)).toEqual({ credentialInstanceUrl: bound }) + + mockResolveTokenBundle.mockResolvedValueOnce({ accessToken: 'oauth-token' }) + const oauthToken = await resolveDocuSign() + if (!oauthToken) throw new Error('Expected an OAuth connector token') + expect(syncContextForToken(oauthToken)).toEqual({}) + }) + it('does not accept an undeclared key alternative on other OAuth connectors', async () => { await expect( resolveConnectorAccessToken({ @@ -164,7 +187,8 @@ describe('delegated connector access', () => { 'actor', 'request', delegationAuth.adminServiceAccountScopes, - 'admin@example.com' + 'admin@example.com', + { service: 'google-drive' } ) await expect(token?.getDelegatedAccessToken?.(' Employee@Example.com ')).resolves.toBe( 'user-drive-token' @@ -273,7 +297,8 @@ describe.each([ 'actor', 'request', [directoryScope], - 'directory.admin@example.com' + 'directory.admin@example.com', + { service: auth.mode === 'oauth' ? auth.provider : undefined } ) expect(token?.getDelegatedAccessToken).toBeTypeOf('function') await expect(token?.getDelegatedAccessToken?.(' Employee@Example.com ')).resolves.toBe( @@ -332,7 +357,8 @@ describe('impersonation on the connector path', () => { 'credential-owner', 'req-1', OAUTH_AUTH.requiredScopes, - 'admin@corp.com' + 'admin@corp.com', + { service: 'google-drive' } ) }) }) diff --git a/apps/sim/lib/knowledge/connectors/access-token.ts b/apps/sim/lib/knowledge/connectors/access-token.ts index 219303a9321..0464a520749 100644 --- a/apps/sim/lib/knowledge/connectors/access-token.ts +++ b/apps/sim/lib/knowledge/connectors/access-token.ts @@ -29,6 +29,11 @@ export interface ConnectorAccessToken { cloudId?: string /** The trusted site domain belonging to the credential's cloud id. */ domain?: string + /** + * The provider API base a minted service-account token is bound to (a + * DocuSign JWT Grant credential's account). Never present for OAuth. + */ + instanceUrl?: string /** Server-only capability bound to this credential and the connector's declared scopes. */ getDelegatedAccessToken?: (subject: string, signal?: AbortSignal) => Promise } @@ -139,14 +144,11 @@ export async function resolveConnectorAccessToken(params: { requestId, connectorServiceAccountScopes(auth, params.accessMode), subject, - ...(githubRepositoryScope || params.signal - ? [ - { - ...(githubRepositoryScope ? { githubRepositoryScope } : {}), - ...(params.signal ? { signal: params.signal } : {}), - }, - ] - : []) + { + service: auth.provider, + ...(githubRepositoryScope ? { githubRepositoryScope } : {}), + ...(params.signal ? { signal: params.signal } : {}), + } ) if (!bundle?.accessToken) return null @@ -190,6 +192,7 @@ export async function resolveConnectorAccessToken(params: { ...(bundle.cloudId ? { cloudId: bundle.cloudId, ...(bundle.domain ? { domain: bundle.domain } : {}) } : {}), + ...(bundle.instanceUrl ? { instanceUrl: bundle.instanceUrl } : {}), } } @@ -232,6 +235,7 @@ export function syncContextForToken(token: ConnectorAccessToken): Record { const adapted = projectAssistantConnectedAccountTool(getIssueV2Tool) expect(adapted).not.toBe(getIssueV2Tool) expect(getIssueV2Tool.params.apiKey.required).toBe(true) - expect(getIssueV2Tool.oauth).toBeUndefined() + expect(getIssueV2Tool.oauth).toMatchObject({ provider: 'github-token', required: false }) expect(adapted.oauth).toMatchObject({ required: true, provider: 'github-repositories', diff --git a/apps/sim/lib/mothership/assistant/connected-account-tool.ts b/apps/sim/lib/mothership/assistant/connected-account-tool.ts index 910b40bf8ce..9e93979e505 100644 --- a/apps/sim/lib/mothership/assistant/connected-account-tool.ts +++ b/apps/sim/lib/mothership/assistant/connected-account-tool.ts @@ -1,8 +1,14 @@ import type { ToolMetadata } from '@/tools/metadata' +import { GITHUB_CREDENTIAL_OAUTH } from '@/tools/shared/saved-credentials' -/** Adapt legacy GitHub API-token operations only at the Assistant boundary; Build schemas stay unchanged. */ +/** + * Adapt GitHub API-token operations only at the Assistant boundary; Build schemas stay unchanged. + * Their optional saved-token policy (`github-token` service accounts) is a workflow credential, so the + * Assistant still swaps it for the person's own connected account. + */ export function projectAssistantConnectedAccountTool(tool: T): T { - if (!/^github_[a-z0-9_]+$/.test(tool.id) || !tool.params.apiKey || tool.oauth) return tool + if (!/^github_[a-z0-9_]+$/.test(tool.id) || !tool.params.apiKey) return tool + if (tool.oauth && tool.oauth.provider !== GITHUB_CREDENTIAL_OAUTH.provider) return tool return { ...tool, oauth: { diff --git a/apps/sim/lib/mothership/generated/docs-manifest.ts b/apps/sim/lib/mothership/generated/docs-manifest.ts index ac5992e9c3a..4c5d21144ed 100644 --- a/apps/sim/lib/mothership/generated/docs-manifest.ts +++ b/apps/sim/lib/mothership/generated/docs-manifest.ts @@ -92,6 +92,7 @@ export const DOCS_MANIFEST: readonly string[] = [ 'integrations/aws-credentials.mdx', 'integrations/azure_data_explorer.mdx', 'integrations/azure_devops.mdx', + 'integrations/bitbucket-service-account.mdx', 'integrations/bitbucket.mdx', 'integrations/box-service-account.mdx', 'integrations/box.mdx', @@ -132,6 +133,7 @@ export const DOCS_MANIFEST: readonly string[] = [ 'integrations/deployments.mdx', 'integrations/devin.mdx', 'integrations/discord.mdx', + 'integrations/docusign-service-account.mdx', 'integrations/docusign.mdx', 'integrations/downdetector.mdx', 'integrations/dropbox.mdx', @@ -239,6 +241,7 @@ export const DOCS_MANIFEST: readonly string[] = [ 'integrations/manageengine_sdp.mdx', 'integrations/mem0.mdx', 'integrations/memory.mdx', + 'integrations/microsoft-app-credentials.mdx', 'integrations/microsoft_ad.mdx', 'integrations/microsoft_dataverse.mdx', 'integrations/microsoft_dynamics_365.mdx', diff --git a/apps/sim/lib/oauth/credential-service.test.ts b/apps/sim/lib/oauth/credential-service.test.ts index 7043f128245..4d04f3b1f2a 100644 --- a/apps/sim/lib/oauth/credential-service.test.ts +++ b/apps/sim/lib/oauth/credential-service.test.ts @@ -30,6 +30,10 @@ vi.mock('@/lib/concurrency/leader-lock', () => ({ })) vi.mock('@/lib/core/security/encryption', () => encryptionMock) +vi.mock('@/lib/credentials/workload-identity/issuer', () => ({ + isWorkloadIdentityConfigured: async () => true, + mintWorkloadIdentityToken: async ({ subject }: { subject: string }) => `sim-oidc|${subject}`, +})) vi.mock('@/lib/oauth/instagram', () => ({ isInstagramProvider: vi.fn(() => false), @@ -1210,6 +1214,90 @@ describe('Google service-account token minting', () => { }) expect(JSON.stringify(loggedCalls('error'))).not.toContain('xxxx') }) + + it('signs the same JSON-key request whether or not the caller names its service', async () => { + queueTableRows(credential, [row]) + await getServiceAccountToken('credential-1', [driveScope], 'member@example.com') + queueTableRows(credential, [row]) + await getServiceAccountToken('credential-1', [driveScope], 'member@example.com', { + service: 'google-drive', + }) + + const [withoutService, withService] = fetchMock.mock.calls.map(([url, init]) => [ + String(url), + String(init?.body), + ]) + expect(fetchMock).toHaveBeenCalledTimes(2) + expect(withService).toEqual(withoutService) + }) + + describe('a keyless credential', () => { + const keylessSecret = { + decrypted: JSON.stringify({ + type: 'google_workload_identity_v1', + config: { + projectNumber: '123456789012', + poolId: 'sim-pool', + providerId: 'sim-oidc', + serviceAccountEmail: 'bq-runner@analytics-prod.iam.gserviceaccount.com', + subject: 'sim:workspace:ws-1:credential:abcdef0123456789', + }, + }), + } + + it('refuses an impersonated Workspace user instead of signing a delegation JWT', async () => { + queueTableRows(credential, [row]) + mocks.decryptSecret.mockResolvedValue(keylessSecret) + + await expect( + getServiceAccountToken('credential-1', [driveScope], 'member@example.com', { + service: 'google-bigquery', + }) + ).rejects.toMatchObject({ code: 'unsupported_use' }) + expect(fetchMock).not.toHaveBeenCalled() + }) + + it('mints through federation, not a JWT, for the BigQuery tool the resolver dispatches', async () => { + queueTableRows(credential, [row]) + mocks.decryptSecret.mockResolvedValue(keylessSecret) + fetchMock.mockImplementation(async (input) => + String(input).startsWith('https://sts.googleapis.com/') + ? Response.json({ access_token: 'federated-token' }) + : Response.json({ accessToken: 'bigquery-token', expireTime: '2026-09-09T19:00:00Z' }) + ) + const bigQueryScope = 'https://www.googleapis.com/auth/bigquery' + + await expect( + resolveServiceAccountToken( + 'credential-keyless', + GOOGLE_SERVICE_ACCOUNT_PROVIDER_ID, + [bigQueryScope], + undefined, + { service: 'google-bigquery' } + ) + ).resolves.toEqual({ accessToken: 'bigquery-token' }) + expect(fetchMock.mock.calls.map(([input]) => String(input))).toEqual([ + 'https://sts.googleapis.com/v1/token', + 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/bq-runner%40analytics-prod.iam.gserviceaccount.com:generateAccessToken', + ]) + }) + + it('refuses a Workspace tool the resolver dispatches to it', async () => { + queueTableRows(credential, [row]) + mocks.decryptSecret.mockResolvedValue(keylessSecret) + + await expect( + resolveServiceAccountToken( + 'credential-1', + GOOGLE_SERVICE_ACCOUNT_PROVIDER_ID, + [driveScope], + undefined, + { service: 'google-drive' } + ) + ).rejects.toMatchObject({ code: 'unsupported_use' }) + expect(fetchMock).not.toHaveBeenCalled() + }) + }) }) describe('getCredentialTerminalRefreshError', () => { diff --git a/apps/sim/lib/oauth/credential-service.ts b/apps/sim/lib/oauth/credential-service.ts index d703e3b98a4..ec263abf4d6 100644 --- a/apps/sim/lib/oauth/credential-service.ts +++ b/apps/sim/lib/oauth/credential-service.ts @@ -18,9 +18,11 @@ import { getClientCredentialAccountMinter, parseClientCredentialAccountSecretBlob, } from '@/lib/credentials/client-credential-accounts/server' +import { isGoogleWorkloadIdentitySecret } from '@/lib/credentials/google-workload-identity' import { getTokenServiceAccountDescriptor, isTokenServiceAccountProviderId, + SNOWFLAKE_SERVICE_ACCOUNT_PROVIDER_ID, } from '@/lib/credentials/token-service-accounts/descriptors' import { parseTokenServiceAccountSecretBlob, @@ -71,6 +73,7 @@ import { AWS_SERVICE_ACCOUNT_PROVIDER_ID, DATABRICKS_SERVICE_ACCOUNT_PROVIDER_ID, GOOGLE_SERVICE_ACCOUNT_PROVIDER_ID, + MICROSOFT_APP_SERVICE_ACCOUNT_PROVIDER_ID, OCI_API_KEY_SERVICE_ACCOUNT_PROVIDER_ID, ORACLE_DATABASE_SERVICE_ACCOUNT_PROVIDER_ID, SLACK_CUSTOM_BOT_PROVIDER_ID, @@ -93,6 +96,13 @@ export interface CredentialTokenResolutionOptions { privacyMode?: 'selector' /** GitHub installation content tokens may only address one connector repository. */ githubRepositoryScope?: GitHubInstallationRepositoryScope + /** + * The OAuth service the token is for, set only from server-side policy (a tool's validated + * policy, a selector's or connector's own definition), never from the caller. A Microsoft app + * credential mints for that service's resource and refuses any other; a keyless Google + * credential refuses any service that is not a Google Cloud API. + */ + service?: string /** * Cancels supported service-account token exchanges and retry waits, and stops this caller * waiting on an OAuth refresh without cancelling the refresh other callers share. @@ -232,10 +242,19 @@ const SA_DIAGNOSTIC_ERROR_CODES = new Set([ * delegated subject) share one query and decrypt; a later read queries again, so it sees a * revocation recorded since. Sharing also bounds a hung read by the coalescing settle timeout. */ -function readGoogleServiceAccountKey(credentialId: string): Promise { +interface GoogleServiceAccountSecret { + decrypted: string + /** Changes whenever the stored secret is re-encrypted. */ + secretVersion: string + owner: { workspaceId?: string; organizationId?: string } +} + +function readGoogleServiceAccountKey(credentialId: string): Promise { return coalesceLocally(`sa-key:${credentialId}`, async () => { const [credentialRow] = await db .select({ + workspaceId: credential.workspaceId, + organizationId: credential.organizationId, type: credential.type, providerId: credential.providerId, revokedAt: credential.revokedAt, @@ -255,7 +274,13 @@ function readGoogleServiceAccountKey(credentialId: string): Promise { } const { decrypted } = await decryptSecret(credentialRow.encryptedServiceAccountKey) - return decrypted + return { + decrypted, + secretVersion: credentialRow.encryptedServiceAccountKey.slice(0, 32), + owner: credentialRow.workspaceId + ? { workspaceId: credentialRow.workspaceId } + : { organizationId: credentialRow.organizationId ?? undefined }, + } }) } @@ -275,15 +300,36 @@ export async function getServiceAccountToken( options?: CredentialTokenResolutionOptions ): Promise { options?.signal?.throwIfAborted() - const decrypted = await waitWithAbort(readGoogleServiceAccountKey(credentialId), options?.signal) + const { decrypted, secretVersion, owner } = await waitWithAbort( + readGoogleServiceAccountKey(credentialId), + options?.signal + ) + const filteredScopes = scopes.filter((s) => !SA_EXCLUDED_SCOPES.has(s)) + + if (isGoogleWorkloadIdentitySecret(decrypted)) { + const { resolveGoogleWorkloadIdentityToken } = await import( + '@/lib/credentials/google-workload-identity.server' + ) + return waitWithAbort( + resolveGoogleWorkloadIdentityToken({ + credentialId, + decrypted, + secretVersion, + owner, + scopes: filteredScopes, + impersonateEmail, + service: options?.service, + }), + options?.signal + ) + } + const keyData = JSON.parse(decrypted) as { client_email: string private_key: string token_uri?: string } - const filteredScopes = scopes.filter((s) => !SA_EXCLUDED_SCOPES.has(s)) - const now = Math.floor(Date.now() / 1000) const ALLOWED_TOKEN_URIS = new Set(['https://oauth2.googleapis.com/token']) const tokenUri = @@ -510,10 +556,12 @@ export interface ServiceAccountTokenResult { apiDomain?: string /** * Set when the token must be sent in an `x-api-token` header instead of - * `Authorization: Bearer` (e.g. Pipedrive personal API tokens). Absent means - * Bearer; OAuth credentials never carry it. + * `Authorization: Bearer` (e.g. Pipedrive personal API tokens), or is a + * Sim-signed OIDC token a keyless Snowflake credential presents through + * workload identity federation. Absent means Bearer; OAuth credentials never + * carry it. */ - authStyle?: 'x-api-token' + authStyle?: 'x-api-token' | 'snowflake-workload-identity' } /** @@ -738,6 +786,12 @@ const SERVICE_ACCOUNT_TOKEN_RESOLVERS: Record ({ accessToken: credentialId, }), + [MICROSOFT_APP_SERVICE_ACCOUNT_PROVIDER_ID]: async (credentialId, options) => { + const { resolveMicrosoftAppCredentialToken } = await import( + '@/lib/credentials/microsoft-app-service-account.server' + ) + return resolveMicrosoftAppCredentialToken(credentialId, options.service, options.signal) + }, [DATABRICKS_SERVICE_ACCOUNT_PROVIDER_ID]: async (credentialId, options) => { const { resolveDatabricksCredentialToken } = await import( '@/lib/credentials/databricks-service-account.server' @@ -797,7 +851,7 @@ const SERVICE_ACCOUNT_TOKEN_RESOLVERS: Record { if (!scopes?.length) { throw new Error('Scopes are required for service account credentials') @@ -805,6 +859,7 @@ const SERVICE_ACCOUNT_TOKEN_RESOLVERS: Record { + if (providerId === SNOWFLAKE_SERVICE_ACCOUNT_PROVIDER_ID) { + const { resolveSnowflakeCredentialToken } = await import( + '@/lib/credentials/snowflake-service-account.server' + ) + return resolveSnowflakeCredentialToken(credentialId) + } if (providerId && isTokenServiceAccountProviderId(providerId)) { const secret = await getTokenServiceAccountSecret(credentialId, providerId) const descriptorAuthStyle = getTokenServiceAccountDescriptor(providerId)?.authStyle diff --git a/apps/sim/lib/oauth/docusign.ts b/apps/sim/lib/oauth/docusign.ts index 27d038b86d5..ab3aa2f501a 100644 --- a/apps/sim/lib/oauth/docusign.ts +++ b/apps/sim/lib/oauth/docusign.ts @@ -45,3 +45,35 @@ export function getDocusignWebBase(): string { ? 'https://app.docusign.com' : 'https://appdemo.docusign.com' } + +/** + * The eSignature REST base a JWT Grant credential is bound to + * (`https://{host}.docusign.net/restapi/v2.1/accounts/{accountId}`), resolved + * by the minter from the credential's own environment. + */ +const DOCUSIGN_ACCOUNT_API_BASE_REGEX = + /^(https:\/\/([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)\.docusign\.net)\/restapi\/v2\.1\/accounts\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/ + +export interface DocuSignBoundAccount { + /** eSignature host origin, e.g. `https://na3.docusign.net`. */ + baseUri: string + accountId: string + /** Web app origin for envelope links in the same environment as {@link baseUri}. */ + webBase: string +} + +/** + * Parses a credential-bound account base, or `undefined` when the value is not + * exactly that shape, so a value that did not come from the minter is never + * sent a token. + */ +export function parseDocuSignAccountApiBase(value: unknown): DocuSignBoundAccount | undefined { + if (typeof value !== 'string') return undefined + const match = DOCUSIGN_ACCOUNT_API_BASE_REGEX.exec(value) + if (!match) return undefined + return { + baseUri: match[1], + accountId: match[3], + webBase: match[2] === 'demo' ? 'https://appdemo.docusign.com' : 'https://app.docusign.com', + } +} diff --git a/apps/sim/lib/oauth/oauth.ts b/apps/sim/lib/oauth/oauth.ts index e2805cb2755..2ffd1bd701c 100644 --- a/apps/sim/lib/oauth/oauth.ts +++ b/apps/sim/lib/oauth/oauth.ts @@ -614,6 +614,7 @@ export const OAUTH_PROVIDERS: Record = { providerId: 'microsoft-ad', icon: AzureIcon, baseProviderIcon: MicrosoftIcon, + serviceAccountProviderId: 'microsoft-app-service-account', scopes: [ 'openid', 'profile', @@ -639,6 +640,7 @@ export const OAUTH_PROVIDERS: Record = { providerId: 'microsoft-dataverse', icon: MicrosoftDataverseIcon, baseProviderIcon: MicrosoftIcon, + serviceAccountProviderId: 'microsoft-app-service-account', scopes: [ 'openid', 'profile', @@ -823,6 +825,7 @@ export const OAUTH_PROVIDERS: Record = { providerId: 'sharepoint', icon: MicrosoftSharepointIcon, baseProviderIcon: MicrosoftIcon, + serviceAccountProviderId: 'microsoft-app-service-account', scopes: [ 'openid', 'profile', @@ -1006,6 +1009,7 @@ export const OAUTH_PROVIDERS: Record = { name: 'Bitbucket', description: 'Read repositories, collaborate on pull requests, and manage pipelines.', providerId: 'bitbucket', + serviceAccountProviderId: 'bitbucket-service-account', icon: BitbucketIcon, baseProviderIcon: BitbucketIcon, scopes: [ @@ -1530,6 +1534,7 @@ export const OAUTH_PROVIDERS: Record = { icon: DocuSignIcon, baseProviderIcon: DocuSignIcon, scopes: ['signature', 'extended'], + serviceAccountProviderId: 'docusign-service-account', }, }, defaultService: 'docusign', @@ -3086,6 +3091,24 @@ export const OAUTH_PROVIDERS: Record = { }, defaultService: 'whatsapp', }, + 'github-token': { + name: 'GitHub', + icon: GithubIcon, + services: { + 'github-token': { + name: 'GitHub', + description: + 'Manage GitHub repositories, issues, pull requests, workflows, releases, and gists.', + providerId: 'github-token', + serviceAccountProviderId: 'github-service-account', + icon: GithubIcon, + baseProviderIcon: GithubIcon, + scopes: [], + authType: 'service_account', + }, + }, + defaultService: 'github-token', + }, gitlab: { name: 'GitLab', icon: GitLabIcon, diff --git a/apps/sim/lib/oauth/token-resolution.test.ts b/apps/sim/lib/oauth/token-resolution.test.ts index 3607961ef1f..8e3d74cc425 100644 --- a/apps/sim/lib/oauth/token-resolution.test.ts +++ b/apps/sim/lib/oauth/token-resolution.test.ts @@ -39,7 +39,9 @@ vi.unmock('@/lib/oauth/utils') import { OrchestrationError } from '@/lib/core/orchestration/types' import { InvalidManagedOAuthDelegationError } from '@/lib/credentials/application/managed-oauth-delegation' +import { TokenServiceAccountValidationError } from '@/lib/credentials/token-service-accounts/errors' import { resolveCredentialAccessToken, resolveCredentialToken } from '@/lib/oauth/token-resolution' +import type { OAuthService } from '@/lib/oauth/types' import { getToolMetadata } from '@/tools/metadata' const mockGetToolMetadata = vi.mocked(getToolMetadata) @@ -617,3 +619,130 @@ describe('ordinary tool credential binding', () => { } ) }) + +describe('Microsoft app credential binding', () => { + const authenticate = async () => INTERNAL_AUTH + const appCredential = { + credentialType: 'service_account', + credentialId: 'microsoft-app-1', + providerId: 'microsoft-app-service-account', + accountId: '', + workspaceId: 'workspace-1', + usedCredentialTable: true, + } as const + + beforeEach(() => { + mockAuthorizeCredentialUseForAuth.mockResolvedValue({ + ok: true, + requesterUserId: 'user-1', + credentialOwnerUserId: 'owner-1', + }) + mockResolveOAuthAccountId.mockResolvedValue(appCredential) + mockResolveServiceAccountToken.mockReset() + mockResolveServiceAccountToken.mockResolvedValue({ accessToken: 'app-token' }) + }) + + function toolFor(provider: OAuthService) { + mockGetToolMetadata.mockReturnValue({ + id: `${provider}-tool`, + params: {}, + oauth: { required: true, provider }, + }) + } + + it.each([ + 'outlook', + 'onedrive', + 'microsoft-excel', + 'microsoft-word', + 'microsoft-planner', + 'microsoft-teams', + ] as const)( + 'refuses an app credential for %s, which acts as a signed-in person', + async (provider) => { + toolFor(provider) + const result = await resolveCredentialAccessToken({ + requestId: 'microsoft-app', + credentialId: 'microsoft-app-1', + toolId: `${provider}-tool`, + authenticate, + }) + expect(result).toMatchObject({ ok: false, status: 400, code: 'CREDENTIAL_PROVIDER_MISMATCH' }) + expect(mockResolveServiceAccountToken).not.toHaveBeenCalled() + } + ) + + it.each(['microsoft-ad', 'sharepoint', 'microsoft-dataverse'] as const)( + 'mints an app-only token for %s and tells the resolver which service it is for', + async (provider) => { + toolFor(provider) + const result = await resolveCredentialAccessToken({ + requestId: 'microsoft-app', + credentialId: 'microsoft-app-1', + toolId: `${provider}-tool`, + authenticate, + }) + expect(result).toMatchObject({ ok: true, token: { credentialType: 'service_account' } }) + expect(mockResolveServiceAccountToken).toHaveBeenCalledWith( + 'microsoft-app-1', + 'microsoft-app-service-account', + expect.any(Array), + undefined, + { service: provider } + ) + } + ) + + it('refuses an app credential for Reset password, which Graph allows only for a signed-in admin', async () => { + const { resetPasswordTool } = await import('@/tools/microsoft_ad/reset_password') + mockGetToolMetadata.mockReturnValue(resetPasswordTool) + const result = await resolveCredentialAccessToken({ + requestId: 'microsoft-app', + credentialId: 'microsoft-app-1', + toolId: resetPasswordTool.id, + authenticate, + }) + expect(result).toMatchObject({ ok: false, status: 400, code: 'CREDENTIAL_TYPE_MISMATCH' }) + expect(mockResolveServiceAccountToken).not.toHaveBeenCalled() + }) +}) + +describe('keyless Google Cloud credential refusals', () => { + const authenticate = async () => INTERNAL_AUTH + + beforeEach(() => { + mockAuthorizeCredentialUseForAuth.mockResolvedValue({ + ok: true, + requesterUserId: 'user-1', + credentialOwnerUserId: 'owner-1', + }) + mockResolveOAuthAccountId.mockResolvedValue({ + credentialType: 'service_account', + credentialId: 'google-keyless-1', + providerId: 'google-service-account', + accountId: '', + workspaceId: 'workspace-1', + usedCredentialTable: true, + }) + mockGetToolMetadata.mockReturnValue({ + id: 'google-drive-tool', + params: {}, + oauth: { required: true, provider: 'google-drive' }, + }) + mockResolveServiceAccountToken.mockReset() + mockResolveServiceAccountToken.mockRejectedValue( + new TokenServiceAccountValidationError('unsupported_use', 400) + ) + }) + + it('tells the caller to use a JSON key instead of asking to reconnect', async () => { + const result = await resolveCredentialAccessToken({ + requestId: 'google-keyless', + credentialId: 'google-keyless-1', + toolId: 'google-drive-tool', + authenticate, + }) + expect(result).toMatchObject({ ok: false, status: 400, code: 'unsupported_use' }) + expect(result.ok ? '' : result.error).toMatch(/use a JSON key credential instead/) + }) +}) diff --git a/apps/sim/lib/oauth/token-resolution.ts b/apps/sim/lib/oauth/token-resolution.ts index f044f954876..eacd22aa7a8 100644 --- a/apps/sim/lib/oauth/token-resolution.ts +++ b/apps/sim/lib/oauth/token-resolution.ts @@ -13,6 +13,7 @@ import { InvalidManagedOAuthDelegationError } from '@/lib/credentials/applicatio import { resolveManagedOAuthCredentialToken } from '@/lib/credentials/application/resolve-managed-oauth-token' import { ManagedOAuthCredentialError } from '@/lib/credentials/managed-oauth' import { TokenServiceAccountValidationError } from '@/lib/credentials/token-service-accounts/errors' +import { projectAssistantConnectedAccountTool } from '@/lib/mothership/assistant/connected-account-tool' import { CredentialRevokedError, OAUTH_CREDENTIAL_REVOKED } from '@/lib/oauth/credential-revoked' import { getCredential, @@ -54,6 +55,13 @@ export type CredentialTokenPayload = OAuthTokenResponse export interface ResolveCredentialTokenInput { /** Tool whose canonical provider and credential-kind policy applies before token minting. */ toolId?: string + /** + * The call is an Assistant turn acting with the person's own connected account, so the + * tool's policy is the one the Assistant projects for it (GitHub tools bind the person's + * GitHub account, never a workspace token). Set only by the in-process executor for an + * authenticated Assistant turn; the token route never forwards it. + */ + assistantConnectedAccount?: boolean /** Correlation id used by the credential service's own logging. */ requestId: string credentialId?: string @@ -283,13 +291,24 @@ function validateToolCredentialKind( } } +/** The credential policy a tool call binds through: the registry's, or the Assistant's projection of it. */ +function toolCredentialPolicy( + toolId: string, + assistantConnectedAccount: boolean | undefined +): OAuthConfig | undefined { + const tool = getToolMetadata(toolId) + if (!tool) return undefined + return (assistantConnectedAccount ? projectAssistantConnectedAccountTool(tool) : tool).oauth +} + function validateToolCredentialBinding( toolId: string | undefined, + assistantConnectedAccount: boolean | undefined, providerId: string | null | undefined, credentialKind: NonNullable ): Extract | undefined { if (!toolId) return - const policy = getToolMetadata(toolId)?.oauth + const policy = toolCredentialPolicy(toolId, assistantConnectedAccount) const kindError = validateToolCredentialKind(policy?.credentialKind, credentialKind) if (kindError) return kindError /** @@ -377,6 +396,7 @@ export async function resolveCredentialToken( } const bindingError = validateToolCredentialBinding( input.toolId, + input.assistantConnectedAccount, resolved.providerId, 'service-account' ) @@ -390,7 +410,10 @@ export async function resolveCredentialToken( resolved.credentialId, resolved.providerId, scopes ?? [], - impersonateEmail + impersonateEmail, + { + service: toolCredentialPolicy(input.toolId, input.assistantConnectedAccount)?.provider, + } ) if (saActorId) { @@ -452,6 +475,33 @@ export async function resolveCredentialToken( error: 'Credential rejected by the provider — reconnect the credential', } } + if (error.code === 'consent_required') { + return { + ok: false, + status: 401, + code: error.code, + error: + 'The provider needs the impersonated user to grant consent — reconnect the credential to get the consent link', + } + } + if (error.code === 'unsupported_use') { + return { + ok: false, + status: 400, + code: error.code, + error: + 'This credential cannot be used here. Keyless Google Cloud credentials work only with Google Cloud tools such as BigQuery and cannot impersonate a Workspace user; use a JSON key credential instead', + } + } + if (error.code === 'account_not_found') { + return { + ok: false, + status: 400, + code: error.code, + error: + 'The credential’s user is no longer a member of its pinned account — reconnect the credential', + } + } } return { ok: false, status: 401, error: 'Failed to get service account token' } } @@ -472,7 +522,12 @@ export async function resolveCredentialToken( return { ok: false, status: 404, error: 'Credential not found' } } - const bindingError = validateToolCredentialBinding(input.toolId, credential.providerId, 'oauth') + const bindingError = validateToolCredentialBinding( + input.toolId, + input.assistantConnectedAccount, + credential.providerId, + 'oauth' + ) if (bindingError) return bindingError return completeOAuthCredentialToken({ @@ -539,6 +594,7 @@ export async function resolveCredentialAccessToken( auditRequest, resolvedCredential: resolved, toolId, + assistantConnectedAccount: input.assistantConnectedAccount, }) } @@ -573,8 +629,8 @@ export async function resolveCredentialAccessToken( } } - const toolMetadata = getToolMetadata(toolId) - if (!toolMetadata?.oauth?.required) { + const toolPolicy = toolCredentialPolicy(toolId, input.assistantConnectedAccount) + if (!toolPolicy?.required) { logger.error('Tool is not configured for managed OAuth', { requestId, toolId }) return { ok: false, @@ -583,17 +639,16 @@ export async function resolveCredentialAccessToken( error: 'This tool is not configured to use managed credentials', } } - const kindError = validateToolCredentialKind(toolMetadata.oauth.credentialKind, 'oauth') + const kindError = validateToolCredentialKind(toolPolicy.credentialKind, 'oauth') if (kindError) return kindError const requiredScopes = - toolMetadata.oauth.requiredScopes ?? - getDefaultToolScopesForProvider(toolMetadata.oauth.provider) - if (requiredScopes.length === 0 && toolMetadata.oauth.requiredScopes === undefined) { + toolPolicy.requiredScopes ?? getDefaultToolScopesForProvider(toolPolicy.provider) + if (requiredScopes.length === 0 && toolPolicy.requiredScopes === undefined) { logger.error('Tool has no trusted OAuth scope policy', { requestId, toolId, - providerId: toolMetadata.oauth.provider, + providerId: toolPolicy.provider, }) return { ok: false, @@ -608,7 +663,7 @@ export async function resolveCredentialAccessToken( principal, input: { credentialId: resolved.credentialId, - expectedProviderId: toolMetadata.oauth.provider, + expectedProviderId: toolPolicy.provider, requiredScopes, toolId, }, @@ -622,7 +677,7 @@ export async function resolveCredentialAccessToken( 'credential_used', { credential_type: 'managed_oauth', - provider_id: toolMetadata.oauth.provider, + provider_id: toolPolicy.provider, workspace_id: principal.workspaceId, }, { groups: { workspace: principal.workspaceId } } diff --git a/apps/sim/lib/oauth/types.ts b/apps/sim/lib/oauth/types.ts index 5bc2b90d841..d8221c2ff05 100644 --- a/apps/sim/lib/oauth/types.ts +++ b/apps/sim/lib/oauth/types.ts @@ -48,6 +48,12 @@ export const AWS_SERVICE_ACCOUNT_PROVIDER_ID = 'aws-service-account' as const /** Saved Databricks connection (PAT, service-principal secret, or keyless OIDC federation). */ export const DATABRICKS_SERVICE_ACCOUNT_PROVIDER_ID = 'databricks-service-account' as const +/** + * Saved Microsoft Entra app-only credential (client secret, certificate, or keyless federated + * credential), shared by the Microsoft services whose tools run without a signed-in user. + */ +export const MICROSOFT_APP_SERVICE_ACCOUNT_PROVIDER_ID = 'microsoft-app-service-account' as const + export type OAuthProvider = | 'aws' | 'databricks' @@ -311,6 +317,7 @@ export type OAuthService = | 'convex' | 'jupyter' | 'grafana' + | 'github-token' | 'gitlab' | 'whatsapp' | 'vercel' diff --git a/apps/sim/lib/permission-groups/block-successors.generated.ts b/apps/sim/lib/permission-groups/block-successors.generated.ts index a8712c2fdce..fbd8d5f4198 100644 --- a/apps/sim/lib/permission-groups/block-successors.generated.ts +++ b/apps/sim/lib/permission-groups/block-successors.generated.ts @@ -64,7 +64,8 @@ export const BLOCK_ACCESS_SUCCESSORS: Record = { fireflies_v2: 'fireflies_v3', flint: 'flint_v2', gamma: 'gamma_v2', - github: 'github_v2', + github: 'github_v3', + github_v2: 'github_v3', gitlab: 'gitlab_v2', gmail: 'gmail_v2', google_calendar: 'google_calendar_v2', diff --git a/apps/sim/lib/selectors/server/app-credential-token.test.ts b/apps/sim/lib/selectors/server/app-credential-token.test.ts new file mode 100644 index 00000000000..8a2808f45b9 --- /dev/null +++ b/apps/sim/lib/selectors/server/app-credential-token.test.ts @@ -0,0 +1,75 @@ +/** + * @vitest-environment node + */ + +import { credential } from '@sim/db/schema' +import { queueTableRows, resetDbChainMock } from '@sim/testing' +import { jsonResponse } from '@sim/testing/helpers/http' +import { encryptionMock, encryptionMockFns } from '@sim/testing/mocks/encryption.mock' +import { beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@/lib/core/security/encryption', () => encryptionMock) +vi.unmock('@/lib/oauth/credential-service') + +import { resolveSelectorOAuthAccessToken } from '@/lib/selectors/server/credentials' +import { createSelectorProtectedValues } from '@/lib/selectors/server/protected-values' + +const TENANT = '11111111-2222-3333-4444-555555555555' +const CLIENT_ID = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee' + +describe('a SharePoint selector with a Microsoft app credential', () => { + const fetch = vi.fn() + + beforeEach(() => { + resetDbChainMock() + const row = { + id: 'app-credential', + type: 'service_account', + accountId: null, + workspaceId: 'ws-1', + organizationId: null, + providerId: 'microsoft-app-service-account', + revokedAt: null, + encryptedServiceAccountKey: 'ciphertext-selector', + } + queueTableRows(credential, [row]) + queueTableRows(credential, [row]) + encryptionMockFns.mockDecryptSecret.mockResolvedValueOnce({ + decrypted: JSON.stringify({ + type: 'microsoft_app_credential_v1', + config: { + authType: 'client_secret', + tenantId: TENANT, + clientId: CLIENT_ID, + clientSecret: 'app-secret', + }, + }), + }) + fetch.mockReset().mockImplementation(async (_url: string, init: RequestInit) => { + const scope = new URLSearchParams(String(init.body)).get('scope') + return jsonResponse({ token_type: 'Bearer', expires_in: 3599, access_token: `at:${scope}` }) + }) + vi.stubGlobal('fetch', fetch) + }) + + it('browses with a Microsoft Graph app-only token', async () => { + await expect( + resolveSelectorOAuthAccessToken({ + credential: { + suppliedId: 'app-credential', + access: { + ok: true, + credentialOwnerUserId: 'user-1', + resolvedCredentialId: 'app-credential', + }, + }, + serviceId: 'sharepoint', + protectedValues: createSelectorProtectedValues(), + }) + ).resolves.toBe('at:https://graph.microsoft.com/.default') + expect(fetch).toHaveBeenCalledWith( + `https://login.microsoftonline.com/${TENANT}/oauth2/v2.0/token`, + expect.anything() + ) + }) +}) diff --git a/apps/sim/lib/selectors/server/credentials.test.ts b/apps/sim/lib/selectors/server/credentials.test.ts index ef2d76f9514..0752b386d31 100644 --- a/apps/sim/lib/selectors/server/credentials.test.ts +++ b/apps/sim/lib/selectors/server/credentials.test.ts @@ -110,6 +110,7 @@ describe('authorizeSelectorCredential', () => { expectedProviderId: 'google-email', requiredScopes: ['gmail.modify'], impersonateEmail: undefined, + service: 'gmail', }) }) @@ -268,7 +269,7 @@ describe('resolveSelectorOAuthAccessToken', () => { expect(liveProtectedValues.contains('shared-access-token')).toBe(true) expect(mocks.resolveCredentialTokenBundle).toHaveBeenCalledTimes(2) for (const call of mocks.resolveCredentialTokenBundle.mock.calls) { - expect(call[5]).toEqual({ privacyMode: 'selector' }) + expect(call[5]).toEqual({ privacyMode: 'selector', service: 'gmail' }) expect(call).not.toContain(canceledController.signal) expect(call).not.toContain(liveController.signal) } diff --git a/apps/sim/lib/selectors/server/credentials.ts b/apps/sim/lib/selectors/server/credentials.ts index 1167e61306d..dec4510f124 100644 --- a/apps/sim/lib/selectors/server/credentials.ts +++ b/apps/sim/lib/selectors/server/credentials.ts @@ -198,6 +198,7 @@ export async function resolveSelectorOAuthAccessToken(input: { requiredScopes: input.scopes ? [...input.scopes] : undefined, impersonateEmail: input.impersonateEmail, expectedProviderId: input.credential.providerId, + service: input.serviceId, }), input.credential.signal ) @@ -223,7 +224,7 @@ export async function resolveSelectorOAuthAccessToken(input: { 'selector-execution', input.scopes ? [...input.scopes] : undefined, input.impersonateEmail, - { privacyMode: 'selector' } + { privacyMode: 'selector', service: input.serviceId } ), input.credential.signal ) diff --git a/apps/sim/lib/selectors/server/providers/pipedrive.ts b/apps/sim/lib/selectors/server/providers/pipedrive.ts index 2473916fa0f..96e6075b887 100644 --- a/apps/sim/lib/selectors/server/providers/pipedrive.ts +++ b/apps/sim/lib/selectors/server/providers/pipedrive.ts @@ -62,7 +62,7 @@ export const pipedriveSelectorAttachments = { const body = await fetchProviderJson(url, { headers: getPipedriveAuthHeaders({ accessToken: token.accessToken, - authStyle: token.authStyle, + authStyle: token.authStyle === 'x-api-token' ? token.authStyle : undefined, }), signal: args.signal, redirect: 'error', diff --git a/apps/sim/lib/selectors/server/providers/snowflake.ts b/apps/sim/lib/selectors/server/providers/snowflake.ts index 08ae2520f61..07e6a96d8b2 100644 --- a/apps/sim/lib/selectors/server/providers/snowflake.ts +++ b/apps/sim/lib/selectors/server/providers/snowflake.ts @@ -54,6 +54,8 @@ interface SnowflakeObject { interface SnowflakeDestination { accessToken: string + /** Token type from the credential: set for a keyless credential, absent for a programmatic access token. */ + authStyle?: string baseUrl: string } @@ -132,6 +134,7 @@ async function prepareSnowflakeDestination( try { return { accessToken: token.accessToken, + authStyle: token.authStyle, baseUrl: normalizeSnowflakeHost(token.domain), } } catch { @@ -162,7 +165,7 @@ async function executeSnowflake( const timeoutSignal = AbortSignal.timeout(SELECTOR_FETCH_TIMEOUT_MS) const signal = args.signal ? AbortSignal.any([args.signal, timeoutSignal]) : timeoutSignal - const headers = buildSnowflakeAuthHeaders(destination.accessToken) + const headers = buildSnowflakeAuthHeaders(destination.accessToken, destination.authStyle) const byteBudget = { remainingBytes: SELECTOR_MAX_AGGREGATE_RESPONSE_BYTES } try { const response = await fetchSnowflakeResponse(`${destination.baseUrl}/api/v2/statements`, { diff --git a/apps/sim/tools/bitbucket/list_workspaces.ts b/apps/sim/tools/bitbucket/list_workspaces.ts index 6b401592afa..9c8eab08f1c 100644 --- a/apps/sim/tools/bitbucket/list_workspaces.ts +++ b/apps/sim/tools/bitbucket/list_workspaces.ts @@ -30,7 +30,17 @@ export const bitbucketListWorkspacesTool: ToolConfig< name: 'Bitbucket List Workspaces', description: 'List Bitbucket Cloud workspaces available to the authenticated account', version: '1.0.0', - oauth: { required: true, provider: 'bitbucket', requiredScopes: ['account'] }, + /** + * Lists the workspaces of the person who connected the account, so it needs a + * person's OAuth account. A saved access token belongs to a workspace, project, + * or repository rather than a person, so it is turned away before any request. + */ + oauth: { + required: true, + provider: 'bitbucket', + requiredScopes: ['account'], + credentialKind: 'oauth', + }, params: { sort: { type: 'string', diff --git a/apps/sim/tools/docusign/create_from_template.ts b/apps/sim/tools/docusign/create_from_template.ts index 49bc2058901..99d3974e6f0 100644 --- a/apps/sim/tools/docusign/create_from_template.ts +++ b/apps/sim/tools/docusign/create_from_template.ts @@ -16,6 +16,7 @@ export const docusignCreateFromTemplateTool: InternalToolConfig< oauth: { required: true, provider: 'docusign', + authoritativeParams: ['instanceUrl'], }, params: { @@ -25,6 +26,12 @@ export const docusignCreateFromTemplateTool: InternalToolConfig< visibility: 'hidden', description: 'DocuSign OAuth access token', }, + instanceUrl: { + type: 'string', + required: false, + visibility: 'hidden', + description: 'DocuSign account API base bound to a JWT Grant credential', + }, templateId: { type: 'string', required: true, @@ -62,6 +69,7 @@ export const docusignCreateFromTemplateTool: InternalToolConfig< operation: { input: (params) => ({ accessToken: params.accessToken, + instanceUrl: params.instanceUrl, templateId: params.templateId, emailSubject: params.emailSubject, emailBody: params.emailBody, diff --git a/apps/sim/tools/docusign/download_document.ts b/apps/sim/tools/docusign/download_document.ts index 829784b86e7..0186d46ff50 100644 --- a/apps/sim/tools/docusign/download_document.ts +++ b/apps/sim/tools/docusign/download_document.ts @@ -16,6 +16,7 @@ export const docusignDownloadDocumentTool: InternalToolConfig< oauth: { required: true, provider: 'docusign', + authoritativeParams: ['instanceUrl'], }, params: { @@ -25,6 +26,12 @@ export const docusignDownloadDocumentTool: InternalToolConfig< visibility: 'hidden', description: 'DocuSign OAuth access token', }, + instanceUrl: { + type: 'string', + required: false, + visibility: 'hidden', + description: 'DocuSign account API base bound to a JWT Grant credential', + }, envelopeId: { type: 'string', required: true, @@ -43,6 +50,7 @@ export const docusignDownloadDocumentTool: InternalToolConfig< operation: { input: (params) => ({ accessToken: params.accessToken, + instanceUrl: params.instanceUrl, envelopeId: params.envelopeId, documentId: params.documentId, }), diff --git a/apps/sim/tools/docusign/get_envelope.ts b/apps/sim/tools/docusign/get_envelope.ts index 469e65ae651..889f0c12640 100644 --- a/apps/sim/tools/docusign/get_envelope.ts +++ b/apps/sim/tools/docusign/get_envelope.ts @@ -13,6 +13,7 @@ export const docusignGetEnvelopeTool: InternalToolConfig< oauth: { required: true, provider: 'docusign', + authoritativeParams: ['instanceUrl'], }, params: { @@ -22,6 +23,12 @@ export const docusignGetEnvelopeTool: InternalToolConfig< visibility: 'hidden', description: 'DocuSign OAuth access token', }, + instanceUrl: { + type: 'string', + required: false, + visibility: 'hidden', + description: 'DocuSign account API base bound to a JWT Grant credential', + }, envelopeId: { type: 'string', required: true, @@ -33,6 +40,7 @@ export const docusignGetEnvelopeTool: InternalToolConfig< operation: { input: (params) => ({ accessToken: params.accessToken, + instanceUrl: params.instanceUrl, envelopeId: params.envelopeId, }), }, diff --git a/apps/sim/tools/docusign/list_envelopes.ts b/apps/sim/tools/docusign/list_envelopes.ts index 9f22a93c0ea..5c1decbbc13 100644 --- a/apps/sim/tools/docusign/list_envelopes.ts +++ b/apps/sim/tools/docusign/list_envelopes.ts @@ -17,6 +17,7 @@ export const docusignListEnvelopesTool: InternalToolConfig< oauth: { required: true, provider: 'docusign', + authoritativeParams: ['instanceUrl'], }, params: { @@ -26,6 +27,12 @@ export const docusignListEnvelopesTool: InternalToolConfig< visibility: 'hidden', description: 'DocuSign OAuth access token', }, + instanceUrl: { + type: 'string', + required: false, + visibility: 'hidden', + description: 'DocuSign account API base bound to a JWT Grant credential', + }, fromDate: { type: 'string', required: false, @@ -61,6 +68,7 @@ export const docusignListEnvelopesTool: InternalToolConfig< operation: { input: (params) => ({ accessToken: params.accessToken, + instanceUrl: params.instanceUrl, fromDate: params.fromDate, toDate: params.toDate, envelopeStatus: params.envelopeStatus, diff --git a/apps/sim/tools/docusign/list_recipients.ts b/apps/sim/tools/docusign/list_recipients.ts index d4c43f9f935..66f09b6a317 100644 --- a/apps/sim/tools/docusign/list_recipients.ts +++ b/apps/sim/tools/docusign/list_recipients.ts @@ -17,6 +17,7 @@ export const docusignListRecipientsTool: InternalToolConfig< oauth: { required: true, provider: 'docusign', + authoritativeParams: ['instanceUrl'], }, params: { @@ -26,6 +27,12 @@ export const docusignListRecipientsTool: InternalToolConfig< visibility: 'hidden', description: 'DocuSign OAuth access token', }, + instanceUrl: { + type: 'string', + required: false, + visibility: 'hidden', + description: 'DocuSign account API base bound to a JWT Grant credential', + }, envelopeId: { type: 'string', required: true, @@ -37,6 +44,7 @@ export const docusignListRecipientsTool: InternalToolConfig< operation: { input: (params) => ({ accessToken: params.accessToken, + instanceUrl: params.instanceUrl, envelopeId: params.envelopeId, }), }, diff --git a/apps/sim/tools/docusign/list_templates.ts b/apps/sim/tools/docusign/list_templates.ts index 7e32ca08b1e..56f4233190b 100644 --- a/apps/sim/tools/docusign/list_templates.ts +++ b/apps/sim/tools/docusign/list_templates.ts @@ -17,6 +17,7 @@ export const docusignListTemplatesTool: InternalToolConfig< oauth: { required: true, provider: 'docusign', + authoritativeParams: ['instanceUrl'], }, params: { @@ -26,6 +27,12 @@ export const docusignListTemplatesTool: InternalToolConfig< visibility: 'hidden', description: 'DocuSign OAuth access token', }, + instanceUrl: { + type: 'string', + required: false, + visibility: 'hidden', + description: 'DocuSign account API base bound to a JWT Grant credential', + }, searchText: { type: 'string', required: false, @@ -43,6 +50,7 @@ export const docusignListTemplatesTool: InternalToolConfig< operation: { input: (params) => ({ accessToken: params.accessToken, + instanceUrl: params.instanceUrl, searchText: params.searchText, count: params.count, }), diff --git a/apps/sim/tools/docusign/send_envelope.ts b/apps/sim/tools/docusign/send_envelope.ts index 0c8f1ab070a..9d2bce764fe 100644 --- a/apps/sim/tools/docusign/send_envelope.ts +++ b/apps/sim/tools/docusign/send_envelope.ts @@ -16,6 +16,7 @@ export const docusignSendEnvelopeTool: InternalToolConfig< oauth: { required: true, provider: 'docusign', + authoritativeParams: ['instanceUrl'], }, params: { @@ -25,6 +26,12 @@ export const docusignSendEnvelopeTool: InternalToolConfig< visibility: 'hidden', description: 'DocuSign OAuth access token', }, + instanceUrl: { + type: 'string', + required: false, + visibility: 'hidden', + description: 'DocuSign account API base bound to a JWT Grant credential', + }, emailSubject: { type: 'string', required: true, @@ -79,6 +86,7 @@ export const docusignSendEnvelopeTool: InternalToolConfig< operation: { input: (params) => ({ accessToken: params.accessToken, + instanceUrl: params.instanceUrl, emailSubject: params.emailSubject, emailBody: params.emailBody, signerEmail: params.signerEmail, diff --git a/apps/sim/tools/docusign/types.ts b/apps/sim/tools/docusign/types.ts index 5eb11690e4e..241e279ed03 100644 --- a/apps/sim/tools/docusign/types.ts +++ b/apps/sim/tools/docusign/types.ts @@ -82,6 +82,7 @@ export const TEMPLATES_ARRAY_OUTPUT: OutputProperty = { /** Params interfaces */ export interface DocuSignSendEnvelopeParams { accessToken: string + instanceUrl?: string emailSubject: string emailBody?: string signerEmail: string @@ -94,6 +95,7 @@ export interface DocuSignSendEnvelopeParams { export interface DocuSignCreateFromTemplateParams { accessToken: string + instanceUrl?: string templateId: string emailSubject?: string emailBody?: string @@ -103,11 +105,13 @@ export interface DocuSignCreateFromTemplateParams { export interface DocuSignGetEnvelopeParams { accessToken: string + instanceUrl?: string envelopeId: string } export interface DocuSignListEnvelopesParams { accessToken: string + instanceUrl?: string fromDate?: string toDate?: string envelopeStatus?: string @@ -117,24 +121,28 @@ export interface DocuSignListEnvelopesParams { export interface DocuSignVoidEnvelopeParams { accessToken: string + instanceUrl?: string envelopeId: string voidedReason: string } export interface DocuSignDownloadDocumentParams { accessToken: string + instanceUrl?: string envelopeId: string documentId?: string } export interface DocuSignListTemplatesParams { accessToken: string + instanceUrl?: string searchText?: string count?: string } export interface DocuSignListRecipientsParams { accessToken: string + instanceUrl?: string envelopeId: string } diff --git a/apps/sim/tools/docusign/void_envelope.ts b/apps/sim/tools/docusign/void_envelope.ts index 806410ee48b..5d2895f1f21 100644 --- a/apps/sim/tools/docusign/void_envelope.ts +++ b/apps/sim/tools/docusign/void_envelope.ts @@ -16,6 +16,7 @@ export const docusignVoidEnvelopeTool: InternalToolConfig< oauth: { required: true, provider: 'docusign', + authoritativeParams: ['instanceUrl'], }, params: { @@ -25,6 +26,12 @@ export const docusignVoidEnvelopeTool: InternalToolConfig< visibility: 'hidden', description: 'DocuSign OAuth access token', }, + instanceUrl: { + type: 'string', + required: false, + visibility: 'hidden', + description: 'DocuSign account API base bound to a JWT Grant credential', + }, envelopeId: { type: 'string', required: true, @@ -42,6 +49,7 @@ export const docusignVoidEnvelopeTool: InternalToolConfig< operation: { input: (params) => ({ accessToken: params.accessToken, + instanceUrl: params.instanceUrl, envelopeId: params.envelopeId, voidedReason: params.voidedReason, }), diff --git a/apps/sim/tools/generated/tool-metadata.ts b/apps/sim/tools/generated/tool-metadata.ts index cb7fcefe39d..d57e38c0512 100644 --- a/apps/sim/tools/generated/tool-metadata.ts +++ b/apps/sim/tools/generated/tool-metadata.ts @@ -3,7 +3,7 @@ /** Serializable metadata for every built-in tool, keyed by tool id. */ const toolMetadata: Record = JSON.parse( - '{"a2a_cancel_task":{"id":"a2a_cancel_task","name":"A2A Cancel Task","description":"Request cancellation of an in-progress A2A task.","version":"1.0.0","params":{"agentUrl":{"type":"string","required":true,"visibility":"user-only","description":"The A2A agent endpoint URL"},"taskId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The task ID to cancel"},"apiKey":{"type":"string","required":false,"visibility":"user-only","description":"API key for authentication (if required)"}},"hostedApiKey":"none"},"a2a_get_agent_card":{"id":"a2a_get_agent_card","name":"A2A Get Agent Card","description":"Fetch the Agent Card (discovery document) for an external A2A agent.","version":"1.0.0","params":{"agentUrl":{"type":"string","required":true,"visibility":"user-only","description":"The A2A agent endpoint URL"},"apiKey":{"type":"string","required":false,"visibility":"user-only","description":"API key for authentication (if required)"}},"hostedApiKey":"none"},"a2a_get_task":{"id":"a2a_get_task","name":"A2A Get Task","description":"Retrieve the current state and result of an A2A task.","version":"1.0.0","params":{"agentUrl":{"type":"string","required":true,"visibility":"user-only","description":"The A2A agent endpoint URL"},"taskId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The task ID to retrieve"},"historyLength":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of history messages to include"},"apiKey":{"type":"string","required":false,"visibility":"user-only","description":"API key for authentication (if required)"}},"hostedApiKey":"none"},"a2a_send_message":{"id":"a2a_send_message","name":"A2A Send Message","description":"Send a message to an external A2A agent and return its response.","version":"1.0.0","params":{"agentUrl":{"type":"string","required":true,"visibility":"user-only","description":"The A2A agent endpoint URL"},"message":{"type":"string","required":true,"visibility":"user-or-llm","description":"The message text to send"},"data":{"type":"json","required":false,"visibility":"user-or-llm","description":"Optional structured JSON data to attach"},"files":{"type":"json","required":false,"visibility":"user-or-llm","description":"Optional files to attach"},"taskId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Existing task ID to continue"},"contextId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Conversation context ID to continue"},"apiKey":{"type":"string","required":false,"visibility":"user-only","description":"API key for authentication (if required)"}},"hostedApiKey":"none"},"affinity_batch_update_entity_fields":{"id":"affinity_batch_update_entity_fields","name":"Affinity Batch Update Entity Fields","description":"Write up to 100 non-list field values on one company or person in a single request.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"entityType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Which entity to write the fields on: companies or persons"},"entityId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of that company or person"},"updates":{"type":"json","required":true,"visibility":"user-or-llm","description":"Up to 100 field updates as [{\\"id\\":\\"\\",\\"value\\":{\\"type\\":\\"…\\",\\"data\\":…}}], using the same value shapes as a single field update"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_batch_update_list_entry_fields":{"id":"affinity_batch_update_list_entry_fields","name":"Affinity Batch Update List Entry Fields","description":"Write up to 100 field values on one list row in a single request. Requires the \\"Export data from Lists\\" permission.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"},"listEntryId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list entry ID"},"updates":{"type":"json","required":true,"visibility":"user-or-llm","description":"Up to 100 field updates as [{\\"id\\":\\"\\",\\"value\\":{\\"type\\":\\"…\\",\\"data\\":…}}], using the same value shapes as a single field update"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_create_list":{"id":"affinity_create_list","name":"Affinity Create List","description":"Create a list. Its type fixes which entities it can hold, and the API key holder becomes its creator and owner.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"name":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the new list"},"type":{"type":"string","required":true,"visibility":"user-or-llm","description":"Entity kind the list holds: company, opportunity, or person"},"isPublic":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Whether everyone in the organization can see the list"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_create_list_field_dropdown_option":{"id":"affinity_create_list_field_dropdown_option","name":"Affinity Create List Field Dropdown Option","description":"Add a selectable option to a dropdown field on a list. A ranked or status option also needs a rank and a color.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"},"fieldId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The dropdown field ID on that list"},"type":{"type":"string","required":true,"visibility":"user-or-llm","description":"Kind of option to create, matching the field. dropdown takes only a label; ranked-dropdown also requires rank and color; status-dropdown additionally requires a status category. Sending a field the kind does not accept is rejected"},"text":{"type":"string","required":true,"visibility":"user-or-llm","description":"The option label"},"rank":{"type":"number","required":false,"visibility":"user-or-llm","description":"Sort order. Required on a ranked-dropdown or status-dropdown option"},"color":{"type":"string","required":false,"visibility":"user-or-llm","description":"Option color: white, gray, blue, green, purple, orange, or red. Required on a ranked-dropdown or status-dropdown option"},"statusCategory":{"type":"string","required":false,"visibility":"user-or-llm","description":"Pipeline meaning of the option: open, won, lost, or on-hold. Status-dropdown options only"},"winRate":{"type":"number","required":false,"visibility":"user-or-llm","description":"Expected win rate of the status. Status-dropdown options only"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_create_merge":{"id":"affinity_create_merge","name":"Affinity Create Merge","description":"Fold a duplicate company or person into the record you are keeping. The merge runs asynchronously — poll the returned task to see it finish. Requires the \\"Manage duplicates\\" permission and an admin role.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"entityType":{"type":"string","required":true,"visibility":"user-or-llm","description":"What to merge: companies or persons"},"primaryId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the record to keep"},"duplicateId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the duplicate record to fold in"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_create_note":{"id":"affinity_create_note","name":"Affinity Create Note","description":"Write a note — attached to companies, persons, and opportunities, anchored to a meeting, call, or chat message, or posted as a reply to an existing note.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"type":{"type":"string","required":true,"visibility":"user-or-llm","description":"Note shape: entities to attach it to records, interaction to anchor it to a meeting, call, or chat message, or user-reply to reply to a note"},"html":{"type":"string","required":true,"visibility":"user-or-llm","description":"The note body as HTML"},"companyIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Companies to attach the note to, e.g. [1, 2]. Not used on a reply"},"personIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Persons to attach the note to, e.g. [1, 2]. Not used on a reply"},"opportunityIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Opportunities to attach the note to, e.g. [1, 2]. Not used on a reply"},"interactionId":{"type":"string","required":false,"visibility":"user-or-llm","description":"The interaction to anchor the note to. Required for an interaction note"},"interactionType":{"type":"string","required":false,"visibility":"user-or-llm","description":"Kind of the anchoring interaction: meeting, call, or chat-message. Required for an interaction note"},"parentId":{"type":"string","required":false,"visibility":"user-or-llm","description":"The note being replied to. Required for a user-reply note"},"creatorId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Attribute the note to another internal person. Defaults to the API key holder"},"createdAt":{"type":"string","required":false,"visibility":"user-or-llm","description":"Backdate the note to this ISO 8601 timestamp"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_create_reminder":{"id":"affinity_create_reminder","name":"Affinity Create Reminder","description":"Create a reminder on one company, person, or opportunity. A recurring reminder resets whenever the chosen signal happens instead of firing once.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"type":{"type":"string","required":true,"visibility":"user-or-llm","description":"one-time to fire once, or recurring to reset on a signal"},"entityType":{"type":"string","required":true,"visibility":"user-or-llm","description":"What the reminder is about: company, person, or opportunity"},"entityId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of that company, person, or opportunity"},"dueDate":{"type":"string","required":false,"visibility":"user-or-llm","description":"When the reminder is due, as an ISO 8601 timestamp. Required for a one-time reminder; on a recurring one Affinity computes it from the period when omitted"},"content":{"type":"string","required":false,"visibility":"user-or-llm","description":"What the reminder says"},"ownerId":{"type":"string","required":true,"visibility":"user-or-llm","description":"User the reminder is assigned to. Must be an internal user. The API key holder is recorded as the creator, which is a separate field"},"resetTrigger":{"type":"string","required":false,"visibility":"user-or-llm","description":"What restarts a recurring reminder: interaction, email, or event. Required when the type is recurring"},"periodDays":{"type":"number","required":false,"visibility":"user-or-llm","description":"Days between firings of a recurring reminder. Required when the type is recurring"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_delete_list_field_dropdown_option":{"id":"affinity_delete_list_field_dropdown_option","name":"Affinity Delete List Field Dropdown Option","description":"Permanently delete a dropdown option on a list field. Every list entry currently set to it is cleared, and those values cannot be recovered.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"},"fieldId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The dropdown field ID on that list"},"dropdownOptionId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The dropdown option ID to delete"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_delete_note":{"id":"affinity_delete_note","name":"Affinity Delete Note","description":"Delete a note you created. Deleting a root note also deletes its replies; deleting a reply removes only that reply.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"noteId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The note ID to delete"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_get_company":{"id":"affinity_get_company","name":"Affinity Get Company","description":"Look up one company by ID. Field data is returned only for the Field IDs or Field Types asked for.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"companyId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The company ID"},"fieldIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field IDs to return values for, e.g. [\\"affinity-data-location\\"]. Mutually exclusive with Field Types"},"fieldTypes":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field categories to return values for: enriched, global, or relationship-intelligence. Mutually exclusive with Field IDs"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_get_current_user":{"id":"affinity_get_current_user","name":"Affinity Get Current User","description":"Verify an Affinity API key and return the tenant, the user behind the key, and the scopes the grant carries.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_get_entity_field_value":{"id":"affinity_get_entity_field_value","name":"Affinity Get Entity Field Value","description":"Read one non-list field value from a company or person.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"entityType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Which entity to read the field from: companies or persons"},"entityId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of that company or person"},"fieldId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The field ID to read"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_get_list":{"id":"affinity_get_list","name":"Affinity Get List","description":"Read one list — its name, type, owner, and privacy setting.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_get_list_entry":{"id":"affinity_get_list_entry","name":"Affinity Get List Entry","description":"Read one row of a list with its entity. Field data is returned only for the Field IDs or Field Types asked for.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"},"listEntryId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list entry ID"},"fieldIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field IDs to return values for, e.g. [\\"affinity-data-location\\"]. Mutually exclusive with Field Types"},"fieldTypes":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field categories to return values for: enriched, global, list, or relationship-intelligence. Mutually exclusive with Field IDs"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_get_list_entry_field":{"id":"affinity_get_list_entry_field","name":"Affinity Get List Entry Field","description":"Read one field value on a list row.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"},"listEntryId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list entry ID"},"fieldId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The field ID to read"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_get_list_field_dropdown_option":{"id":"affinity_get_list_field_dropdown_option","name":"Affinity Get List Field Dropdown Option","description":"Read one dropdown option on a list field.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"},"fieldId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The dropdown field ID on that list"},"dropdownOptionId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The dropdown option ID"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_get_merge":{"id":"affinity_get_merge","name":"Affinity Get Merge","description":"Read the status of one company or person merge, including why it failed if it did.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"entityType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Which merge to read: companies or persons"},"mergeId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The merge ID"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_get_merge_task":{"id":"affinity_get_merge_task","name":"Affinity Get Merge Task","description":"Read one merge task and how its merges are progressing. Poll this after starting a merge.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"entityType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Which merge task to read: companies or persons"},"taskId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The merge task ID"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_get_note":{"id":"affinity_get_note","name":"Affinity Get Note","description":"Read one note with its body, author, mentions, and attached records.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"noteId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The note ID"},"includes":{"type":"json","required":false,"visibility":"user-or-llm","description":"Extra properties to return, e.g. [\\"repliesCount\\",\\"personsPreview\\",\\"companiesPreview\\",\\"opportunitiesPreview\\"]. Those four fields are omitted unless requested here"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_get_opportunity":{"id":"affinity_get_opportunity","name":"Affinity Get Opportunity","description":"Read one opportunity and the list it belongs to. Its field data lives on the list entry.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"opportunityId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The opportunity ID"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_get_person":{"id":"affinity_get_person","name":"Affinity Get Person","description":"Look up one person by ID. Field data is returned only for the Field IDs or Field Types asked for.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"personId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The person ID"},"fieldIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field IDs to return values for, e.g. [\\"affinity-data-location\\"]. Mutually exclusive with Field Types"},"fieldTypes":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field categories to return values for: enriched, global, or relationship-intelligence. Mutually exclusive with Field IDs"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_get_saved_view":{"id":"affinity_get_saved_view","name":"Affinity Get Saved View","description":"Read one saved view — its name, kind, and creation date.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"},"viewId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The saved view ID"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_get_transcript":{"id":"affinity_get_transcript","name":"Affinity Get Transcript","description":"Read one transcript with its first 100 fragments. Page the fragments endpoint for a longer meeting.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"transcriptId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The transcript ID"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_get_user":{"id":"affinity_get_user","name":"Affinity Get User","description":"Read one internal user. A user and their person record share the same numeric ID, so a person ID works here.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"userId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The user ID, which is also their person ID"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_calls":{"id":"affinity_list_calls","name":"Affinity List Calls","description":"Page through logged calls and their participants. Only calls the API key holder can see are returned.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression, e.g. \\"createdAt>=2026-01-01\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_chat_messages":{"id":"affinity_list_chat_messages","name":"Affinity List Chat Messages","description":"Page through logged chat messages and their participants. Only messages the API key holder can see are returned.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression, e.g. \\"createdAt>=2026-01-01\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_companies":{"id":"affinity_list_companies","name":"Affinity List Companies","description":"Page through companies. Companies come back without field data unless Field IDs or Field Types asks for it.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"ids":{"type":"json","required":false,"visibility":"user-or-llm","description":"Restrict the page to these company IDs, e.g. [1, 2, 3]"},"fieldIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field IDs to return values for, e.g. [\\"affinity-data-location\\"]. Mutually exclusive with Field Types"},"fieldTypes":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field categories to return values for: enriched, global, or relationship-intelligence. Mutually exclusive with Field IDs"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_coworker_connections":{"id":"affinity_list_coworker_connections","name":"Affinity List Coworker Connections","description":"Find warm paths into a company through shared work history: who in your Affinity data once worked alongside the people you want to reach. Grouped by target, strongest first.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"filter":{"type":"string","required":true,"visibility":"user-or-llm","description":"Required scope. The only supported filter is target.currentCompany.id, e.g. \\"target.currentCompany.id=123\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of targets to return per page, 1-50. Defaults to 20"},"totalCount":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Include the total size of the collection. Costs an extra query"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_emails":{"id":"affinity_list_emails","name":"Affinity List Emails","description":"Page through email metadata — subject, participants, and timestamps. Affinity never exposes email bodies through the API.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression, e.g. \\"createdAt>=2026-01-01\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_entity_field_values":{"id":"affinity_list_entity_field_values","name":"Affinity List Entity Field Values","description":"Page through a company\'s or person\'s non-list field values. List fields are not returned here — read those through the list entry.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"entityType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Which entity to read field values from: companies or persons"},"entityId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of that company or person"},"ids":{"type":"json","required":false,"visibility":"user-or-llm","description":"Restrict to these field IDs. Mutually exclusive with Field Types"},"types":{"type":"json","required":false,"visibility":"user-or-llm","description":"Restrict to these field categories: enriched, global, relationship-intelligence. Mutually exclusive with Field IDs"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 20"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_entity_list_entries":{"id":"affinity_list_entity_list_entries","name":"Affinity List Entity List Entries","description":"Page through a company\'s or person\'s rows across every list, each carrying that list\'s field values and when the entity was added.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"entityType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Which entity to look up the rows of: companies or persons"},"entityId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of that company or person"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_entity_lists":{"id":"affinity_list_entity_lists","name":"Affinity List Entity Lists","description":"List every list a company or person appears on that the caller can view.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"entityType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Which entity to look up the lists of: companies or persons"},"entityId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of that company or person"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_entity_notes":{"id":"affinity_list_entity_notes","name":"Affinity List Entity Notes","description":"List the notes relevant to one company, person, or opportunity — directly attached notes plus notes reaching it through its people and meetings.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"entityType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Which entity the notes hang off: companies, persons, or opportunities"},"entityId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of that company, person, or opportunity"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression, e.g. \\"createdAt>=2026-01-01\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"},"totalCount":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Include the total size of the collection. Costs an extra query"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_entity_relationships":{"id":"affinity_list_entity_relationships","name":"Affinity List Entity Relationships","description":"List who knows a company or person, scored 0.0 to 1.0 by how much the two actually interact. Strongest first by default.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"entityType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Which entity to look up relationships for: companies or persons"},"entityId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of that company or person"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression. This endpoint filters on interactionScore only, e.g. \\"interactionScore>=0.5\\""},"orderBy":{"type":"json","required":false,"visibility":"user-or-llm","description":"Sort order: [\\"interactionScore\\"] for weakest first, [\\"-interactionScore\\"] for strongest first (the default)"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"},"totalCount":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Include the total size of the collection. Costs an extra query"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_field_dropdown_options":{"id":"affinity_list_field_dropdown_options","name":"Affinity List Field Dropdown Options","description":"List the selectable options on a dropdown or ranked-dropdown company or person field. Writing such a field needs the option ID, not its text.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"entityType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Which field family the field belongs to: companies or persons"},"fieldId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The dropdown or ranked-dropdown field ID"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_field_metadata":{"id":"affinity_list_field_metadata","name":"Affinity List Field Metadata","description":"List the non-list company or person fields, with the value type, filter operators, and sort support of each. Start here to find the Field IDs the read and write tools take.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"entityType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Which fields to describe: companies or persons"},"includes":{"type":"json","required":false,"visibility":"user-or-llm","description":"Extra properties to return: [\\"filterability\\",\\"sortability\\"]. Both are omitted unless requested here"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression. This endpoint filters on name only, e.g. \\"name=~Status\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_field_value_changes":{"id":"affinity_list_field_value_changes","name":"Affinity List Field Value Changes","description":"Page through field value changes across the whole workspace. Built for delta sync: follow nextCursor to the end of a run, then resume from the last cursor next time.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression over field.id, listEntry.id, changer.id, changedAt, or actionType. Resume a sync with e.g. \\"changedAt>2026-06-01T12:00:00Z\\""},"orderBy":{"type":"json","required":false,"visibility":"user-or-llm","description":"Sort order: [\\"changedAt\\"] for oldest first (the default), [\\"-changedAt\\"] for newest first"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_investor_executive_connections":{"id":"affinity_list_investor_executive_connections","name":"Affinity List Investor Executive Connections","description":"Find warm paths into a company through investment history: which investors in your Affinity data backed a company the people you want to reach once led. Grouped by target, strongest first.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"filter":{"type":"string","required":true,"visibility":"user-or-llm","description":"Required scope. The only supported filter is target.currentCompany.id, e.g. \\"target.currentCompany.id=123\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of targets to return per page, 1-50. Defaults to 20"},"totalCount":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Include the total size of the collection. Costs an extra query"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_list_entries":{"id":"affinity_list_list_entries","name":"Affinity List List Entries","description":"Page through the rows of a list. Rows come back without field data unless Field IDs or Field Types asks for it.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"},"fieldIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field IDs to return values for, e.g. [\\"affinity-data-location\\"]. Mutually exclusive with Field Types"},"fieldTypes":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field categories to return values for: enriched, global, list, or relationship-intelligence. Mutually exclusive with Field IDs"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_list_entry_field_value_changes":{"id":"affinity_list_list_entry_field_value_changes","name":"Affinity List List Entry Field Value Changes","description":"Page through the history of one list row — who changed which field, when, and to what.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"},"listEntryId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list entry ID"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression over field.id, changer.id, changedAt, or actionType, e.g. \\"field.id=field-1234\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_list_entry_fields":{"id":"affinity_list_list_entry_fields","name":"Affinity List List Entry Fields","description":"Page through every field value on one list row, including the list-specific columns. All fields are returned unless narrowed.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"},"listEntryId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list entry ID"},"ids":{"type":"json","required":false,"visibility":"user-or-llm","description":"Restrict to these field IDs. Mutually exclusive with Field Types"},"types":{"type":"json","required":false,"visibility":"user-or-llm","description":"Restrict to these field categories: enriched, global, list, relationship-intelligence. Mutually exclusive with Field IDs"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 20"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_list_field_dropdown_options":{"id":"affinity_list_list_field_dropdown_options","name":"Affinity List List Field Dropdown Options","description":"List the selectable options on a dropdown, ranked-dropdown, or status-dropdown field of a list.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"},"fieldId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The dropdown field ID on that list"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_list_fields":{"id":"affinity_list_list_fields","name":"Affinity List List Fields","description":"List the fields available on one list, including its list-specific columns. Use these Field IDs when reading or writing list entries.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"},"includes":{"type":"json","required":false,"visibility":"user-or-llm","description":"Extra properties to return: [\\"filterability\\",\\"sortability\\"]. Both are omitted unless requested here"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression. This endpoint filters on name only, e.g. \\"name=~Stage\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_lists":{"id":"affinity_list_lists","name":"Affinity List Lists","description":"Page through the lists in the organization that the caller can view.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"term":{"type":"string","required":false,"visibility":"user-or-llm","description":"Case-insensitive substring match on the list name"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_meetings":{"id":"affinity_list_meetings","name":"Affinity List Meetings","description":"Page through past and upcoming meetings with their organizer and attendees.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression, e.g. \\"createdAt>=2026-01-01\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_merge_tasks":{"id":"affinity_list_merge_tasks","name":"Affinity List Merge Tasks","description":"Page through merge tasks, each summarizing how many of its merges are in progress, succeeded, or failed.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"entityType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Which merge tasks to list: companies or persons"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression. This endpoint filters on status only, e.g. \\"status=in-progress\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_merges":{"id":"affinity_list_merges","name":"Affinity List Merges","description":"Page through the company or person merges the organization has run, with the status and the records involved in each.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"entityType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Which merges to list: companies or persons"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression over status or taskId, e.g. \\"status=failed\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_note_attached_companies":{"id":"affinity_list_note_attached_companies","name":"Affinity List Note Attached Companies","description":"List the companies directly attached to one note.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"noteId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The note ID"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"},"totalCount":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Include the total size of the collection. Costs an extra query"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_note_attached_opportunities":{"id":"affinity_list_note_attached_opportunities","name":"Affinity List Note Attached Opportunities","description":"List the opportunities directly attached to one note.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"noteId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The note ID"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"},"totalCount":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Include the total size of the collection. Costs an extra query"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_note_attached_persons":{"id":"affinity_list_note_attached_persons","name":"Affinity List Note Attached Persons","description":"List the persons directly attached to one note.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"noteId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The note ID"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"},"totalCount":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Include the total size of the collection. Costs an extra query"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_note_replies":{"id":"affinity_list_note_replies","name":"Affinity List Note Replies","description":"Page through the replies on one note, including AI Notetaker replies.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"noteId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The note ID whose replies to read"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression, e.g. \\"createdAt>=2026-01-01\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"},"totalCount":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Include the total size of the collection. Costs an extra query"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_notes":{"id":"affinity_list_notes","name":"Affinity List Notes","description":"Page through every note the caller can see. Replies are excluded.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"includes":{"type":"json","required":false,"visibility":"user-or-llm","description":"Extra properties to return, e.g. [\\"repliesCount\\",\\"personsPreview\\",\\"companiesPreview\\",\\"opportunitiesPreview\\"]. Those four fields are omitted unless requested here"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression, e.g. \\"createdAt>=2026-01-01\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"},"totalCount":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Include the total size of the collection. Costs an extra query"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_opportunities":{"id":"affinity_list_opportunities","name":"Affinity List Opportunities","description":"Page through opportunities. Field data lives on the list entry, not here — read it through the list or saved view the opportunity belongs to.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"ids":{"type":"json","required":false,"visibility":"user-or-llm","description":"Restrict the page to these opportunity IDs, e.g. [1, 2, 3]"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_persons":{"id":"affinity_list_persons","name":"Affinity List Persons","description":"Page through persons. Persons come back without field data unless Field IDs or Field Types asks for it.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"ids":{"type":"json","required":false,"visibility":"user-or-llm","description":"Restrict the page to these person IDs, e.g. [1, 2, 3]"},"fieldIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field IDs to return values for, e.g. [\\"affinity-data-location\\"]. Mutually exclusive with Field Types"},"fieldTypes":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field categories to return values for: enriched, global, or relationship-intelligence. Mutually exclusive with Field IDs"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_reminders":{"id":"affinity_list_reminders","name":"Affinity List Reminders","description":"Page through the reminders the caller can see. Filter by status to surface what is overdue.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression, e.g. \\"createdAt>=2026-01-01\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"},"totalCount":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Include the total size of the collection. Costs an extra query"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_saved_view_entries":{"id":"affinity_list_saved_view_entries","name":"Affinity List Saved View Entries","description":"Page through the rows of a saved view. The view\'s own filters and columns decide which rows and which field data come back.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"},"viewId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The saved view ID"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_saved_views":{"id":"affinity_list_saved_views","name":"Affinity List Saved Views","description":"List the saved views on a list that the caller can view.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_transcript_fragments":{"id":"affinity_list_transcript_fragments","name":"Affinity List Transcript Fragments","description":"Page through everything said in a meeting, segment by segment with the speaker.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"transcriptId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The transcript ID"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"},"totalCount":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Include the total size of the collection. Costs an extra query"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_transcripts":{"id":"affinity_list_transcripts","name":"Affinity List Transcripts","description":"Page through meeting transcript metadata. Read one transcript to get what was actually said.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression, e.g. \\"createdAt>=2026-01-01\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"},"totalCount":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Include the total size of the collection. Costs an extra query"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_list_users":{"id":"affinity_list_users","name":"Affinity List Users","description":"Page through the internal users in the organization. Email addresses and roles are returned only to callers with the \\"Manage Users\\" permission.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"term":{"type":"string","required":false,"visibility":"user-or-llm","description":"Case-insensitive match across first name, last name, and primary email"},"filter":{"type":"string","required":false,"visibility":"user-or-llm","description":"Affinity Filtering Language expression over id or status, e.g. \\"status=active\\""},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_search_companies":{"id":"affinity_search_companies","name":"Affinity Search Companies","description":"Search companies by filters, sorts, and a free-text term. Requires the \\"Export All Organizations directory\\" permission.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"filters":{"type":"json","required":false,"visibility":"user-or-llm","description":"Filter group as {operator: \\"and\\"|\\"or\\", filters: [...]}, at most 50 leaves. Each leaf is {valueType, fieldId, operator, value}, and a leaf may itself be a nested group"},"searchTerm":{"type":"string","required":false,"visibility":"user-or-llm","description":"Free-text term matched against the searchable fields. At least 3 characters"},"searchFieldIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field IDs the search term is matched against. Defaults to the searchable fields"},"sorts":{"type":"json","required":false,"visibility":"user-or-llm","description":"Sort order as [{fieldId, direction: \\"asc\\"|\\"desc\\", attributeId?}], up to 5, applied in order"},"fieldIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field IDs to return values for, e.g. [\\"affinity-data-location\\"]. Mutually exclusive with Field Types"},"fieldTypes":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field categories to return values for: enriched, global, or relationship-intelligence. Mutually exclusive with Field IDs"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"},"totalCount":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Include the total size of the collection. Costs an extra query"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_search_files":{"id":"affinity_search_files","name":"Affinity Search Files","description":"Search files by keyword, ordered by relevance. Narrow to specific files or to one company, or leave both unset to search the whole account.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"prompt":{"type":"string","required":true,"visibility":"user-or-llm","description":"What to search for. Between 3 and 500 characters"},"ids":{"type":"json","required":false,"visibility":"user-or-llm","description":"Restrict the search to these file IDs. Cannot be combined with Company ID"},"companyId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Restrict the search to one company\'s files. Cannot be combined with file IDs"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of files to return, 1-100. Defaults to 20"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_search_list_entries":{"id":"affinity_search_list_entries","name":"Affinity Search List Entries","description":"Search the rows of one list by filters, sorts, and a free-text term. Requires the \\"Export data from Lists\\" permission.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID to search"},"filters":{"type":"json","required":false,"visibility":"user-or-llm","description":"Filter group as {operator: \\"and\\"|\\"or\\", filters: [...]}, at most 50 leaves. Each leaf is {valueType, fieldId, operator, value}, and a leaf may itself be a nested group"},"searchTerm":{"type":"string","required":false,"visibility":"user-or-llm","description":"Free-text term matched against the searchable fields. At least 3 characters"},"searchFieldIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field IDs the search term is matched against. Defaults to the searchable fields"},"sorts":{"type":"json","required":false,"visibility":"user-or-llm","description":"Sort order as [{fieldId, direction: \\"asc\\"|\\"desc\\", attributeId?}], up to 5, applied in order"},"fieldIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field IDs to return values for, e.g. [\\"affinity-data-location\\"]. Mutually exclusive with Field Types"},"fieldTypes":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field categories to return values for: enriched, global, list, or relationship-intelligence. Mutually exclusive with Field IDs"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"},"totalCount":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Include the total size of the collection. Costs an extra query"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_search_notes":{"id":"affinity_search_notes","name":"Affinity Search Notes","description":"Search notes by keyword, ordered by relevance. Narrow to specific notes or to one company, or leave both unset to search the whole account.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"prompt":{"type":"string","required":true,"visibility":"user-or-llm","description":"What to search for. Between 3 and 500 characters"},"ids":{"type":"json","required":false,"visibility":"user-or-llm","description":"Restrict the search to these note IDs. Cannot be combined with Company ID"},"companyId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Restrict the search to one company\'s notes. Cannot be combined with note IDs"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of notes to return, 1-100. Defaults to 20"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_search_persons":{"id":"affinity_search_persons","name":"Affinity Search Persons","description":"Search persons by filters, sorts, and a free-text term. Requires the \\"Export All People directory\\" permission.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"filters":{"type":"json","required":false,"visibility":"user-or-llm","description":"Filter group as {operator: \\"and\\"|\\"or\\", filters: [...]}, at most 50 leaves. Each leaf is {valueType, fieldId, operator, value}, and a leaf may itself be a nested group"},"searchTerm":{"type":"string","required":false,"visibility":"user-or-llm","description":"Free-text term matched against the searchable fields. At least 3 characters"},"searchFieldIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field IDs the search term is matched against. Defaults to the searchable fields"},"sorts":{"type":"json","required":false,"visibility":"user-or-llm","description":"Sort order as [{fieldId, direction: \\"asc\\"|\\"desc\\", attributeId?}], up to 5, applied in order"},"fieldIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field IDs to return values for, e.g. [\\"affinity-data-location\\"]. Mutually exclusive with Field Types"},"fieldTypes":{"type":"json","required":false,"visibility":"user-or-llm","description":"Field categories to return values for: enriched, global, or relationship-intelligence. Mutually exclusive with Field IDs"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous page, returned as nextCursor or prevCursor"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to return per page, 1-100. Defaults to 100"},"totalCount":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Include the total size of the collection. Costs an extra query"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_semantic_search":{"id":"affinity_semantic_search","name":"Affinity Semantic Search","description":"Find companies from a description in plain language — industry, technology, stage, or business model. Currently searches companies only.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"prompt":{"type":"string","required":true,"visibility":"user-or-llm","description":"What to look for, in plain language, e.g. \\"climate tech companies in our pipeline\\". Up to 500 characters"},"listIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Restrict the search to companies on these lists, e.g. [1, 2]"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of companies to return, 1-100. Defaults to 100"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_update_entity_field_value":{"id":"affinity_update_entity_field_value","name":"Affinity Update Entity Field Value","description":"Write one non-list field value on a company or person. The value type must match how the field is defined.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"entityType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Which entity to write the field on: companies or persons"},"entityId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of that company or person"},"fieldId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The field ID to write"},"value":{"type":"json","required":true,"visibility":"user-or-llm","description":"The new value as {type, data}, where type matches the field\'s value type. Examples: {\\"type\\":\\"text\\",\\"data\\":\\"Series B\\"}, {\\"type\\":\\"number\\",\\"data\\":42}, {\\"type\\":\\"dropdown\\",\\"data\\":{\\"dropdownOptionId\\":7}}, {\\"type\\":\\"person\\",\\"data\\":{\\"id\\":123}}, {\\"type\\":\\"person-multi\\",\\"data\\":[{\\"id\\":123}]}. Pass data as null to clear the field"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_update_list_entry_field":{"id":"affinity_update_list_entry_field","name":"Affinity Update List Entry Field","description":"Write one field value on a list row. Requires the \\"Export data from Lists\\" permission.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"},"listEntryId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list entry ID"},"fieldId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The field ID to write"},"value":{"type":"json","required":true,"visibility":"user-or-llm","description":"The new value as {type, data}, where type matches the field\'s value type. Examples: {\\"type\\":\\"text\\",\\"data\\":\\"Series B\\"}, {\\"type\\":\\"number\\",\\"data\\":42}, {\\"type\\":\\"dropdown\\",\\"data\\":{\\"dropdownOptionId\\":7}}, {\\"type\\":\\"person\\",\\"data\\":{\\"id\\":123}}, {\\"type\\":\\"person-multi\\",\\"data\\":[{\\"id\\":123}]}. Pass data as null to clear the field"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_update_list_field_dropdown_option":{"id":"affinity_update_list_field_dropdown_option","name":"Affinity Update List Field Dropdown Option","description":"Change a dropdown option on a list field. Every field is optional — supply only what should change, and only fields the option\'s kind actually has.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"listId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The list ID"},"fieldId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The dropdown field ID on that list"},"dropdownOptionId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The dropdown option ID to update"},"text":{"type":"string","required":false,"visibility":"user-or-llm","description":"Replacement option label. Supply at least one field to change"},"rank":{"type":"number","required":false,"visibility":"user-or-llm","description":"Sort order. Required on a ranked-dropdown or status-dropdown option"},"color":{"type":"string","required":false,"visibility":"user-or-llm","description":"Option color: white, gray, blue, green, purple, orange, or red. Required on a ranked-dropdown or status-dropdown option"},"statusCategory":{"type":"string","required":false,"visibility":"user-or-llm","description":"Pipeline meaning of the option: open, won, lost, or on-hold. Status-dropdown options only"},"winRate":{"type":"number","required":false,"visibility":"user-or-llm","description":"Expected win rate of the status. Status-dropdown options only"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"affinity_update_note":{"id":"affinity_update_note","name":"Affinity Update Note","description":"Rewrite a note\'s body or replace which records it is attached to. Each list of IDs replaces that association wholesale, an empty list clears it, and omitting one leaves it untouched. A note\'s type cannot be changed.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Affinity API key, sent as a bearer token"},"noteId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The note ID to update"},"html":{"type":"string","required":false,"visibility":"user-or-llm","description":"Replacement note body as HTML"},"companyIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Replacement set of attached companies, e.g. [1, 2]. Send [] to detach every company; omit to leave them unchanged"},"personIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Replacement set of attached persons, e.g. [1, 2]. Send [] to detach every person; omit to leave them unchanged"},"opportunityIds":{"type":"json","required":false,"visibility":"user-or-llm","description":"Replacement set of attached opportunities, e.g. [1, 2]. Send [] to detach every opportunity; omit to leave them unchanged"}},"oauth":{"required":false,"provider":"affinity","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_create_draft":{"id":"agentmail_create_draft","name":"Create Draft","description":"Create a new email draft in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox to create the draft in"},"to":{"type":"string","required":false,"visibility":"user-or-llm","description":"Recipient email addresses (comma-separated)"},"subject":{"type":"string","required":false,"visibility":"user-or-llm","description":"Draft subject line"},"text":{"type":"string","required":false,"visibility":"user-or-llm","description":"Plain text draft body"},"html":{"type":"string","required":false,"visibility":"user-or-llm","description":"HTML draft body"},"cc":{"type":"string","required":false,"visibility":"user-or-llm","description":"CC recipient email addresses (comma-separated)"},"bcc":{"type":"string","required":false,"visibility":"user-or-llm","description":"BCC recipient email addresses (comma-separated)"},"inReplyTo":{"type":"string","required":false,"visibility":"user-or-llm","description":"ID of message being replied to"},"sendAt":{"type":"string","required":false,"visibility":"user-or-llm","description":"ISO 8601 timestamp to schedule sending"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_create_inbox":{"id":"agentmail_create_inbox","name":"Create Inbox","description":"Create a new email inbox with AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"username":{"type":"string","required":false,"visibility":"user-or-llm","description":"Username for the inbox email address"},"domain":{"type":"string","required":false,"visibility":"user-or-llm","description":"Domain for the inbox email address"},"displayName":{"type":"string","required":false,"visibility":"user-or-llm","description":"Display name for the inbox"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_delete_draft":{"id":"agentmail_delete_draft","name":"Delete Draft","description":"Delete an email draft in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox containing the draft"},"draftId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the draft to delete"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_delete_inbox":{"id":"agentmail_delete_inbox","name":"Delete Inbox","description":"Delete an email inbox in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox to delete"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_delete_thread":{"id":"agentmail_delete_thread","name":"Delete Thread","description":"Delete an email thread in AgentMail (moves to trash, or permanently deletes if already in trash)","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox containing the thread"},"threadId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the thread to delete"},"permanent":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Force permanent deletion instead of moving to trash"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_forward_message":{"id":"agentmail_forward_message","name":"Forward Message","description":"Forward an email message to new recipients in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox containing the message"},"messageId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the message to forward"},"to":{"type":"string","required":true,"visibility":"user-or-llm","description":"Recipient email addresses (comma-separated)"},"subject":{"type":"string","required":false,"visibility":"user-or-llm","description":"Override subject line"},"text":{"type":"string","required":false,"visibility":"user-or-llm","description":"Additional plain text to prepend"},"html":{"type":"string","required":false,"visibility":"user-or-llm","description":"Additional HTML to prepend"},"cc":{"type":"string","required":false,"visibility":"user-or-llm","description":"CC recipient email addresses (comma-separated)"},"bcc":{"type":"string","required":false,"visibility":"user-or-llm","description":"BCC recipient email addresses (comma-separated)"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_get_draft":{"id":"agentmail_get_draft","name":"Get Draft","description":"Get details of a specific email draft in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox the draft belongs to"},"draftId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the draft to retrieve"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_get_inbox":{"id":"agentmail_get_inbox","name":"Get Inbox","description":"Get details of a specific email inbox in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox to retrieve"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_get_message":{"id":"agentmail_get_message","name":"Get Message","description":"Get details of a specific email message in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox containing the message"},"messageId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the message to retrieve"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_get_thread":{"id":"agentmail_get_thread","name":"Get Thread","description":"Get details of a specific email thread including messages in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox containing the thread"},"threadId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the thread to retrieve"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_list_drafts":{"id":"agentmail_list_drafts","name":"List Drafts","description":"List email drafts in an inbox in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox to list drafts from"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of drafts to return"},"pageToken":{"type":"string","required":false,"visibility":"user-or-llm","description":"Pagination token for next page of results"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_list_inboxes":{"id":"agentmail_list_inboxes","name":"List Inboxes","description":"List all email inboxes in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of inboxes to return"},"pageToken":{"type":"string","required":false,"visibility":"user-or-llm","description":"Pagination token for next page of results"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_list_messages":{"id":"agentmail_list_messages","name":"List Messages","description":"List messages in an inbox in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox to list messages from"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of messages to return"},"pageToken":{"type":"string","required":false,"visibility":"user-or-llm","description":"Pagination token for next page of results"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_list_threads":{"id":"agentmail_list_threads","name":"List Threads","description":"List email threads in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox to list threads from"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of threads to return"},"pageToken":{"type":"string","required":false,"visibility":"user-or-llm","description":"Pagination token for next page of results"},"labels":{"type":"string","required":false,"visibility":"user-or-llm","description":"Comma-separated labels to filter threads by"},"before":{"type":"string","required":false,"visibility":"user-or-llm","description":"Filter threads before this ISO 8601 timestamp"},"after":{"type":"string","required":false,"visibility":"user-or-llm","description":"Filter threads after this ISO 8601 timestamp"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_reply_message":{"id":"agentmail_reply_message","name":"Reply to Message","description":"Reply to an existing email message in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox to reply from"},"messageId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the message to reply to"},"text":{"type":"string","required":false,"visibility":"user-or-llm","description":"Plain text reply body"},"html":{"type":"string","required":false,"visibility":"user-or-llm","description":"HTML reply body"},"to":{"type":"string","required":false,"visibility":"user-or-llm","description":"Override recipient email addresses (comma-separated)"},"cc":{"type":"string","required":false,"visibility":"user-or-llm","description":"CC email addresses (comma-separated)"},"bcc":{"type":"string","required":false,"visibility":"user-or-llm","description":"BCC email addresses (comma-separated)"},"replyAll":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Reply to all recipients of the original message"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_send_draft":{"id":"agentmail_send_draft","name":"Send Draft","description":"Send an existing email draft in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox containing the draft"},"draftId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the draft to send"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_send_message":{"id":"agentmail_send_message","name":"Send Message","description":"Send an email message from an AgentMail inbox","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox to send from"},"to":{"type":"string","required":true,"visibility":"user-or-llm","description":"Recipient email address (comma-separated for multiple)"},"subject":{"type":"string","required":true,"visibility":"user-or-llm","description":"Email subject line"},"text":{"type":"string","required":false,"visibility":"user-or-llm","description":"Plain text email body"},"html":{"type":"string","required":false,"visibility":"user-or-llm","description":"HTML email body"},"cc":{"type":"string","required":false,"visibility":"user-or-llm","description":"CC recipient email addresses (comma-separated)"},"bcc":{"type":"string","required":false,"visibility":"user-or-llm","description":"BCC recipient email addresses (comma-separated)"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_update_draft":{"id":"agentmail_update_draft","name":"Update Draft","description":"Update an existing email draft in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox containing the draft"},"draftId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the draft to update"},"to":{"type":"string","required":false,"visibility":"user-or-llm","description":"Recipient email addresses (comma-separated)"},"subject":{"type":"string","required":false,"visibility":"user-or-llm","description":"Draft subject line"},"text":{"type":"string","required":false,"visibility":"user-or-llm","description":"Plain text draft body"},"html":{"type":"string","required":false,"visibility":"user-or-llm","description":"HTML draft body"},"cc":{"type":"string","required":false,"visibility":"user-or-llm","description":"CC recipient email addresses (comma-separated)"},"bcc":{"type":"string","required":false,"visibility":"user-or-llm","description":"BCC recipient email addresses (comma-separated)"},"sendAt":{"type":"string","required":false,"visibility":"user-or-llm","description":"ISO 8601 timestamp to schedule sending"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_update_inbox":{"id":"agentmail_update_inbox","name":"Update Inbox","description":"Update the display name of an email inbox in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox to update"},"displayName":{"type":"string","required":true,"visibility":"user-or-llm","description":"New display name for the inbox"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_update_message":{"id":"agentmail_update_message","name":"Update Message","description":"Add or remove labels on an email message in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox containing the message"},"messageId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the message to update"},"addLabels":{"type":"string","required":false,"visibility":"user-or-llm","description":"Comma-separated labels to add to the message"},"removeLabels":{"type":"string","required":false,"visibility":"user-or-llm","description":"Comma-separated labels to remove from the message"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentmail_update_thread":{"id":"agentmail_update_thread","name":"Update Thread Labels","description":"Add or remove labels on an email thread in AgentMail","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentMail API key"},"inboxId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the inbox containing the thread"},"threadId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the thread to update"},"addLabels":{"type":"string","required":false,"visibility":"user-or-llm","description":"Comma-separated labels to add to the thread"},"removeLabels":{"type":"string","required":false,"visibility":"user-or-llm","description":"Comma-separated labels to remove from the thread"}},"oauth":{"required":false,"provider":"agentmail","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_create_call":{"id":"agentphone_create_call","name":"Create Outbound Call","description":"Initiate an outbound voice call from an AgentPhone agent","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"agentId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Agent that will handle the call"},"toNumber":{"type":"string","required":true,"visibility":"user-or-llm","description":"Phone number to call in E.164 format (e.g. +14155551234)"},"fromNumberId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Phone number ID to use as caller ID. Must belong to the agent. If omitted, the agent\'s first assigned number is used."},"initialGreeting":{"type":"string","required":false,"visibility":"user-or-llm","description":"Optional greeting spoken when the recipient answers"},"voice":{"type":"string","required":false,"visibility":"user-or-llm","description":"Voice ID override for this call (defaults to the agent\'s configured voice)"},"systemPrompt":{"type":"string","required":false,"visibility":"user-or-llm","description":"When provided, uses a built-in LLM for the conversation instead of forwarding to your webhook"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_create_contact":{"id":"agentphone_create_contact","name":"Create Contact","description":"Create a new contact in AgentPhone","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"phoneNumber":{"type":"string","required":true,"visibility":"user-or-llm","description":"Phone number in E.164 format (e.g. +14155551234)"},"name":{"type":"string","required":true,"visibility":"user-or-llm","description":"Contact\'s full name"},"email":{"type":"string","required":false,"visibility":"user-or-llm","description":"Contact\'s email address"},"notes":{"type":"string","required":false,"visibility":"user-or-llm","description":"Freeform notes stored on the contact"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_create_number":{"id":"agentphone_create_number","name":"Create Phone Number","description":"Provision a new SMS- and voice-enabled phone number","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"country":{"type":"string","required":false,"visibility":"user-or-llm","description":"Two-letter country code (e.g. US, CA). Defaults to US."},"areaCode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Preferred area code (US/CA only, e.g. \\"415\\"). Best-effort — may be ignored if unavailable."},"agentId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Optionally attach the number to an agent immediately"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_delete_contact":{"id":"agentphone_delete_contact","name":"Delete Contact","description":"Delete a contact by ID","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"contactId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Contact ID"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_get_call":{"id":"agentphone_get_call","name":"Get Call","description":"Fetch a call and its full transcript","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"callId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the call to retrieve"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_get_call_transcript":{"id":"agentphone_get_call_transcript","name":"Get Call Transcript","description":"Get the full ordered transcript for a call","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"callId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the call to retrieve the transcript for"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_get_contact":{"id":"agentphone_get_contact","name":"Get Contact","description":"Fetch a single contact by ID","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"contactId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Contact ID"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_get_conversation":{"id":"agentphone_get_conversation","name":"Get Conversation","description":"Get a conversation along with its recent messages","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"conversationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Conversation ID"},"messageLimit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of recent messages to include (default 50, max 100)"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_get_conversation_messages":{"id":"agentphone_get_conversation_messages","name":"Get Conversation Messages","description":"Get paginated messages for a conversation","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"conversationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Conversation ID"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of messages to return (default 50, max 200)"},"before":{"type":"string","required":false,"visibility":"user-or-llm","description":"Return messages received before this ISO 8601 timestamp"},"after":{"type":"string","required":false,"visibility":"user-or-llm","description":"Return messages received after this ISO 8601 timestamp"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_get_number_messages":{"id":"agentphone_get_number_messages","name":"Get Phone Number Messages","description":"Fetch messages received on a specific phone number","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"numberId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the phone number"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of messages to return (default 50, max 200)"},"before":{"type":"string","required":false,"visibility":"user-or-llm","description":"Return messages received before this ISO 8601 timestamp"},"after":{"type":"string","required":false,"visibility":"user-or-llm","description":"Return messages received after this ISO 8601 timestamp"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_get_usage":{"id":"agentphone_get_usage","name":"Get Usage","description":"Retrieve current usage statistics for the AgentPhone account","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_get_usage_daily":{"id":"agentphone_get_usage_daily","name":"Get Daily Usage","description":"Get a daily breakdown of usage (messages, calls, webhooks) for the last N days","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"days":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of days to return (1-365, default 30)"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_get_usage_monthly":{"id":"agentphone_get_usage_monthly","name":"Get Monthly Usage","description":"Get monthly usage aggregation (messages, calls, webhooks) for the last N months","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"months":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of months to return (1-24, default 6)"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_list_calls":{"id":"agentphone_list_calls","name":"List Calls","description":"List voice calls for this AgentPhone account","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of results to return (default 20, max 100)"},"offset":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of results to skip (min 0)"},"status":{"type":"string","required":false,"visibility":"user-or-llm","description":"Filter by status (completed, in-progress, failed)"},"direction":{"type":"string","required":false,"visibility":"user-or-llm","description":"Filter by direction (inbound, outbound)"},"type":{"type":"string","required":false,"visibility":"user-or-llm","description":"Filter by call type (pstn, web)"},"search":{"type":"string","required":false,"visibility":"user-or-llm","description":"Search by phone number (matches fromNumber or toNumber)"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_list_contacts":{"id":"agentphone_list_contacts","name":"List Contacts","description":"List contacts for this AgentPhone account","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"search":{"type":"string","required":false,"visibility":"user-or-llm","description":"Filter by name or phone number (case-insensitive contains)"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of results to return (default 50, max 200)"},"offset":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of results to skip (min 0)"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_list_conversations":{"id":"agentphone_list_conversations","name":"List Conversations","description":"List conversations (message threads) for this AgentPhone account","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of results to return (default 20, max 100)"},"offset":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of results to skip (min 0)"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_list_numbers":{"id":"agentphone_list_numbers","name":"List Phone Numbers","description":"List all phone numbers provisioned for this AgentPhone account","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of results to return (default 20, max 100)"},"offset":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of results to skip (min 0)"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_react_to_message":{"id":"agentphone_react_to_message","name":"React to Message","description":"Send an iMessage tapback reaction to a message (iMessage only)","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"messageId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the message to react to"},"reaction":{"type":"string","required":true,"visibility":"user-or-llm","description":"Reaction type: love, like, dislike, laugh, emphasize, or question"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_release_number":{"id":"agentphone_release_number","name":"Release Phone Number","description":"Release (delete) a phone number. This action is irreversible.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"numberId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the phone number to release"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_send_message":{"id":"agentphone_send_message","name":"Send Message","description":"Send an outbound SMS or iMessage from an AgentPhone agent","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"agentId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Agent sending the message"},"toNumber":{"type":"string","required":true,"visibility":"user-or-llm","description":"Recipient phone number in E.164 format (e.g. +14155551234)"},"body":{"type":"string","required":true,"visibility":"user-or-llm","description":"Message text to send"},"mediaUrl":{"type":"string","required":false,"visibility":"user-or-llm","description":"Optional URL of an image, video, or file to attach"},"numberId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Phone number ID to send from. If omitted, the agent\'s first assigned number is used."}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_update_contact":{"id":"agentphone_update_contact","name":"Update Contact","description":"Update a contact\'s fields","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"contactId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Contact ID"},"phoneNumber":{"type":"string","required":false,"visibility":"user-or-llm","description":"New phone number in E.164 format"},"name":{"type":"string","required":false,"visibility":"user-or-llm","description":"New contact name"},"email":{"type":"string","required":false,"visibility":"user-or-llm","description":"New email address"},"notes":{"type":"string","required":false,"visibility":"user-or-llm","description":"New freeform notes"}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agentphone_update_conversation":{"id":"agentphone_update_conversation","name":"Update Conversation","description":"Update conversation metadata (stored state). Pass null to clear existing metadata.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"AgentPhone API key"},"conversationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Conversation ID"},"metadata":{"type":"json","required":false,"visibility":"user-or-llm","description":"Custom key-value metadata to store on the conversation. Pass null to clear existing metadata."}},"oauth":{"required":false,"provider":"agentphone","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"agiloft_async_status":{"id":"agiloft_async_status","name":"Agiloft Async Status","description":"Check whether an asynchronous Agiloft call, such as a run action button, has completed.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table the asynchronous call was made against"},"callbackId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Callback ID returned by the asynchronous call, e.g. from Run Action Button"}},"hostedApiKey":"none"},"agiloft_attach_file":{"id":"agiloft_attach_file","name":"Agiloft Attach File","description":"Attach a file to a field in an Agiloft record.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table name (e.g., \\"contracts\\")"},"recordId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the record to attach the file to"},"fieldName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the attachment field"},"file":{"type":"file","required":true,"visibility":"user-or-llm","description":"File to attach"},"fileName":{"type":"string","required":false,"visibility":"user-or-llm","description":"Name to assign to the file (defaults to original file name)"},"overwrite":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Replace the contents of the field instead of adding another file to it"}},"hostedApiKey":"none"},"agiloft_attachment_info":{"id":"agiloft_attachment_info","name":"Agiloft Attachment Info","description":"Get information about file attachments on a record field.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table name (e.g., \\"contracts\\")"},"recordId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the record to check attachments on"},"fieldName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the attachment field to inspect"}},"hostedApiKey":"none"},"agiloft_create_record":{"id":"agiloft_create_record","name":"Agiloft Create Record","description":"Create a new record in an Agiloft table.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table name (e.g., \\"contracts\\", \\"contacts.employees\\")"},"data":{"type":"string","required":true,"visibility":"user-or-llm","description":"Record field values as a JSON object (e.g., {\\"first_name\\": \\"John\\", \\"status\\": \\"Active\\"})"}},"hostedApiKey":"none"},"agiloft_delete_record":{"id":"agiloft_delete_record","name":"Agiloft Delete Record","description":"Delete a record from an Agiloft table.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table name (e.g., \\"contracts\\", \\"contacts.employees\\")"},"recordId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the record to delete"},"substituteIds":{"type":"string","required":false,"visibility":"user-or-llm","description":"Comma-separated IDs of records that adopt the dependants of the deleted record. Read only when the delete rule is REPLACE_WITH_ANOTHER."},"deleteRule":{"type":"string","required":false,"visibility":"user-or-llm","description":"How to treat records that depend on this one: ERROR_IF_DEPENDANTS (default — fails rather than cascading), APPLY_DELETE_WHERE_POSSIBLE, DELETE_WHERE_POSSIBLE_OTHERWISE_UNLINK, APPLY_UNLINK, UNLINK_WHERE_POSSIBLE_OTHERWISE_DELETE, or REPLACE_WITH_ANOTHER"}},"hostedApiKey":"none"},"agiloft_get_choice_line_id":{"id":"agiloft_get_choice_line_id","name":"Agiloft Get Choice Line ID","description":"Resolve the internal numeric ID of a choice-list value, for use in EWSelect WHERE clauses against choice fields.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table name (e.g., \\"case\\", \\"contracts\\")"},"fieldName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Choice field name (e.g., \\"priority\\", \\"status\\")"},"value":{"type":"string","required":true,"visibility":"user-or-llm","description":"Choice display value to resolve (e.g., \\"High\\", \\"Active\\")"}},"hostedApiKey":"none"},"agiloft_list_tables":{"id":"agiloft_list_tables","name":"Agiloft List Tables","description":"List the tables and fields in an Agiloft knowledge base, to discover the logical names other operations need.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":false,"visibility":"user-or-llm","description":"Logical name of a single table to describe (e.g., \\"contacts\\"). Leave empty to list every table in the knowledge base."},"includeLinkedInfo":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Include the source table and column behind each linked field"},"skipColumnsInfo":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Return table names only, omitting field details, for a much smaller response"}},"hostedApiKey":"none"},"agiloft_lock_record":{"id":"agiloft_lock_record","name":"Agiloft Lock Record","description":"Lock, unlock, or check the lock status of an Agiloft record.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table name (e.g., \\"contracts\\")"},"recordId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the record to lock, unlock, or check"},"lockAction":{"type":"string","required":true,"visibility":"user-or-llm","description":"Action to perform: \\"lock\\", \\"unlock\\", or \\"check\\""},"force":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Unlock only: release a lock held by another user."}},"hostedApiKey":"none"},"agiloft_nlp_search":{"id":"agiloft_nlp_search","name":"Agiloft Natural Language Search","description":"Search Agiloft records by describing what you want in plain language, such as \\"active NDAs submitted last month\\".","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"nlpQuery":{"type":"string","required":true,"visibility":"user-or-llm","description":"The request in plain language, e.g. \\"Show me open, high-priority contracts\\". Structured field filters are not accepted — use Search Records for those."},"fields":{"type":"string","required":true,"visibility":"user-or-llm","description":"Comma-separated field names to return, e.g. \\"id, contract_title1, company_name\\""},"page":{"type":"string","required":false,"visibility":"user-or-llm","description":"Page number, starting from 0"},"limit":{"type":"string","required":false,"visibility":"user-or-llm","description":"Records per page"}},"hostedApiKey":"none"},"agiloft_read_record":{"id":"agiloft_read_record","name":"Agiloft Read Record","description":"Read a record by ID from an Agiloft table.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table name (e.g., \\"contracts\\", \\"contacts.employees\\")"},"recordId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the record to read"},"fields":{"type":"string","required":false,"visibility":"user-or-llm","description":"Comma-separated list of field names to include in the response"}},"hostedApiKey":"none"},"agiloft_remove_attachment":{"id":"agiloft_remove_attachment","name":"Agiloft Remove Attachment","description":"Remove an attached file from a field in an Agiloft record.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table name (e.g., \\"contracts\\")"},"recordId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the record containing the attachment"},"fieldName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the attachment field"},"position":{"type":"string","required":true,"visibility":"user-or-llm","description":"Position index of the file to remove (starting from 0)"}},"hostedApiKey":"none"},"agiloft_retrieve_attachment":{"id":"agiloft_retrieve_attachment","name":"Agiloft Retrieve Attachment","description":"Download an attached file from an Agiloft record field.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table name (e.g., \\"contracts\\")"},"recordId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the record containing the attachment"},"fieldName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the attachment field"},"position":{"type":"string","required":true,"visibility":"user-or-llm","description":"Position index of the file in the field (starting from 0)"}},"hostedApiKey":"none"},"agiloft_run_action_button":{"id":"agiloft_run_action_button","name":"Agiloft Run Action Button","description":"Run an action button on an Agiloft record, such as an approval or send-for-signature step.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table name (e.g., \\"contracts\\", \\"case\\")"},"recordId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the record to run the action button on"},"actionButtonField":{"type":"string","required":true,"visibility":"user-or-llm","description":"Logical name of the field holding the action button (e.g., \\"ab_field\\")"}},"hostedApiKey":"none"},"agiloft_saved_search":{"id":"agiloft_saved_search","name":"Agiloft Saved Search","description":"List the saved searches defined for an Agiloft table.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":true,"visibility":"user-or-llm","description":"Logical table name to list saved searches for (e.g., \\"contract\\")"}},"hostedApiKey":"none"},"agiloft_search_records":{"id":"agiloft_search_records","name":"Agiloft Search Records","description":"Search for records in an Agiloft table using a query.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table name to search in (e.g., \\"contracts\\", \\"contacts.employees\\")"},"query":{"type":"string","required":false,"visibility":"user-or-llm","description":"Ad hoc EWSearch query. Combine conditions with && (and) or || (or) and quote every value — e.g. \\"summary~=\'test\'&&priority=\'High\'\\". Required unless a saved search is given."},"search":{"type":"string","required":false,"visibility":"user-or-llm","description":"Label of a saved search defined on the table (e.g., \\"C: Status is Closed\\"). Can be combined with a query to narrow it further."},"fields":{"type":"string","required":false,"visibility":"user-or-llm","description":"Comma-separated list of field names to include in the results"},"page":{"type":"string","required":false,"visibility":"user-or-llm","description":"Page number for paginated results (starting from 0)"},"limit":{"type":"string","required":false,"visibility":"user-or-llm","description":"Maximum number of records to return per page. Agiloft treats 0 as \\"all records\\", so leave it unset or use a positive value to keep result sizes bounded."}},"hostedApiKey":"none"},"agiloft_select_records":{"id":"agiloft_select_records","name":"Agiloft Select Records","description":"Select record IDs matching a SQL WHERE clause from an Agiloft table.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table name (e.g., \\"contracts\\", \\"contacts.employees\\")"},"where":{"type":"string","required":true,"visibility":"user-or-llm","description":"SQL WHERE clause using database column names (e.g., \\"summary like \'%new%\'\\" or \\"assigned_person=\'John Doe\'\\"). EWSelect has no page size and returns every matching ID, so append a database limit such as \\"limit 0,200\\" to bound the result."}},"hostedApiKey":"none"},"agiloft_update_record":{"id":"agiloft_update_record","name":"Agiloft Update Record","description":"Update an existing record in an Agiloft table.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table name (e.g., \\"contracts\\", \\"contacts.employees\\")"},"recordId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the record to update"},"data":{"type":"string","required":true,"visibility":"user-or-llm","description":"Updated field values as a JSON object (e.g., {\\"status\\": \\"Active\\", \\"priority\\": \\"High\\"})"}},"hostedApiKey":"none"},"agiloft_upsert_record":{"id":"agiloft_upsert_record","name":"Agiloft Upsert Record","description":"Create an Agiloft record, or update it when a record already matches the given fields.","version":"1.0.0","params":{"instanceUrl":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft instance URL (e.g., https://mycompany.agiloft.com)"},"knowledgeBase":{"type":"string","required":true,"visibility":"user-only","description":"Knowledge base name"},"login":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft username"},"password":{"type":"string","required":true,"visibility":"user-only","description":"Agiloft password"},"table":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table name (e.g., \\"contracts\\", \\"contacts.employees\\")"},"match":{"type":"string","required":true,"visibility":"user-or-llm","description":"Field used to find an existing record (e.g., \\"ext_id\\"). Pick something that identifies a record uniquely — if more than one record matches, Agiloft writes nothing and returns a conflict."},"async":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Queue the write instead of waiting for it. Returns a callback ID instead of a record ID; pass that to Async Status to poll the result."},"data":{"type":"string","required":true,"visibility":"user-or-llm","description":"Field values as a JSON object. On create these populate the new record; on update only the supplied fields change."}},"hostedApiKey":"none"},"ahrefs_anchors":{"id":"ahrefs_anchors","name":"Ahrefs Anchors","description":"Get the anchor text distribution for a target domain or URL\'s backlinks, showing how many links and referring domains use each anchor text.","version":"1.0.0","params":{"target":{"type":"string","required":true,"visibility":"user-or-llm","description":"The target domain or URL to analyze. Example: \\"example.com\\" or \\"https://example.com/page\\""},"mode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Analysis mode: domain (entire domain), prefix (URL prefix), subdomains (include all subdomains, default), exact (exact URL match)"},"history":{"type":"string","required":false,"visibility":"user-or-llm","description":"Historical scope: \\"live\\" (currently live), \\"all_time\\" (default, includes lost backlinks), or \\"since:YYYY-MM-DD\\" (backlinks found since a date)"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of results to return. Example: 50 (default: 1000)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_backlinks":{"id":"ahrefs_backlinks","name":"Ahrefs Backlinks","description":"Get a list of backlinks pointing to a target domain or URL. Returns details about each backlink including source URL, anchor text, and domain rating.","version":"1.0.0","params":{"target":{"type":"string","required":true,"visibility":"user-or-llm","description":"The target domain or URL to analyze. Example: \\"example.com\\" or \\"https://example.com/page\\""},"mode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Analysis mode: domain (entire domain), prefix (URL prefix), subdomains (include all subdomains, default), exact (exact URL match). Example: \\"domain\\""},"history":{"type":"string","required":false,"visibility":"user-or-llm","description":"Historical scope: \\"live\\" (currently live backlinks), \\"all_time\\" (default, includes lost backlinks), or \\"since:YYYY-MM-DD\\" (backlinks found since a date)."},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of results to return. Example: 50 (default: 1000)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_backlinks_stats":{"id":"ahrefs_backlinks_stats","name":"Ahrefs Backlinks Stats","description":"Get backlink and referring domain totals for a target domain or URL, both currently live and across all time.","version":"1.0.0","params":{"target":{"type":"string","required":true,"visibility":"user-or-llm","description":"The target domain or URL to analyze. Example: \\"example.com\\" or \\"https://example.com/page\\""},"mode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Analysis mode: domain (entire domain), prefix (URL prefix), subdomains (include all subdomains, default), exact (exact URL match). Example: \\"domain\\""},"date":{"type":"string","required":false,"visibility":"user-only","description":"Date to report metrics on, in YYYY-MM-DD format (defaults to today)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_batch_analysis":{"id":"ahrefs_batch_analysis","name":"Ahrefs Batch Analysis","description":"Get bulk SEO metrics (Domain Rating, backlinks, referring domains, organic traffic, and more) for multiple domains or URLs in a single request. Useful for comparing many competitors at once.","version":"1.0.0","params":{"targets":{"type":"string","required":true,"visibility":"user-or-llm","description":"Comma-separated list of domains or URLs to analyze. Example: \\"example.com,competitor.com\\""},"mode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Analysis mode applied to every target: domain (entire domain), prefix (URL prefix), subdomains (include all subdomains, default), exact (exact URL match)"},"protocol":{"type":"string","required":false,"visibility":"user-or-llm","description":"Protocol applied to every target: \\"both\\" (default), \\"http\\", or \\"https\\""},"country":{"type":"string","required":false,"visibility":"user-or-llm","description":"Country code for traffic data. Example: \\"us\\", \\"gb\\", \\"de\\" (default: \\"us\\")"},"volumeMode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Search volume calculation: \\"monthly\\" or \\"average\\" (default: \\"monthly\\")"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_broken_backlinks":{"id":"ahrefs_broken_backlinks","name":"Ahrefs Broken Backlinks","description":"Get a list of broken backlinks pointing to a target domain or URL. Useful for identifying link reclamation opportunities.","version":"1.0.0","params":{"target":{"type":"string","required":true,"visibility":"user-or-llm","description":"The target domain or URL to analyze. Example: \\"example.com\\" or \\"https://example.com/page\\""},"mode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Analysis mode: domain (entire domain), prefix (URL prefix), subdomains (include all subdomains, default), exact (exact URL match). Example: \\"domain\\""},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of results to return. Example: 50 (default: 1000)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_domain_rating":{"id":"ahrefs_domain_rating","name":"Ahrefs Domain Rating","description":"Get the Domain Rating (DR) and Ahrefs Rank for a target domain. Domain Rating shows the strength of a website\'s backlink profile on a scale from 0 to 100.","version":"1.0.0","params":{"target":{"type":"string","required":true,"visibility":"user-or-llm","description":"The target domain to analyze (e.g., example.com)"},"date":{"type":"string","required":false,"visibility":"user-only","description":"Date for historical data in YYYY-MM-DD format (defaults to today)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_domain_rating_history":{"id":"ahrefs_domain_rating_history","name":"Ahrefs Domain Rating History","description":"Get the historical Domain Rating (DR) trend for a target domain or URL over a date range, grouped daily, weekly, or monthly.","version":"1.0.0","params":{"target":{"type":"string","required":true,"visibility":"user-or-llm","description":"The target domain or URL to analyze. Example: \\"example.com\\""},"dateFrom":{"type":"string","required":true,"visibility":"user-only","description":"Start date of the historical period, in YYYY-MM-DD format"},"dateTo":{"type":"string","required":false,"visibility":"user-only","description":"End date of the historical period, in YYYY-MM-DD format (defaults to today)"},"historyGrouping":{"type":"string","required":false,"visibility":"user-or-llm","description":"Time interval for grouping data points: \\"daily\\", \\"weekly\\", or \\"monthly\\" (default: \\"monthly\\")"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_keyword_overview":{"id":"ahrefs_keyword_overview","name":"Ahrefs Keyword Overview","description":"Get detailed metrics for a keyword including search volume, keyword difficulty, CPC, clicks, and traffic potential.","version":"1.0.0","params":{"keyword":{"type":"string","required":true,"visibility":"user-or-llm","description":"The keyword to analyze"},"country":{"type":"string","required":false,"visibility":"user-or-llm","description":"Country code for keyword data. Example: \\"us\\", \\"gb\\", \\"de\\" (default: \\"us\\")"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_keywords_history":{"id":"ahrefs_keywords_history","name":"Ahrefs Keywords History","description":"Get the historical organic keyword ranking distribution for a target domain or URL over a date range: how many keywords rank in each position bucket at each point in time.","version":"1.0.0","params":{"target":{"type":"string","required":true,"visibility":"user-or-llm","description":"The target domain or URL to analyze. Example: \\"example.com\\""},"dateFrom":{"type":"string","required":true,"visibility":"user-only","description":"Start date of the historical period, in YYYY-MM-DD format"},"dateTo":{"type":"string","required":false,"visibility":"user-only","description":"End date of the historical period, in YYYY-MM-DD format (defaults to today)"},"historyGrouping":{"type":"string","required":false,"visibility":"user-or-llm","description":"Time interval for grouping data points: \\"daily\\", \\"weekly\\", or \\"monthly\\" (default: \\"monthly\\")"},"country":{"type":"string","required":false,"visibility":"user-or-llm","description":"Country code for search results. Example: \\"us\\", \\"gb\\", \\"de\\" (default: \\"us\\")"},"mode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Analysis mode: domain (entire domain), prefix (URL prefix), subdomains (include all subdomains, default), exact (exact URL match)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_metrics":{"id":"ahrefs_metrics","name":"Ahrefs Metrics","description":"Get a one-call organic and paid search overview for a target domain or URL: organic traffic, organic keywords, paid traffic, paid keywords, and estimated traffic cost.","version":"1.0.0","params":{"target":{"type":"string","required":true,"visibility":"user-or-llm","description":"The target domain or URL to analyze. Example: \\"example.com\\""},"country":{"type":"string","required":false,"visibility":"user-or-llm","description":"Country code for traffic data. Example: \\"us\\", \\"gb\\", \\"de\\""},"mode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Analysis mode: domain (entire domain), prefix (URL prefix), subdomains (include all subdomains, default), exact (exact URL match). Example: \\"domain\\""},"date":{"type":"string","required":false,"visibility":"user-only","description":"Date to report metrics on, in YYYY-MM-DD format (defaults to today)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_metrics_history":{"id":"ahrefs_metrics_history","name":"Ahrefs Metrics History","description":"Get the historical organic and paid traffic trend for a target domain or URL over a date range: organic traffic/cost and paid traffic/cost at each point in time.","version":"1.0.0","params":{"target":{"type":"string","required":true,"visibility":"user-or-llm","description":"The target domain or URL to analyze. Example: \\"example.com\\""},"dateFrom":{"type":"string","required":true,"visibility":"user-only","description":"Start date of the historical period, in YYYY-MM-DD format"},"dateTo":{"type":"string","required":false,"visibility":"user-only","description":"End date of the historical period, in YYYY-MM-DD format (defaults to today)"},"volumeMode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Search volume calculation: \\"monthly\\" or \\"average\\" (default: \\"monthly\\")"},"historyGrouping":{"type":"string","required":false,"visibility":"user-or-llm","description":"Time interval for grouping data points: \\"daily\\", \\"weekly\\", or \\"monthly\\" (default: \\"monthly\\")"},"country":{"type":"string","required":false,"visibility":"user-or-llm","description":"Country code for traffic data. Example: \\"us\\", \\"gb\\", \\"de\\" (default: \\"us\\")"},"mode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Analysis mode: domain (entire domain), prefix (URL prefix), subdomains (include all subdomains, default), exact (exact URL match)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_organic_competitors":{"id":"ahrefs_organic_competitors","name":"Ahrefs Organic Competitors","description":"Get domains that compete with a target domain or URL for the same organic keywords, ranked by keyword overlap.","version":"1.0.0","params":{"target":{"type":"string","required":true,"visibility":"user-or-llm","description":"The target domain or URL to analyze. Example: \\"example.com\\""},"country":{"type":"string","required":false,"visibility":"user-or-llm","description":"Country code for search results. Example: \\"us\\", \\"gb\\", \\"de\\" (default: \\"us\\")"},"mode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Analysis mode: domain (entire domain), prefix (URL prefix), subdomains (include all subdomains, default), exact (exact URL match). Example: \\"domain\\""},"date":{"type":"string","required":false,"visibility":"user-only","description":"Date to report metrics on, in YYYY-MM-DD format (defaults to today)"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of results to return. Example: 50 (default: 1000)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_organic_keywords":{"id":"ahrefs_organic_keywords","name":"Ahrefs Organic Keywords","description":"Get organic keywords that a target domain or URL ranks for in Google search results. Returns keyword details including search volume, ranking position, and estimated traffic.","version":"1.0.0","params":{"target":{"type":"string","required":true,"visibility":"user-or-llm","description":"The target domain or URL to analyze. Example: \\"example.com\\" or \\"https://example.com/page\\""},"country":{"type":"string","required":false,"visibility":"user-or-llm","description":"Country code for search results. Example: \\"us\\", \\"gb\\", \\"de\\" (default: \\"us\\")"},"mode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Analysis mode: domain (entire domain), prefix (URL prefix), subdomains (include all subdomains, default), exact (exact URL match). Example: \\"domain\\""},"date":{"type":"string","required":false,"visibility":"user-only","description":"Date to report metrics on, in YYYY-MM-DD format (defaults to today)"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of results to return. Example: 50 (default: 1000)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_paid_pages":{"id":"ahrefs_paid_pages","name":"Ahrefs Paid Pages","description":"Get a target domain\'s pages that receive paid search traffic, sorted by estimated paid traffic. Returns page URLs with their paid traffic, keyword counts, and estimated spend.","version":"1.0.0","params":{"target":{"type":"string","required":true,"visibility":"user-or-llm","description":"The target domain or URL to analyze. Example: \\"example.com\\""},"country":{"type":"string","required":false,"visibility":"user-or-llm","description":"Country code for traffic data. Example: \\"us\\", \\"gb\\", \\"de\\" (default: \\"us\\")"},"mode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Analysis mode: domain (entire domain), prefix (URL prefix), subdomains (include all subdomains, default), exact (exact URL match)"},"date":{"type":"string","required":false,"visibility":"user-only","description":"Date to report metrics on, in YYYY-MM-DD format (defaults to today)"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of results to return. Example: 50 (default: 1000)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_rank_tracker_competitors_overview":{"id":"ahrefs_rank_tracker_competitors_overview","name":"Ahrefs Rank Tracker Competitors Overview","description":"Get competitor rankings for the keywords tracked in an Ahrefs Rank Tracker project: each tracked keyword\'s volume and difficulty alongside every competitor\'s position, traffic, and traffic value. This endpoint is free and does not consume API units.","version":"1.0.0","params":{"projectId":{"type":"number","required":true,"visibility":"user-or-llm","description":"The Rank Tracker project ID (found in the project URL in Ahrefs)"},"date":{"type":"string","required":true,"visibility":"user-only","description":"Date to report rankings for, in YYYY-MM-DD format"},"device":{"type":"string","required":true,"visibility":"user-or-llm","description":"Rankings device type: \\"desktop\\" or \\"mobile\\""},"dateCompared":{"type":"string","required":false,"visibility":"user-only","description":"Comparison date in YYYY-MM-DD format, to compute position/traffic deltas"},"volumeMode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Search volume calculation: \\"monthly\\" or \\"average\\" (default: \\"monthly\\")"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of results to return. Example: 50 (default: 1000)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_rank_tracker_competitors_stats":{"id":"ahrefs_rank_tracker_competitors_stats","name":"Ahrefs Rank Tracker Competitors Stats","description":"Get aggregate competitor stats for an Ahrefs Rank Tracker project: each competitor\'s traffic, traffic value, average position, and share of voice across all tracked keywords. This endpoint is free and does not consume API units.","version":"1.0.0","params":{"projectId":{"type":"number","required":true,"visibility":"user-or-llm","description":"The Rank Tracker project ID (found in the project URL in Ahrefs)"},"date":{"type":"string","required":true,"visibility":"user-only","description":"Date to report metrics for, in YYYY-MM-DD format"},"device":{"type":"string","required":true,"visibility":"user-or-llm","description":"Rankings device type: \\"desktop\\" or \\"mobile\\""},"volumeMode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Search volume calculation: \\"monthly\\" or \\"average\\" (default: \\"monthly\\")"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_rank_tracker_overview":{"id":"ahrefs_rank_tracker_overview","name":"Ahrefs Rank Tracker Overview","description":"Get ranking overview metrics for the keywords tracked in an Ahrefs Rank Tracker project: position, search volume, keyword difficulty, and estimated traffic. This endpoint is free and does not consume API units.","version":"1.0.0","params":{"projectId":{"type":"number","required":true,"visibility":"user-or-llm","description":"The Rank Tracker project ID (found in the project URL in Ahrefs)"},"date":{"type":"string","required":true,"visibility":"user-only","description":"Date to report rankings for, in YYYY-MM-DD format"},"device":{"type":"string","required":true,"visibility":"user-or-llm","description":"Rankings device type: \\"desktop\\" or \\"mobile\\""},"dateCompared":{"type":"string","required":false,"visibility":"user-only","description":"Comparison date in YYYY-MM-DD format, to compute position/traffic deltas"},"volumeMode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Search volume calculation: \\"monthly\\" or \\"average\\" (default: \\"monthly\\")"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of results to return. Example: 50 (default: 1000)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_rank_tracker_serp_overview":{"id":"ahrefs_rank_tracker_serp_overview","name":"Ahrefs Rank Tracker SERP Overview","description":"Get the full SERP (search engine results page) for a keyword tracked in an Ahrefs Rank Tracker project, including every ranking URL with its position, title, and authority metrics. This endpoint is free and does not consume API units.","version":"1.0.0","params":{"projectId":{"type":"number","required":true,"visibility":"user-or-llm","description":"The Rank Tracker project ID (found in the project URL in Ahrefs)"},"keyword":{"type":"string","required":true,"visibility":"user-or-llm","description":"The tracked keyword to retrieve SERP data for"},"country":{"type":"string","required":true,"visibility":"user-or-llm","description":"Country code for the tracked keyword. Example: \\"us\\", \\"gb\\", \\"de\\""},"device":{"type":"string","required":true,"visibility":"user-or-llm","description":"Rankings device type: \\"desktop\\" or \\"mobile\\""},"topPositions":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of top organic positions to return (defaults to all available)"},"date":{"type":"string","required":false,"visibility":"user-only","description":"Timestamp to return the last available SERP Overview at, in YYYY-MM-DDThh:mm:ss format"},"locationId":{"type":"number","required":false,"visibility":"user-or-llm","description":"Location ID of the tracked keyword, if tracked at a specific location"},"languageCode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Language code of the tracked keyword"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_refdomains_history":{"id":"ahrefs_refdomains_history","name":"Ahrefs Referring Domains History","description":"Get the historical referring domains trend for a target domain or URL over a date range, grouped daily, weekly, or monthly.","version":"1.0.0","params":{"target":{"type":"string","required":true,"visibility":"user-or-llm","description":"The target domain or URL to analyze. Example: \\"example.com\\""},"dateFrom":{"type":"string","required":true,"visibility":"user-only","description":"Start date of the historical period, in YYYY-MM-DD format"},"dateTo":{"type":"string","required":false,"visibility":"user-only","description":"End date of the historical period, in YYYY-MM-DD format (defaults to today)"},"historyGrouping":{"type":"string","required":false,"visibility":"user-or-llm","description":"Time interval for grouping data points: \\"daily\\", \\"weekly\\", or \\"monthly\\" (default: \\"monthly\\")"},"mode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Analysis mode: domain (entire domain), prefix (URL prefix), subdomains (include all subdomains, default), exact (exact URL match)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_referring_domains":{"id":"ahrefs_referring_domains","name":"Ahrefs Referring Domains","description":"Get a list of domains that link to a target domain or URL. Returns unique referring domains with their domain rating, backlink counts, and discovery dates.","version":"1.0.0","params":{"target":{"type":"string","required":true,"visibility":"user-or-llm","description":"The target domain or URL to analyze. Example: \\"example.com\\" or \\"https://example.com/page\\""},"mode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Analysis mode: domain (entire domain), prefix (URL prefix), subdomains (include all subdomains, default), exact (exact URL match). Example: \\"domain\\""},"history":{"type":"string","required":false,"visibility":"user-or-llm","description":"Historical scope: \\"live\\" (currently live), \\"all_time\\" (default, includes lost domains), or \\"since:YYYY-MM-DD\\" (domains found since a date)."},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of results to return. Example: 50 (default: 1000)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_related_terms":{"id":"ahrefs_related_terms","name":"Ahrefs Related Terms","description":"Get keyword ideas related to a seed keyword: terms the same top-ranking pages also rank for (\\"also rank for\\") or also discuss (\\"also talk about\\"), with volume, difficulty, and CPC.","version":"1.0.0","params":{"keyword":{"type":"string","required":true,"visibility":"user-or-llm","description":"The seed keyword to find related terms for"},"country":{"type":"string","required":false,"visibility":"user-or-llm","description":"Country code for keyword data. Example: \\"us\\", \\"gb\\", \\"de\\" (default: \\"us\\")"},"terms":{"type":"string","required":false,"visibility":"user-or-llm","description":"Type of related keywords to return: \\"also_rank_for\\", \\"also_talk_about\\", or \\"all\\" (default: \\"all\\")"},"viewFor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Whether to derive related terms from the top 10 or top 100 ranking pages (default: \\"top_10\\")"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of results to return. Example: 50 (default: 1000)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_site_audit_page_explorer":{"id":"ahrefs_site_audit_page_explorer","name":"Ahrefs Site Audit Page Explorer","description":"Get crawled pages from an Ahrefs Site Audit project with health and SEO metrics: HTTP status, title, link counts, backlinks, indexability, and traffic. Optionally filter to pages affected by a specific issue.","version":"1.0.0","params":{"projectId":{"type":"number","required":true,"visibility":"user-or-llm","description":"The Site Audit project ID (found in the project URL in Ahrefs)"},"date":{"type":"string","required":false,"visibility":"user-only","description":"Crawl date in YYYY-MM-DDThh:mm:ss format (defaults to the most recent crawl)"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of results to return. Example: 50 (default: 1000)"},"offset":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of results to skip, for pagination"},"issueId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Only return pages affected by this issue ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ahrefs_top_pages":{"id":"ahrefs_top_pages","name":"Ahrefs Top Pages","description":"Get the top pages of a target domain sorted by organic traffic. Returns page URLs with their traffic, keyword counts, and estimated traffic value.","version":"1.0.0","params":{"target":{"type":"string","required":true,"visibility":"user-or-llm","description":"The target domain to analyze. Example: \\"example.com\\""},"country":{"type":"string","required":false,"visibility":"user-or-llm","description":"Country code for traffic data. Example: \\"us\\", \\"gb\\", \\"de\\" (default: \\"us\\")"},"mode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Analysis mode: domain (entire domain), prefix (URL prefix), subdomains (include all subdomains, default), exact (exact URL match). Example: \\"domain\\""},"date":{"type":"string","required":false,"visibility":"user-only","description":"Date to report metrics on, in YYYY-MM-DD format (defaults to today)"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of results to return. Example: 50 (default: 1000)"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ahrefs API Key"}},"oauth":{"required":false,"provider":"ahrefs","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"airtable_create_records":{"id":"airtable_create_records","name":"Airtable Create Records","description":"Write new records to an Airtable table","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token"},"baseId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Airtable base ID (starts with \\"app\\", e.g., \\"appXXXXXXXXXXXXXX\\")"},"tableId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table ID (starts with \\"tbl\\") or table name"},"records":{"type":"json","required":true,"visibility":"user-or-llm","description":"Array of records to create, each with a `fields` object"},"typecast":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"When true, Airtable automatically converts string values to the field type"}},"oauth":{"required":true,"provider":"airtable"},"hostedApiKey":"none"},"airtable_delete_records":{"id":"airtable_delete_records","name":"Airtable Delete Records","description":"Delete one or more records from an Airtable table by ID","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token"},"baseId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Airtable base ID (starts with \\"app\\", e.g., \\"appXXXXXXXXXXXXXX\\")"},"tableId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table ID (starts with \\"tbl\\") or table name"},"recordIds":{"type":"json","required":true,"visibility":"user-or-llm","description":"Array of record IDs to delete (each starts with \\"rec\\", e.g., [\\"recXXXXXXXXXXXXXX\\"]). Pass a single-element array to delete one record."}},"oauth":{"required":true,"provider":"airtable"},"hostedApiKey":"none"},"airtable_get_base_schema":{"id":"airtable_get_base_schema","name":"Airtable Get Base Schema","description":"Get the schema of all tables, fields, and views in an Airtable base","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token"},"baseId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Airtable base ID (starts with \\"app\\", e.g., \\"appXXXXXXXXXXXXXX\\")"}},"oauth":{"required":true,"provider":"airtable"},"hostedApiKey":"none"},"airtable_get_record":{"id":"airtable_get_record","name":"Airtable Get Record","description":"Retrieve a single record from an Airtable table by its ID","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token"},"baseId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Airtable base ID (starts with \\"app\\", e.g., \\"appXXXXXXXXXXXXXX\\")"},"tableId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table ID (starts with \\"tbl\\") or table name"},"recordId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Record ID to retrieve (starts with \\"rec\\", e.g., \\"recXXXXXXXXXXXXXX\\")"}},"oauth":{"required":true,"provider":"airtable"},"hostedApiKey":"none"},"airtable_list_bases":{"id":"airtable_list_bases","name":"Airtable List Bases","description":"List all bases the authenticated user has access to","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token"},"offset":{"type":"string","required":false,"visibility":"user-or-llm","description":"Pagination offset for retrieving additional bases"}},"oauth":{"required":true,"provider":"airtable"},"hostedApiKey":"none"},"airtable_list_records":{"id":"airtable_list_records","name":"Airtable List Records","description":"Read records from an Airtable table","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token"},"baseId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Airtable base ID (starts with \\"app\\", e.g., \\"appXXXXXXXXXXXXXX\\")"},"tableId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table ID (starts with \\"tbl\\") or table name"},"maxRecords":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of records to return (default: all records)"},"filterFormula":{"type":"string","required":false,"visibility":"user-or-llm","description":"Formula to filter records (e.g., \\"({Field Name} = \'Value\')\\")"}},"oauth":{"required":true,"provider":"airtable"},"hostedApiKey":"none"},"airtable_list_tables":{"id":"airtable_list_tables","name":"Airtable List Tables","description":"List all tables and their schema in an Airtable base","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token"},"baseId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Airtable base ID (starts with \\"app\\", e.g., \\"appXXXXXXXXXXXXXX\\")"}},"oauth":{"required":true,"provider":"airtable"},"hostedApiKey":"none"},"airtable_update_multiple_records":{"id":"airtable_update_multiple_records","name":"Airtable Update Multiple Records","description":"Update multiple existing records in an Airtable table","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token"},"baseId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Airtable base ID (starts with \\"app\\", e.g., \\"appXXXXXXXXXXXXXX\\")"},"tableId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table ID (starts with \\"tbl\\") or table name"},"records":{"type":"json","required":true,"visibility":"user-or-llm","description":"Array of records to update, each with an `id` and a `fields` object"},"typecast":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"When true, Airtable automatically converts string values to the field type"}},"oauth":{"required":true,"provider":"airtable"},"hostedApiKey":"none"},"airtable_update_record":{"id":"airtable_update_record","name":"Airtable Update Record","description":"Update an existing record in an Airtable table by ID","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token"},"baseId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Airtable base ID (starts with \\"app\\", e.g., \\"appXXXXXXXXXXXXXX\\")"},"tableId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table ID (starts with \\"tbl\\") or table name"},"recordId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Record ID to update (starts with \\"rec\\", e.g., \\"recXXXXXXXXXXXXXX\\")"},"fields":{"type":"json","required":true,"visibility":"user-or-llm","description":"An object containing the field names and their new values"},"typecast":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"When true, Airtable automatically converts string values to the field type"}},"oauth":{"required":true,"provider":"airtable"},"hostedApiKey":"none"},"airtable_upsert_records":{"id":"airtable_upsert_records","name":"Airtable Upsert Records","description":"Update existing records or create new ones in an Airtable table, matching on the specified merge fields","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token"},"baseId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Airtable base ID (starts with \\"app\\", e.g., \\"appXXXXXXXXXXXXXX\\")"},"tableId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Table ID (starts with \\"tbl\\") or table name"},"records":{"type":"json","required":true,"visibility":"user-or-llm","description":"Array of records to upsert, each with a `fields` object"},"fieldsToMergeOn":{"type":"json","required":true,"visibility":"user-or-llm","description":"Array of field names used to match existing records (max 3). A record is updated when all merge fields match, otherwise it is created. Example: [\\"Name\\"]"},"typecast":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"When true, Airtable automatically converts string values to the field type"}},"oauth":{"required":true,"provider":"airtable"},"hostedApiKey":"none"},"algolia_add_record":{"id":"algolia_add_record","name":"Algolia Add Record","description":"Add or replace a record in an Algolia index","version":"1.0","params":{"applicationId":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Application ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Admin API Key"},"indexName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the Algolia index"},"objectID":{"type":"string","required":false,"visibility":"user-or-llm","description":"Object ID for the record (auto-generated if not provided)"},"record":{"type":"json","required":true,"visibility":"user-or-llm","description":"JSON object representing the record to add"}},"oauth":{"required":false,"provider":"algolia","credentialKind":"service-account","credentialParams":{"applicationId":"providerWorkspaceId","apiKey":"accessToken"},"credentialSuppliedParams":["applicationId","apiKey"]},"hostedApiKey":"none"},"algolia_batch_operations":{"id":"algolia_batch_operations","name":"Algolia Batch Operations","description":"Perform batch add, update, partial update, or delete operations on records in an Algolia index","version":"1.0","params":{"applicationId":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Application ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Admin API Key"},"indexName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the Algolia index"},"requests":{"type":"json","required":true,"visibility":"user-or-llm","description":"Array of batch operations. Each item has \\"action\\" (addObject, updateObject, partialUpdateObject, partialUpdateObjectNoCreate, deleteObject, delete, clear) and \\"body\\" (the record data; must include objectID for update/delete; use an empty object {} for the index-level delete/clear actions)"}},"oauth":{"required":false,"provider":"algolia","credentialKind":"service-account","credentialParams":{"applicationId":"providerWorkspaceId","apiKey":"accessToken"},"credentialSuppliedParams":["applicationId","apiKey"]},"hostedApiKey":"none"},"algolia_browse_records":{"id":"algolia_browse_records","name":"Algolia Browse Records","description":"Browse and iterate over all records in an Algolia index using cursor pagination","version":"1.0","params":{"applicationId":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Application ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Algolia API Key (must have browse ACL)"},"indexName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the Algolia index to browse"},"query":{"type":"string","required":false,"visibility":"user-or-llm","description":"Search query to filter browsed records"},"filters":{"type":"string","required":false,"visibility":"user-or-llm","description":"Filter string to narrow down results"},"attributesToRetrieve":{"type":"string","required":false,"visibility":"user-or-llm","description":"Comma-separated list of attributes to retrieve"},"hitsPerPage":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of hits per page (default: 1000, max: 1000)"},"cursor":{"type":"string","required":false,"visibility":"user-or-llm","description":"Cursor from a previous browse response for pagination"},"aroundLatLng":{"type":"string","required":false,"visibility":"user-or-llm","description":"Coordinates for geo-search (e.g., \\"40.71,-74.01\\")"},"aroundRadius":{"type":"string","required":false,"visibility":"user-or-llm","description":"Maximum radius in meters for geo-search, or \\"all\\" for unlimited"},"insideBoundingBox":{"type":"json","required":false,"visibility":"user-or-llm","description":"Bounding box coordinates as [[lat1, lng1, lat2, lng2]] for geo-search"},"insidePolygon":{"type":"json","required":false,"visibility":"user-or-llm","description":"Polygon coordinates as [[lat1, lng1, lat2, lng2, lat3, lng3, ...]] for geo-search"}},"oauth":{"required":false,"provider":"algolia","credentialKind":"service-account","credentialParams":{"applicationId":"providerWorkspaceId","apiKey":"accessToken"},"credentialSuppliedParams":["applicationId","apiKey"]},"hostedApiKey":"none"},"algolia_clear_records":{"id":"algolia_clear_records","name":"Algolia Clear Records","description":"Clear all records from an Algolia index while keeping settings, synonyms, and rules","version":"1.0","params":{"applicationId":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Application ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Admin API Key (must have deleteIndex ACL)"},"indexName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the Algolia index to clear"}},"oauth":{"required":false,"provider":"algolia","credentialKind":"service-account","credentialParams":{"applicationId":"providerWorkspaceId","apiKey":"accessToken"},"credentialSuppliedParams":["applicationId","apiKey"]},"hostedApiKey":"none"},"algolia_copy_move_index":{"id":"algolia_copy_move_index","name":"Algolia Copy/Move Index","description":"Copy or move an Algolia index to a new destination","version":"1.0","params":{"applicationId":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Application ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Admin API Key"},"indexName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the source index"},"operation":{"type":"string","required":true,"visibility":"user-or-llm","description":"Operation to perform: \\"copy\\" or \\"move\\""},"destination":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the destination index"},"scope":{"type":"json","required":false,"visibility":"user-or-llm","description":"Array of scopes to copy (only for \\"copy\\" operation): [\\"settings\\", \\"synonyms\\", \\"rules\\"]. Omit to copy everything including records."}},"oauth":{"required":false,"provider":"algolia","credentialKind":"service-account","credentialParams":{"applicationId":"providerWorkspaceId","apiKey":"accessToken"},"credentialSuppliedParams":["applicationId","apiKey"]},"hostedApiKey":"none"},"algolia_delete_by_filter":{"id":"algolia_delete_by_filter","name":"Algolia Delete By Filter","description":"Delete all records matching a filter from an Algolia index","version":"1.0","params":{"applicationId":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Application ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Admin API Key (must have deleteIndex ACL)"},"indexName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the Algolia index"},"filters":{"type":"string","required":false,"visibility":"user-or-llm","description":"Filter expression to match records for deletion (e.g., \\"category:outdated\\")"},"facetFilters":{"type":"json","required":false,"visibility":"user-or-llm","description":"Array of facet filters (e.g., [\\"brand:Acme\\"])"},"numericFilters":{"type":"json","required":false,"visibility":"user-or-llm","description":"Array of numeric filters (e.g., [\\"price > 100\\"])"},"tagFilters":{"type":"json","required":false,"visibility":"user-or-llm","description":"Array of tag filters using the _tags attribute (e.g., [\\"published\\"])"},"aroundLatLng":{"type":"string","required":false,"visibility":"user-or-llm","description":"Coordinates for geo-search filter (e.g., \\"40.71,-74.01\\")"},"aroundRadius":{"type":"string","required":false,"visibility":"user-or-llm","description":"Maximum radius in meters for geo-search, or \\"all\\" for unlimited"},"insideBoundingBox":{"type":"json","required":false,"visibility":"user-or-llm","description":"Bounding box coordinates as [[lat1, lng1, lat2, lng2]] for geo-search filter"},"insidePolygon":{"type":"json","required":false,"visibility":"user-or-llm","description":"Polygon coordinates as [[lat1, lng1, lat2, lng2, lat3, lng3, ...]] for geo-search filter"}},"oauth":{"required":false,"provider":"algolia","credentialKind":"service-account","credentialParams":{"applicationId":"providerWorkspaceId","apiKey":"accessToken"},"credentialSuppliedParams":["applicationId","apiKey"]},"hostedApiKey":"none"},"algolia_delete_index":{"id":"algolia_delete_index","name":"Algolia Delete Index","description":"Delete an entire Algolia index and all its records","version":"1.0","params":{"applicationId":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Application ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Admin API Key (must have deleteIndex ACL)"},"indexName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the Algolia index to delete"}},"oauth":{"required":false,"provider":"algolia","credentialKind":"service-account","credentialParams":{"applicationId":"providerWorkspaceId","apiKey":"accessToken"},"credentialSuppliedParams":["applicationId","apiKey"]},"hostedApiKey":"none"},"algolia_delete_record":{"id":"algolia_delete_record","name":"Algolia Delete Record","description":"Delete a record by objectID from an Algolia index","version":"1.0","params":{"applicationId":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Application ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Admin API Key"},"indexName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the Algolia index"},"objectID":{"type":"string","required":true,"visibility":"user-or-llm","description":"The objectID of the record to delete"}},"oauth":{"required":false,"provider":"algolia","credentialKind":"service-account","credentialParams":{"applicationId":"providerWorkspaceId","apiKey":"accessToken"},"credentialSuppliedParams":["applicationId","apiKey"]},"hostedApiKey":"none"},"algolia_get_record":{"id":"algolia_get_record","name":"Algolia Get Record","description":"Get a record by objectID from an Algolia index","version":"1.0","params":{"applicationId":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Application ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Algolia API Key"},"indexName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the Algolia index"},"objectID":{"type":"string","required":true,"visibility":"user-or-llm","description":"The objectID of the record to retrieve"},"attributesToRetrieve":{"type":"string","required":false,"visibility":"user-or-llm","description":"Comma-separated list of attributes to retrieve"}},"oauth":{"required":false,"provider":"algolia","credentialKind":"service-account","credentialParams":{"applicationId":"providerWorkspaceId","apiKey":"accessToken"},"credentialSuppliedParams":["applicationId","apiKey"]},"hostedApiKey":"none"},"algolia_get_records":{"id":"algolia_get_records","name":"Algolia Get Records","description":"Retrieve multiple records by objectID from one or more Algolia indices","version":"1.0","params":{"applicationId":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Application ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Algolia API Key"},"indexName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Default index name for all requests"},"requests":{"type":"json","required":true,"visibility":"user-or-llm","description":"Array of objects specifying records to retrieve. Each must have \\"objectID\\" and optionally \\"indexName\\" and \\"attributesToRetrieve\\"."}},"oauth":{"required":false,"provider":"algolia","credentialKind":"service-account","credentialParams":{"applicationId":"providerWorkspaceId","apiKey":"accessToken"},"credentialSuppliedParams":["applicationId","apiKey"]},"hostedApiKey":"none"},"algolia_get_settings":{"id":"algolia_get_settings","name":"Algolia Get Settings","description":"Retrieve the settings of an Algolia index","version":"1.0","params":{"applicationId":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Application ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Algolia API Key"},"indexName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the Algolia index"}},"oauth":{"required":false,"provider":"algolia","credentialKind":"service-account","credentialParams":{"applicationId":"providerWorkspaceId","apiKey":"accessToken"},"credentialSuppliedParams":["applicationId","apiKey"]},"hostedApiKey":"none"},"algolia_get_task_status":{"id":"algolia_get_task_status","name":"Algolia Get Task Status","description":"Check whether an Algolia indexing task has finished publishing","version":"1.0","params":{"applicationId":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Application ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Algolia API Key"},"indexName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the Algolia index the task ran against"},"taskID":{"type":"number","required":true,"visibility":"user-or-llm","description":"The taskID returned by a previous write operation"}},"oauth":{"required":false,"provider":"algolia","credentialKind":"service-account","credentialParams":{"applicationId":"providerWorkspaceId","apiKey":"accessToken"},"credentialSuppliedParams":["applicationId","apiKey"]},"hostedApiKey":"none"},"algolia_list_indices":{"id":"algolia_list_indices","name":"Algolia List Indices","description":"List all indices in an Algolia application","version":"1.0","params":{"applicationId":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Application ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Algolia API Key"},"page":{"type":"number","required":false,"visibility":"user-or-llm","description":"Page number for paginating indices (default: not paginated)"},"hitsPerPage":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of indices per page (default: 100)"}},"oauth":{"required":false,"provider":"algolia","credentialKind":"service-account","credentialParams":{"applicationId":"providerWorkspaceId","apiKey":"accessToken"},"credentialSuppliedParams":["applicationId","apiKey"]},"hostedApiKey":"none"},"algolia_partial_update_record":{"id":"algolia_partial_update_record","name":"Algolia Partial Update Record","description":"Partially update a record in an Algolia index without replacing it entirely","version":"1.0","params":{"applicationId":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Application ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Admin API Key"},"indexName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the Algolia index"},"objectID":{"type":"string","required":true,"visibility":"user-or-llm","description":"The objectID of the record to update"},"attributes":{"type":"json","required":true,"visibility":"user-or-llm","description":"JSON object with attributes to update. Supports built-in operations like {\\"stock\\": {\\"_operation\\": \\"Decrement\\", \\"value\\": 1}}"},"createIfNotExists":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Whether to create the record if it does not exist (default: true)"}},"oauth":{"required":false,"provider":"algolia","credentialKind":"service-account","credentialParams":{"applicationId":"providerWorkspaceId","apiKey":"accessToken"},"credentialSuppliedParams":["applicationId","apiKey"]},"hostedApiKey":"none"},"algolia_search":{"id":"algolia_search","name":"Algolia Search","description":"Search an Algolia index","version":"1.0","params":{"applicationId":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Application ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Algolia API Key"},"indexName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the Algolia index to search"},"query":{"type":"string","required":true,"visibility":"user-or-llm","description":"Search query text"},"hitsPerPage":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of hits per page (default: 20)"},"page":{"type":"number","required":false,"visibility":"user-or-llm","description":"Page number to retrieve (default: 0)"},"filters":{"type":"string","required":false,"visibility":"user-or-llm","description":"Filter string (e.g., \\"category:electronics AND price < 100\\")"},"attributesToRetrieve":{"type":"string","required":false,"visibility":"user-or-llm","description":"Comma-separated list of attributes to retrieve"},"facets":{"type":"string","required":false,"visibility":"user-or-llm","description":"Comma-separated list of facet attribute names to retrieve counts for (use \\"*\\" for all)"},"getRankingInfo":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Whether to include detailed ranking information in each hit"},"aroundLatLng":{"type":"string","required":false,"visibility":"user-or-llm","description":"Coordinates for geo-search (e.g., \\"40.71,-74.01\\")"},"aroundRadius":{"type":"string","required":false,"visibility":"user-or-llm","description":"Maximum radius in meters for geo-search, or \\"all\\" for unlimited"},"insideBoundingBox":{"type":"json","required":false,"visibility":"user-or-llm","description":"Bounding box coordinates as [[lat1, lng1, lat2, lng2]] for geo-search"},"insidePolygon":{"type":"json","required":false,"visibility":"user-or-llm","description":"Polygon coordinates as [[lat1, lng1, lat2, lng2, lat3, lng3, ...]] for geo-search"}},"oauth":{"required":false,"provider":"algolia","credentialKind":"service-account","credentialParams":{"applicationId":"providerWorkspaceId","apiKey":"accessToken"},"credentialSuppliedParams":["applicationId","apiKey"]},"hostedApiKey":"none"},"algolia_update_settings":{"id":"algolia_update_settings","name":"Algolia Update Settings","description":"Update the settings of an Algolia index","version":"1.0","params":{"applicationId":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Application ID"},"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Algolia Admin API Key (must have editSettings ACL)"},"indexName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the Algolia index"},"settings":{"type":"json","required":true,"visibility":"user-or-llm","description":"JSON object with settings to update (e.g., {\\"searchableAttributes\\": [\\"name\\", \\"description\\"], \\"customRanking\\": [\\"desc(popularity)\\"]})"},"forwardToReplicas":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Whether to apply changes to replica indices (default: false)"}},"oauth":{"required":false,"provider":"algolia","credentialKind":"service-account","credentialParams":{"applicationId":"providerWorkspaceId","apiKey":"accessToken"},"credentialSuppliedParams":["applicationId","apiKey"]},"hostedApiKey":"none"},"amplitude_event_segmentation":{"id":"amplitude_event_segmentation","name":"Amplitude Event Segmentation","description":"Query event analytics data with segmentation. Get event counts, uniques, averages, and more.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude API Key"},"secretKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude Secret Key"},"eventType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Event type name to analyze"},"start":{"type":"string","required":true,"visibility":"user-or-llm","description":"Start date in YYYYMMDD format"},"end":{"type":"string","required":true,"visibility":"user-or-llm","description":"End date in YYYYMMDD format"},"metric":{"type":"string","required":false,"visibility":"user-or-llm","description":"Metric type: uniques, totals, pct_dau, average, histogram, sums, value_avg, or formula (default: uniques)"},"interval":{"type":"string","required":false,"visibility":"user-or-llm","description":"Time interval: 1 (daily), 7 (weekly), or 30 (monthly)"},"groupBy":{"type":"string","required":false,"visibility":"user-or-llm","description":"Property name to group by (prefix custom user properties with \\"gp:\\")"},"groupBy2":{"type":"string","required":false,"visibility":"user-or-llm","description":"Second property name to group by (prefix custom user properties with \\"gp:\\")"},"limit":{"type":"string","required":false,"visibility":"user-or-llm","description":"Maximum number of group-by values (max 1000)"},"filters":{"type":"string","required":false,"visibility":"user-or-llm","description":"JSON array of filter objects applied to the event, e.g. [{\\"subprop_type\\":\\"event\\",\\"subprop_key\\":\\"city\\",\\"subprop_op\\":\\"is\\",\\"subprop_value\\":[\\"San Francisco\\"]}]"},"formula":{"type":"string","required":false,"visibility":"user-or-llm","description":"Required when metric is \\"formula\\", e.g. \\"UNIQUES(A)/UNIQUES(B)\\""},"segment":{"type":"string","required":false,"visibility":"user-or-llm","description":"JSON segment definition(s) applied to the query"},"dataResidency":{"type":"string","required":false,"visibility":"user-or-llm","description":"Data residency region: \\"us\\" (default) or \\"eu\\""}},"hostedApiKey":"none"},"amplitude_funnels":{"id":"amplitude_funnels","name":"Amplitude Funnels","description":"Analyze conversion rates and drop-off between a sequence of events.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude API Key"},"secretKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude Secret Key"},"events":{"type":"string","required":true,"visibility":"user-or-llm","description":"JSON array of event objects, one per funnel step in order, e.g. [{\\"event_type\\":\\"signup\\"},{\\"event_type\\":\\"purchase\\"}]"},"start":{"type":"string","required":true,"visibility":"user-or-llm","description":"Start date in YYYYMMDD format"},"end":{"type":"string","required":true,"visibility":"user-or-llm","description":"End date in YYYYMMDD format"},"mode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Funnel ordering: \\"ordered\\", \\"unordered\\", or \\"sequential\\" (default: ordered)"},"userType":{"type":"string","required":false,"visibility":"user-or-llm","description":"User type: \\"new\\" or \\"active\\" (default: active)"},"interval":{"type":"string","required":false,"visibility":"user-or-llm","description":"Time interval: -300000 (real-time), -3600000 (hourly), 1 (daily), 7 (weekly), or 30 (monthly)"},"conversionWindowSeconds":{"type":"string","required":false,"visibility":"user-or-llm","description":"Conversion window in seconds (default: 2592000, i.e. 30 days)"},"groupBy":{"type":"string","required":false,"visibility":"user-or-llm","description":"Property to group by (limit: one; prefix custom properties with \\"gp:\\")"},"limit":{"type":"string","required":false,"visibility":"user-or-llm","description":"Maximum number of group-by values (default: 100, max: 1000)"},"segment":{"type":"string","required":false,"visibility":"user-or-llm","description":"JSON segment definition(s) applied to the query"},"dataResidency":{"type":"string","required":false,"visibility":"user-or-llm","description":"Data residency region: \\"us\\" (default) or \\"eu\\""}},"hostedApiKey":"none"},"amplitude_get_active_users":{"id":"amplitude_get_active_users","name":"Amplitude Get Active Users","description":"Get active or new user counts over a date range from the Dashboard REST API.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude API Key"},"secretKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude Secret Key"},"start":{"type":"string","required":true,"visibility":"user-or-llm","description":"Start date in YYYYMMDD format"},"end":{"type":"string","required":true,"visibility":"user-or-llm","description":"End date in YYYYMMDD format"},"metric":{"type":"string","required":false,"visibility":"user-or-llm","description":"Metric type: \\"active\\" or \\"new\\" (default: active)"},"interval":{"type":"string","required":false,"visibility":"user-or-llm","description":"Time interval: 1 (daily), 7 (weekly), or 30 (monthly)"},"groupBy":{"type":"string","required":false,"visibility":"user-or-llm","description":"Property name to group by"},"segment":{"type":"string","required":false,"visibility":"user-or-llm","description":"JSON segment definition(s) applied to the query"},"dataResidency":{"type":"string","required":false,"visibility":"user-or-llm","description":"Data residency region: \\"us\\" (default) or \\"eu\\""}},"hostedApiKey":"none"},"amplitude_get_revenue":{"id":"amplitude_get_revenue","name":"Amplitude Get Revenue","description":"Get revenue LTV data including ARPU, ARPPU, total revenue, and paying user counts.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude API Key"},"secretKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude Secret Key"},"start":{"type":"string","required":true,"visibility":"user-or-llm","description":"Start date in YYYYMMDD format"},"end":{"type":"string","required":true,"visibility":"user-or-llm","description":"End date in YYYYMMDD format"},"metric":{"type":"string","required":false,"visibility":"user-or-llm","description":"Metric: 0 (ARPU), 1 (ARPPU), 2 (Total Revenue), 3 (Paying Users)"},"interval":{"type":"string","required":false,"visibility":"user-or-llm","description":"Time interval: 1 (daily), 7 (weekly), or 30 (monthly)"},"groupBy":{"type":"string","required":false,"visibility":"user-or-llm","description":"Property name to group by (limit: one)"},"segment":{"type":"string","required":false,"visibility":"user-or-llm","description":"JSON segment definition(s) applied to the query"},"dataResidency":{"type":"string","required":false,"visibility":"user-or-llm","description":"Data residency region: \\"us\\" (default) or \\"eu\\""}},"hostedApiKey":"none"},"amplitude_group_identify":{"id":"amplitude_group_identify","name":"Amplitude Group Identify","description":"Set group-level properties in Amplitude. Supports $set, $setOnce, $add, $append, $unset operations.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude API Key"},"groupType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Group classification (e.g., \\"company\\", \\"org_id\\")"},"groupValue":{"type":"string","required":true,"visibility":"user-or-llm","description":"Specific group identifier (e.g., \\"Acme Corp\\")"},"groupProperties":{"type":"string","required":true,"visibility":"user-or-llm","description":"JSON object of group properties. Use operations like $set, $setOnce, $add, $append, $unset."},"dataResidency":{"type":"string","required":false,"visibility":"user-or-llm","description":"Data residency region: \\"us\\" (default) or \\"eu\\""}},"hostedApiKey":"none"},"amplitude_identify_user":{"id":"amplitude_identify_user","name":"Amplitude Identify User","description":"Set user properties in Amplitude using the Identify API. Supports $set, $setOnce, $add, $append, $unset operations.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude API Key"},"userId":{"type":"string","required":false,"visibility":"user-or-llm","description":"User ID (required if no device_id)"},"deviceId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Device ID (required if no user_id)"},"userProperties":{"type":"string","required":true,"visibility":"user-or-llm","description":"JSON object of user properties. Use operations like $set, $setOnce, $add, $append, $unset."},"dataResidency":{"type":"string","required":false,"visibility":"user-or-llm","description":"Data residency region: \\"us\\" (default) or \\"eu\\""}},"hostedApiKey":"none"},"amplitude_list_events":{"id":"amplitude_list_events","name":"Amplitude List Events","description":"List all event types in the Amplitude project with their weekly totals and unique counts.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude API Key"},"secretKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude Secret Key"},"dataResidency":{"type":"string","required":false,"visibility":"user-or-llm","description":"Data residency region: \\"us\\" (default) or \\"eu\\""}},"hostedApiKey":"none"},"amplitude_realtime_active_users":{"id":"amplitude_realtime_active_users","name":"Amplitude Real-time Active Users","description":"Get real-time active user counts at 5-minute granularity for the last 2 days.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude API Key"},"secretKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude Secret Key"},"dataResidency":{"type":"string","required":false,"visibility":"user-or-llm","description":"Data residency region: \\"us\\" (default) or \\"eu\\""}},"hostedApiKey":"none"},"amplitude_retention":{"id":"amplitude_retention","name":"Amplitude Retention","description":"Measure how many users return to perform an action after a starting action.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude API Key"},"secretKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude Secret Key"},"startEvent":{"type":"string","required":true,"visibility":"user-or-llm","description":"JSON starting event object, e.g. {\\"event_type\\":\\"_new\\"} or {\\"event_type\\":\\"_active\\"}"},"returnEvent":{"type":"string","required":true,"visibility":"user-or-llm","description":"JSON returning event object, e.g. {\\"event_type\\":\\"_all\\"} or {\\"event_type\\":\\"_active\\"}"},"start":{"type":"string","required":true,"visibility":"user-or-llm","description":"Start date in YYYYMMDD format"},"end":{"type":"string","required":true,"visibility":"user-or-llm","description":"End date in YYYYMMDD format"},"retentionMode":{"type":"string","required":false,"visibility":"user-or-llm","description":"Retention type: \\"bracket\\", \\"rolling\\", or \\"n-day\\" (default: n-day)"},"retentionBrackets":{"type":"string","required":false,"visibility":"user-or-llm","description":"Required when Retention Mode is \\"bracket\\". Day ranges, e.g. [[0,4]]"},"interval":{"type":"string","required":false,"visibility":"user-or-llm","description":"Time interval: 1 (daily), 7 (weekly), or 30 (monthly)"},"groupBy":{"type":"string","required":false,"visibility":"user-or-llm","description":"Property to group by (limit: one; prefix custom properties with \\"gp:\\")"},"segment":{"type":"string","required":false,"visibility":"user-or-llm","description":"JSON segment definition(s) applied to the query"},"dataResidency":{"type":"string","required":false,"visibility":"user-or-llm","description":"Data residency region: \\"us\\" (default) or \\"eu\\""}},"hostedApiKey":"none"},"amplitude_send_event":{"id":"amplitude_send_event","name":"Amplitude Send Event","description":"Track an event in Amplitude using the HTTP V2 API.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude API Key"},"userId":{"type":"string","required":false,"visibility":"user-or-llm","description":"User ID (required if no device_id)"},"deviceId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Device ID (required if no user_id)"},"eventType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the event (e.g., \\"page_view\\", \\"purchase\\")"},"eventProperties":{"type":"string","required":false,"visibility":"user-or-llm","description":"JSON object of custom event properties"},"userProperties":{"type":"string","required":false,"visibility":"user-or-llm","description":"JSON object of user properties to set (supports $set, $setOnce, $add, $append, $unset)"},"time":{"type":"string","required":false,"visibility":"user-or-llm","description":"Event timestamp in milliseconds since epoch"},"sessionId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Session start time in milliseconds since epoch"},"insertId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Unique ID for deduplication (within 7-day window)"},"appVersion":{"type":"string","required":false,"visibility":"user-or-llm","description":"Application version string"},"platform":{"type":"string","required":false,"visibility":"user-or-llm","description":"Platform (e.g., \\"Web\\", \\"iOS\\", \\"Android\\")"},"country":{"type":"string","required":false,"visibility":"user-or-llm","description":"Two-letter country code"},"language":{"type":"string","required":false,"visibility":"user-or-llm","description":"Language code (e.g., \\"en\\")"},"ip":{"type":"string","required":false,"visibility":"user-or-llm","description":"IP address for geo-location"},"price":{"type":"string","required":false,"visibility":"user-or-llm","description":"Price of the item purchased"},"quantity":{"type":"string","required":false,"visibility":"user-or-llm","description":"Quantity of items purchased"},"revenue":{"type":"string","required":false,"visibility":"user-or-llm","description":"Revenue amount"},"productId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Product identifier"},"revenueType":{"type":"string","required":false,"visibility":"user-or-llm","description":"Revenue type (e.g., \\"purchase\\", \\"refund\\")"},"dataResidency":{"type":"string","required":false,"visibility":"user-or-llm","description":"Data residency region: \\"us\\" (default) or \\"eu\\""}},"hostedApiKey":"none"},"amplitude_user_activity":{"id":"amplitude_user_activity","name":"Amplitude User Activity","description":"Get the event stream for a specific user by their Amplitude ID.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude API Key"},"secretKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude Secret Key"},"amplitudeId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Amplitude internal user ID"},"offset":{"type":"string","required":false,"visibility":"user-or-llm","description":"Offset for pagination (default 0)"},"limit":{"type":"string","required":false,"visibility":"user-or-llm","description":"Maximum number of events to return (default 1000, max 1000)"},"direction":{"type":"string","required":false,"visibility":"user-or-llm","description":"Sort direction: \\"latest\\" or \\"earliest\\" (default: latest)"},"dataResidency":{"type":"string","required":false,"visibility":"user-or-llm","description":"Data residency region: \\"us\\" (default) or \\"eu\\""}},"hostedApiKey":"none"},"amplitude_user_profile":{"id":"amplitude_user_profile","name":"Amplitude User Profile","description":"Get a user profile including properties, cohort memberships, and computed properties. Not available for EU data-residency projects.","version":"1.0.0","params":{"secretKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude Secret Key"},"userId":{"type":"string","required":false,"visibility":"user-or-llm","description":"External user ID (required if no device_id)"},"deviceId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Device ID (required if no user_id)"},"getAmpProps":{"type":"string","required":false,"visibility":"user-or-llm","description":"Include Amplitude user properties (true/false, default: false)"},"getCohortIds":{"type":"string","required":false,"visibility":"user-or-llm","description":"Include cohort IDs the user belongs to (true/false, default: false)"},"getComputations":{"type":"string","required":false,"visibility":"user-or-llm","description":"Include computed user properties (true/false, default: false)"}},"hostedApiKey":"none"},"amplitude_user_search":{"id":"amplitude_user_search","name":"Amplitude User Search","description":"Search for a user by User ID, Device ID, or Amplitude ID using the Dashboard REST API.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude API Key"},"secretKey":{"type":"string","required":true,"visibility":"user-only","description":"Amplitude Secret Key"},"user":{"type":"string","required":true,"visibility":"user-or-llm","description":"User ID, Device ID, or Amplitude ID to search for"},"dataResidency":{"type":"string","required":false,"visibility":"user-or-llm","description":"Data residency region: \\"us\\" (default) or \\"eu\\""}},"hostedApiKey":"none"},"apify_get_dataset_items":{"id":"apify_get_dataset_items","name":"APIFY Get Dataset Items","description":"Retrieve items stored in an APIFY dataset","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"APIFY API token from console.apify.com/account#/integrations"},"datasetId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Dataset ID to read items from. Example: \\"9RnD3Pql2vGZkc5H5\\""},"itemLimit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Max items to return (1-250000). Default: all items. Example: 500"},"offset":{"type":"number","required":false,"visibility":"user-or-llm","description":"Number of items to skip at the start. Default: 0"},"fields":{"type":"string","required":false,"visibility":"user-or-llm","description":"Comma-separated list of fields to include. Example: \\"title,url,price\\""}},"oauth":{"required":false,"provider":"apify","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apify_get_run":{"id":"apify_get_run","name":"APIFY Get Run","description":"Get the status and details of an APIFY actor run","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"APIFY API token from console.apify.com/account#/integrations"},"runId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Actor run ID to fetch. Example: \\"HG7ML7M8z78YcAPEB\\""}},"oauth":{"required":false,"provider":"apify","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apify_run_actor_async":{"id":"apify_run_actor_async","name":"APIFY Run Actor (Async)","description":"Start an APIFY Actor run and poll it within the same workflow step until completion or the polling deadline","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"APIFY API token from console.apify.com/account#/integrations"},"actorId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Actor ID or username/actor-name. Examples: \\"apify/web-scraper\\", \\"janedoe/my-actor\\", \\"moJRLRc85AitArpNN\\""},"input":{"type":"string","required":false,"visibility":"user-or-llm","description":"Actor input as JSON string. Example: { \\"startUrls\\": [ { \\"url\\": \\"https://example.com\\" } ], \\"maxPages\\": 10 }"},"waitForFinish":{"type":"number","required":false,"visibility":"user-or-llm","description":"Initial wait time in seconds (0-60) before polling starts. Example: 30"},"itemLimit":{"type":"number","required":false,"default":100,"visibility":"user-or-llm","description":"Max dataset items to fetch (1-250000). Default: 100. Example: 500"},"memory":{"type":"number","required":false,"visibility":"user-or-llm","description":"Memory in megabytes allocated for the actor run (128-32768). Example: 1024 for 1GB, 2048 for 2GB"},"timeout":{"type":"number","required":false,"visibility":"user-or-llm","description":"Timeout in seconds for the actor run. Example: 300 for 5 minutes, 3600 for 1 hour"},"build":{"type":"string","required":false,"visibility":"user-or-llm","description":"Actor build to run. Examples: \\"latest\\", \\"beta\\", \\"1.2.3\\", \\"build-tag-name\\""}},"oauth":{"required":false,"provider":"apify","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apify_run_actor_sync":{"id":"apify_run_actor_sync","name":"APIFY Run Actor (Sync)","description":"Run an APIFY actor synchronously and get results (max 5 minutes)","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"APIFY API token from console.apify.com/account#/integrations"},"actorId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Actor ID or username/actor-name. Examples: \\"apify/web-scraper\\", \\"janedoe/my-actor\\", \\"moJRLRc85AitArpNN\\""},"input":{"type":"string","required":false,"visibility":"user-or-llm","description":"Actor input as JSON string. Example: { \\"startUrls\\": [ { \\"url\\": \\"https://example.com\\" } ], \\"maxPages\\": 10 }"},"memory":{"type":"number","required":false,"visibility":"user-or-llm","description":"Memory in megabytes allocated for the actor run (128-32768). Example: 1024 for 1GB, 2048 for 2GB"},"timeout":{"type":"number","required":false,"visibility":"user-or-llm","description":"Timeout in seconds for the actor run. Example: 300 for 5 minutes, 3600 for 1 hour"},"build":{"type":"string","required":false,"visibility":"user-or-llm","description":"Actor build to run. Examples: \\"latest\\", \\"beta\\", \\"1.2.3\\", \\"build-tag-name\\""}},"oauth":{"required":false,"provider":"apify","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apify_run_task":{"id":"apify_run_task","name":"APIFY Run Task","description":"Run a saved APIFY actor task synchronously and get dataset items (max 5 minutes)","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"APIFY API token from console.apify.com/account#/integrations"},"taskId":{"type":"string","required":true,"visibility":"user-or-llm","description":"Task ID or username/task-name. Examples: \\"janedoe/my-task\\", \\"moJRLRc85AitArpNN\\""},"input":{"type":"string","required":false,"visibility":"user-or-llm","description":"JSON string that overrides the task\'s saved input. Example: { \\"startUrls\\": [ { \\"url\\": \\"https://example.com\\" } ] }"},"itemLimit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Max dataset items to return (1-250000). Example: 500"},"memory":{"type":"number","required":false,"visibility":"user-or-llm","description":"Memory in megabytes allocated for the run (128-32768). Example: 1024 for 1GB"},"timeout":{"type":"number","required":false,"visibility":"user-or-llm","description":"Timeout in seconds for the run. Example: 300 for 5 minutes"},"build":{"type":"string","required":false,"visibility":"user-or-llm","description":"Actor build to run. Examples: \\"latest\\", \\"beta\\", \\"1.2.3\\""}},"oauth":{"required":false,"provider":"apify","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apollo_account_bulk_create":{"id":"apollo_account_bulk_create","name":"Apollo Bulk Create Accounts","description":"Create up to 100 accounts at once in your Apollo database. Set run_dedupe=true to deduplicate by domain, organization_id, and name. Master key required.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key (master key required)"},"accounts":{"type":"array","required":true,"visibility":"user-or-llm","description":"Array of accounts to create (max 100). Each account should include a name, and may optionally include domain, phone, phone_status_cd, raw_address, owner_id, linkedin_url, facebook_url, twitter_url, salesforce_id, and hubspot_id."},"append_label_names":{"type":"array","required":false,"visibility":"user-only","description":"Array of label names to add to ALL accounts in this request"},"run_dedupe":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"When true, performs aggressive deduplication by domain, organization_id, and name (defaults to false)"}},"oauth":{"required":false,"provider":"apollo","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apollo_account_bulk_update":{"id":"apollo_account_bulk_update","name":"Apollo Bulk Update Accounts","description":"Update up to 1000 existing accounts at once in your Apollo database (higher limit than contacts!). Each account must include an id field. Master key required.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key (master key required)"},"account_ids":{"type":"array","required":false,"visibility":"user-or-llm","description":"Array of account IDs to update with the same values (max 1000). Use with name/owner_id for uniform updates. Use either this OR account_attributes."},"name":{"type":"string","required":false,"visibility":"user-or-llm","description":"When using account_ids, apply this name to all accounts"},"owner_id":{"type":"string","required":false,"visibility":"user-or-llm","description":"When using account_ids, apply this owner to all accounts"},"account_stage_id":{"type":"string","required":false,"visibility":"user-or-llm","description":"When using account_ids, apply this account stage to all accounts"},"account_attributes":{"type":"json","required":false,"visibility":"user-or-llm","description":"Array of account objects with individual updates (each must include id). Example: [{\\"id\\": \\"acc1\\", \\"name\\": \\"Acme\\", \\"owner_id\\": \\"u1\\", \\"account_stage_id\\": \\"s1\\", \\"typed_custom_fields\\": {\\"field_id\\": \\"value\\"}}]"},"async":{"type":"boolean","required":false,"visibility":"user-only","description":"When true, processes the update asynchronously. Only supported when using account_ids; returns 422 if used with account_attributes."}},"oauth":{"required":false,"provider":"apollo","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apollo_account_create":{"id":"apollo_account_create","name":"Apollo Create Account","description":"Create a new account (company) in your Apollo database","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key (master key required)"},"name":{"type":"string","required":true,"visibility":"user-or-llm","description":"Company name (e.g., \\"Acme Corporation\\")"},"domain":{"type":"string","required":false,"visibility":"user-or-llm","description":"Company domain without www. prefix (e.g., \\"acme.com\\")"},"phone":{"type":"string","required":false,"visibility":"user-or-llm","description":"Primary phone number for the account"},"owner_id":{"type":"string","required":false,"visibility":"user-only","description":"Apollo user ID of the account owner"},"account_stage_id":{"type":"string","required":false,"visibility":"user-only","description":"Apollo ID for the account stage to assign this account to"},"raw_address":{"type":"string","required":false,"visibility":"user-or-llm","description":"Corporate location (e.g., \\"San Francisco, CA, USA\\")"},"typed_custom_fields":{"type":"json","required":false,"visibility":"user-only","description":"Custom field values as { custom_field_id: value } map"}},"oauth":{"required":false,"provider":"apollo","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apollo_account_search":{"id":"apollo_account_search","name":"Apollo Search Accounts","description":"Search your team\'s accounts in Apollo. Display limit: 50,000 records (100 records per page, 500 pages max). Use filters to narrow results. Master key required.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key (master key required)"},"q_organization_name":{"type":"string","required":false,"visibility":"user-or-llm","description":"Filter accounts by organization name (partial-match search)"},"account_stage_ids":{"type":"array","required":false,"visibility":"user-only","description":"Filter by account stage IDs"},"account_label_ids":{"type":"array","required":false,"visibility":"user-only","description":"Filter by account label IDs"},"sort_by_field":{"type":"string","required":false,"visibility":"user-or-llm","description":"Sort field: \\"account_last_activity_date\\", \\"account_created_at\\", or \\"account_updated_at\\""},"sort_ascending":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Sort ascending when true. Defaults to descending."},"page":{"type":"number","required":false,"visibility":"user-or-llm","description":"Page number for pagination (e.g., 1, 2, 3)"},"per_page":{"type":"number","required":false,"visibility":"user-or-llm","description":"Results per page, max 100 (e.g., 25, 50, 100)"}},"oauth":{"required":false,"provider":"apollo","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apollo_account_update":{"id":"apollo_account_update","name":"Apollo Update Account","description":"Update an existing account in your Apollo database","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key"},"account_id":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the account to update (e.g., \\"acc_abc123\\")"},"name":{"type":"string","required":false,"visibility":"user-or-llm","description":"Company name (e.g., \\"Acme Corporation\\")"},"domain":{"type":"string","required":false,"visibility":"user-or-llm","description":"Company domain (e.g., \\"acme.com\\")"},"phone":{"type":"string","required":false,"visibility":"user-or-llm","description":"Company phone number"},"owner_id":{"type":"string","required":false,"visibility":"user-only","description":"Apollo user ID of the account owner"},"account_stage_id":{"type":"string","required":false,"visibility":"user-only","description":"Apollo ID for the account stage to assign this account to"},"raw_address":{"type":"string","required":false,"visibility":"user-or-llm","description":"Corporate location (e.g., \\"San Francisco, CA, USA\\")"},"typed_custom_fields":{"type":"json","required":false,"visibility":"user-only","description":"Custom field values as { custom_field_id: value } map"}},"oauth":{"required":false,"provider":"apollo","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apollo_contact_bulk_create":{"id":"apollo_contact_bulk_create","name":"Apollo Bulk Create Contacts","description":"Create up to 100 contacts at once in your Apollo database. Supports deduplication to prevent creating duplicate contacts. Master key required.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key (master key required)"},"contacts":{"type":"array","required":true,"visibility":"user-or-llm","description":"Array of contacts to create (max 100). Each contact may include first_name, last_name, email, title, organization_name, account_id, owner_id, contact_stage_id, linkedin_url, phone (single string) or phone_numbers (array of {raw_number, position}), contact_emails, typed_custom_fields, and CRM IDs (salesforce_contact_id, hubspot_id, team_id) for cross-system matching"},"append_label_names":{"type":"array","required":false,"visibility":"user-or-llm","description":"Label names to add to all contacts in this request (e.g., [\\"Hot Lead\\"])"},"run_dedupe":{"type":"boolean","required":false,"visibility":"user-only","description":"Enable deduplication to prevent creating duplicate contacts. When true, existing contacts are returned without modification"}},"oauth":{"required":false,"provider":"apollo","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apollo_contact_bulk_update":{"id":"apollo_contact_bulk_update","name":"Apollo Bulk Update Contacts","description":"Update up to 100 existing contacts at once in your Apollo database. Each contact must include an id field. Master key required.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key (master key required)"},"contact_ids":{"type":"array","required":false,"visibility":"user-or-llm","description":"Array of contact IDs to update. Must be paired with an object-form contact_attributes specifying the fields to apply uniformly to all listed contacts."},"contact_attributes":{"type":"json","required":false,"visibility":"user-or-llm","description":"Required. Either an array of per-contact updates (each with id) — used standalone — or a single object of attributes to apply to all contact_ids. Supported fields: owner_id, email, organization_name, title, first_name, last_name, account_id, present_raw_address, linkedin_url, typed_custom_fields"},"async":{"type":"boolean","required":false,"visibility":"user-only","description":"Force asynchronous processing. Automatically enabled for >100 contacts"}},"oauth":{"required":false,"provider":"apollo","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apollo_contact_create":{"id":"apollo_contact_create","name":"Apollo Create Contact","description":"Create a new contact in your Apollo database","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key"},"first_name":{"type":"string","required":true,"visibility":"user-or-llm","description":"First name of the contact"},"last_name":{"type":"string","required":true,"visibility":"user-or-llm","description":"Last name of the contact"},"email":{"type":"string","required":false,"visibility":"user-or-llm","description":"Email address of the contact"},"title":{"type":"string","required":false,"visibility":"user-or-llm","description":"Job title (e.g., \\"VP of Sales\\", \\"Software Engineer\\")"},"account_id":{"type":"string","required":false,"visibility":"user-or-llm","description":"Apollo account ID to associate with (e.g., \\"acc_abc123\\")"},"owner_id":{"type":"string","required":false,"visibility":"user-only","description":"User ID of the contact owner (accepted by Apollo but not officially documented for POST /contacts)"},"organization_name":{"type":"string","required":false,"visibility":"user-or-llm","description":"Name of the contact\'s employer (e.g., \\"Apollo\\")"},"website_url":{"type":"string","required":false,"visibility":"user-or-llm","description":"Corporate website URL (e.g., \\"https://www.apollo.io/\\")"},"label_names":{"type":"array","required":false,"visibility":"user-or-llm","description":"Lists/labels to add the contact to (e.g., [\\"Prospects\\"])"},"contact_stage_id":{"type":"string","required":false,"visibility":"user-or-llm","description":"Apollo ID for the contact stage"},"present_raw_address":{"type":"string","required":false,"visibility":"user-or-llm","description":"Personal location for the contact (e.g., \\"Atlanta, United States\\")"},"direct_phone":{"type":"string","required":false,"visibility":"user-or-llm","description":"Primary phone number"},"corporate_phone":{"type":"string","required":false,"visibility":"user-or-llm","description":"Work/office phone number"},"mobile_phone":{"type":"string","required":false,"visibility":"user-or-llm","description":"Mobile phone number"},"home_phone":{"type":"string","required":false,"visibility":"user-or-llm","description":"Home phone number"},"other_phone":{"type":"string","required":false,"visibility":"user-or-llm","description":"Alternative phone number"},"typed_custom_fields":{"type":"json","required":false,"visibility":"user-or-llm","description":"Custom field values keyed by custom field ID"},"run_dedupe":{"type":"boolean","required":false,"visibility":"user-only","description":"When true, Apollo deduplicates against existing contacts"}},"oauth":{"required":false,"provider":"apollo","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apollo_contact_search":{"id":"apollo_contact_search","name":"Apollo Search Contacts","description":"Search your team\'s contacts in Apollo","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key"},"q_keywords":{"type":"string","required":false,"visibility":"user-or-llm","description":"Keywords to search for"},"contact_stage_ids":{"type":"array","required":false,"visibility":"user-only","description":"Filter by contact stage IDs"},"contact_label_ids":{"type":"array","required":false,"visibility":"user-only","description":"Filter by Apollo label IDs (lists)"},"sort_by_field":{"type":"string","required":false,"visibility":"user-only","description":"Sort field: contact_last_activity_date, contact_email_last_opened_at, contact_email_last_clicked_at, contact_created_at, or contact_updated_at"},"sort_ascending":{"type":"boolean","required":false,"visibility":"user-only","description":"When true, sort ascending. Must be used together with sort_by_field"},"page":{"type":"number","required":false,"visibility":"user-or-llm","description":"Page number for pagination (e.g., 1, 2, 3)"},"per_page":{"type":"number","required":false,"visibility":"user-or-llm","description":"Results per page, max 100 (e.g., 25, 50, 100)"}},"oauth":{"required":false,"provider":"apollo","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apollo_contact_update":{"id":"apollo_contact_update","name":"Apollo Update Contact","description":"Update an existing contact in your Apollo database","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key"},"contact_id":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the contact to update (e.g., \\"con_abc123\\")"},"first_name":{"type":"string","required":false,"visibility":"user-or-llm","description":"First name of the contact"},"last_name":{"type":"string","required":false,"visibility":"user-or-llm","description":"Last name of the contact"},"email":{"type":"string","required":false,"visibility":"user-or-llm","description":"Email address"},"title":{"type":"string","required":false,"visibility":"user-or-llm","description":"Job title (e.g., \\"VP of Sales\\", \\"Software Engineer\\")"},"account_id":{"type":"string","required":false,"visibility":"user-or-llm","description":"Apollo account ID (e.g., \\"acc_abc123\\")"},"owner_id":{"type":"string","required":false,"visibility":"user-only","description":"User ID of the contact owner (accepted by Apollo but not officially documented for PATCH /contacts/{id})"},"organization_name":{"type":"string","required":false,"visibility":"user-or-llm","description":"Name of the contact\'s employer (e.g., \\"Apollo\\")"},"website_url":{"type":"string","required":false,"visibility":"user-or-llm","description":"Corporate website URL (e.g., \\"https://www.apollo.io/\\")"},"label_names":{"type":"array","required":false,"visibility":"user-or-llm","description":"Lists/labels to add the contact to (e.g., [\\"Prospects\\"])"},"contact_stage_id":{"type":"string","required":false,"visibility":"user-or-llm","description":"Apollo ID for the contact stage"},"present_raw_address":{"type":"string","required":false,"visibility":"user-or-llm","description":"Personal location for the contact (e.g., \\"Atlanta, United States\\")"},"direct_phone":{"type":"string","required":false,"visibility":"user-or-llm","description":"Primary phone number"},"corporate_phone":{"type":"string","required":false,"visibility":"user-or-llm","description":"Work/office phone number"},"mobile_phone":{"type":"string","required":false,"visibility":"user-or-llm","description":"Mobile phone number"},"home_phone":{"type":"string","required":false,"visibility":"user-or-llm","description":"Home phone number"},"other_phone":{"type":"string","required":false,"visibility":"user-or-llm","description":"Alternative phone number"},"typed_custom_fields":{"type":"json","required":false,"visibility":"user-or-llm","description":"Custom field values keyed by custom field ID"}},"oauth":{"required":false,"provider":"apollo","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apollo_email_accounts":{"id":"apollo_email_accounts","name":"Apollo Get Email Accounts","description":"Get list of team\'s linked email accounts in Apollo","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key (master key required)"}},"oauth":{"required":false,"provider":"apollo","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apollo_opportunity_create":{"id":"apollo_opportunity_create","name":"Apollo Create Opportunity","description":"Create a new deal for an account in your Apollo database (master key required)","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key (master key required)"},"name":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the opportunity/deal (e.g., \\"Enterprise License - Q1\\")"},"account_id":{"type":"string","required":false,"visibility":"user-or-llm","description":"ID of the account this opportunity belongs to (e.g., \\"acc_abc123\\")"},"amount":{"type":"string","required":false,"visibility":"user-or-llm","description":"Monetary value as a plain number string with no commas or currency symbols"},"opportunity_stage_id":{"type":"string","required":false,"visibility":"user-only","description":"ID of the opportunity stage"},"owner_id":{"type":"string","required":false,"visibility":"user-only","description":"User ID of the opportunity owner"},"closed_date":{"type":"string","required":false,"visibility":"user-or-llm","description":"Expected close date in YYYY-MM-DD format"},"typed_custom_fields":{"type":"json","required":false,"visibility":"user-only","description":"Custom field values as { custom_field_id: value } map"}},"oauth":{"required":false,"provider":"apollo","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apollo_opportunity_get":{"id":"apollo_opportunity_get","name":"Apollo Get Opportunity","description":"Retrieve complete details of a specific deal/opportunity by ID","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key"},"opportunity_id":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the opportunity to retrieve (e.g., \\"opp_abc123\\")"}},"oauth":{"required":false,"provider":"apollo","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apollo_opportunity_search":{"id":"apollo_opportunity_search","name":"Apollo Search Opportunities","description":"Search and list all deals/opportunities in your team\'s Apollo account","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key"},"sort_by_field":{"type":"string","required":false,"visibility":"user-or-llm","description":"Sort field: \\"amount\\", \\"is_closed\\", or \\"is_won\\""},"page":{"type":"number","required":false,"visibility":"user-or-llm","description":"Page number for pagination (e.g., 1, 2, 3)"},"per_page":{"type":"number","required":false,"visibility":"user-or-llm","description":"Results per page, max 100 (e.g., 25, 50, 100)"}},"oauth":{"required":false,"provider":"apollo","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apollo_opportunity_update":{"id":"apollo_opportunity_update","name":"Apollo Update Opportunity","description":"Update an existing deal/opportunity in your Apollo database","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key"},"opportunity_id":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the opportunity to update (e.g., \\"opp_abc123\\")"},"name":{"type":"string","required":false,"visibility":"user-or-llm","description":"Name of the opportunity/deal (e.g., \\"Enterprise License - Q1\\")"},"amount":{"type":"string","required":false,"visibility":"user-or-llm","description":"Monetary value as a plain number string with no commas or currency symbols"},"opportunity_stage_id":{"type":"string","required":false,"visibility":"user-only","description":"ID of the opportunity stage"},"owner_id":{"type":"string","required":false,"visibility":"user-only","description":"User ID of the opportunity owner"},"closed_date":{"type":"string","required":false,"visibility":"user-or-llm","description":"Expected close date in YYYY-MM-DD format"},"typed_custom_fields":{"type":"json","required":false,"visibility":"user-only","description":"Custom field values as { custom_field_id: value } map"}},"oauth":{"required":false,"provider":"apollo","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apollo_organization_bulk_enrich":{"id":"apollo_organization_bulk_enrich","name":"Apollo Bulk Organization Enrichment","description":"Enrich data for up to 10 organizations at once using Apollo","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key"},"domains":{"type":"array","required":true,"visibility":"user-or-llm","description":"Array of company domains to enrich (max 10, no www. or @, e.g., [\\"apollo.io\\", \\"stripe.com\\"])"}},"oauth":{"required":false,"provider":"apollo","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apollo_organization_enrich":{"id":"apollo_organization_enrich","name":"Apollo Organization Enrichment","description":"Enrich data for a single organization using Apollo","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key"},"domain":{"type":"string","required":true,"visibility":"user-or-llm","description":"Company domain (e.g., \\"apollo.io\\", \\"acme.com\\")"}},"oauth":{"required":false,"provider":"apollo","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apollo_organization_search":{"id":"apollo_organization_search","name":"Apollo Organization Search","description":"Search Apollo\'s database for companies using filters","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key"},"organization_locations":{"type":"array","required":false,"visibility":"user-or-llm","description":"Company HQ locations (cities, US states, or countries)"},"organization_not_locations":{"type":"array","required":false,"visibility":"user-or-llm","description":"Exclude companies whose HQ is in these locations"},"organization_num_employees_ranges":{"type":"array","required":false,"visibility":"user-or-llm","description":"Employee count ranges as \\"min,max\\" strings (e.g., [\\"1,10\\", \\"250,500\\", \\"10000,20000\\"])"},"q_organization_keyword_tags":{"type":"array","required":false,"visibility":"user-or-llm","description":"Industry or keyword tags"},"q_organization_name":{"type":"string","required":false,"visibility":"user-or-llm","description":"Organization name to search for (e.g., \\"Acme\\", \\"TechCorp\\")"},"organization_ids":{"type":"array","required":false,"visibility":"user-or-llm","description":"Apollo organization IDs to include (e.g., [\\"5e66b6381e05b4008c8331b8\\"])"},"q_organization_domains_list":{"type":"array","required":false,"visibility":"user-or-llm","description":"Domain names to filter by (no www. or @, up to 1,000)"},"page":{"type":"number","required":false,"visibility":"user-or-llm","description":"Page number for pagination (e.g., 1, 2, 3)"},"per_page":{"type":"number","required":false,"visibility":"user-or-llm","description":"Results per page, max 100 (e.g., 25, 50, 100)"}},"oauth":{"required":false,"provider":"apollo","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apollo_people_bulk_enrich":{"id":"apollo_people_bulk_enrich","name":"Apollo Bulk People Enrichment","description":"Enrich data for up to 10 people at once using Apollo","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key"},"people":{"type":"array","required":true,"visibility":"user-or-llm","description":"Array of people to enrich (max 10)"},"reveal_personal_emails":{"type":"boolean","required":false,"visibility":"user-only","description":"Reveal personal email addresses (uses credits)"},"reveal_phone_number":{"type":"boolean","required":false,"visibility":"user-only","description":"Reveal phone numbers (uses credits, requires webhook_url)"},"webhook_url":{"type":"string","required":false,"visibility":"user-only","description":"Webhook URL for async phone number delivery (required when reveal_phone_number is true)"}},"oauth":{"required":false,"provider":"apollo","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apollo_people_enrich":{"id":"apollo_people_enrich","name":"Apollo People Enrichment","description":"Enrich data for a single person using Apollo","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key"},"first_name":{"type":"string","required":false,"visibility":"user-or-llm","description":"First name of the person"},"last_name":{"type":"string","required":false,"visibility":"user-or-llm","description":"Last name of the person"},"name":{"type":"string","required":false,"visibility":"user-or-llm","description":"Full name of the person (alternative to first_name/last_name)"},"id":{"type":"string","required":false,"visibility":"user-or-llm","description":"Apollo ID for the person"},"hashed_email":{"type":"string","required":false,"visibility":"user-or-llm","description":"MD5 or SHA-256 hashed email"},"email":{"type":"string","required":false,"visibility":"user-or-llm","description":"Email address of the person"},"organization_name":{"type":"string","required":false,"visibility":"user-or-llm","description":"Company name where the person works"},"domain":{"type":"string","required":false,"visibility":"user-or-llm","description":"Company domain (e.g., \\"apollo.io\\", \\"acme.com\\")"},"linkedin_url":{"type":"string","required":false,"visibility":"user-or-llm","description":"LinkedIn profile URL"},"reveal_personal_emails":{"type":"boolean","required":false,"visibility":"user-only","description":"Reveal personal email addresses (uses credits)"},"reveal_phone_number":{"type":"boolean","required":false,"visibility":"user-only","description":"Reveal phone numbers (uses credits, requires webhook_url)"},"webhook_url":{"type":"string","required":false,"visibility":"user-only","description":"Webhook URL for async phone number delivery (required when reveal_phone_number is true)"}},"oauth":{"required":false,"provider":"apollo","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apollo_people_search":{"id":"apollo_people_search","name":"Apollo People Search","description":"Search Apollo\'s database for people using demographic filters","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key"},"person_titles":{"type":"array","required":false,"visibility":"user-or-llm","description":"Job titles to search for (e.g., [\\"CEO\\", \\"VP of Sales\\"])"},"include_similar_titles":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Whether to return people with job titles similar to person_titles"},"person_locations":{"type":"array","required":false,"visibility":"user-or-llm","description":"Locations to search in (e.g., [\\"San Francisco, CA\\", \\"New York, NY\\"])"},"person_seniorities":{"type":"array","required":false,"visibility":"user-or-llm","description":"Seniority levels (one of: owner, founder, c_suite, partner, vp, head, director, manager, senior, entry, intern)"},"organization_ids":{"type":"array","required":false,"visibility":"user-or-llm","description":"Apollo organization IDs to filter by (e.g., [\\"5e66b6381e05b4008c8331b8\\"])"},"organization_names":{"type":"array","required":false,"visibility":"user-or-llm","description":"Company names to search within (legacy filter)"},"organization_locations":{"type":"array","required":false,"visibility":"user-or-llm","description":"Headquarters locations of the people\'s current employer (e.g., [\'texas\', \'tokyo\', \'spain\'])"},"q_organization_domains_list":{"type":"array","required":false,"visibility":"user-or-llm","description":"Employer domain names (e.g., [\\"apollo.io\\", \\"microsoft.com\\"]) — up to 1,000, no www. or @"},"organization_num_employees_ranges":{"type":"array","required":false,"visibility":"user-or-llm","description":"Employee count ranges for the person\'s current employer. Each entry is \\"min,max\\" (e.g., [\\"1,10\\", \\"250,500\\", \\"10000,20000\\"])"},"contact_email_status":{"type":"array","required":false,"visibility":"user-or-llm","description":"Email statuses to filter by: \\"verified\\", \\"unverified\\", \\"likely to engage\\", \\"unavailable\\""},"q_keywords":{"type":"string","required":false,"visibility":"user-or-llm","description":"Keywords to search for"},"page":{"type":"number","required":false,"visibility":"user-or-llm","description":"Page number for pagination, default 1 (e.g., 1, 2, 3)"},"per_page":{"type":"number","required":false,"visibility":"user-or-llm","description":"Results per page, default 25, max 100 (e.g., 25, 50, 100)"}},"oauth":{"required":false,"provider":"apollo","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apollo_sequence_add_contacts":{"id":"apollo_sequence_add_contacts","name":"Apollo Add Contacts to Sequence","description":"Add contacts to an Apollo sequence","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key (master key required)"},"sequence_id":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the sequence to add contacts to (e.g., \\"seq_abc123\\")"},"contact_ids":{"type":"array","required":false,"visibility":"user-or-llm","description":"Array of contact IDs to add to the sequence (e.g., [\\"con_abc123\\", \\"con_def456\\"]). Either contact_ids or label_names must be provided."},"label_names":{"type":"array","required":false,"visibility":"user-or-llm","description":"Array of label names to identify contacts to add to the sequence. Either contact_ids or label_names must be provided."},"send_email_from_email_account_id":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the email account to send from. Use the Get Email Accounts operation to look this up."},"send_email_from_email_address":{"type":"string","required":false,"visibility":"user-only","description":"Specific email address to send from within the email account."},"sequence_no_email":{"type":"boolean","required":false,"visibility":"user-only","description":"Add contacts even if they have no email address"},"sequence_unverified_email":{"type":"boolean","required":false,"visibility":"user-only","description":"Add contacts with unverified email addresses"},"sequence_job_change":{"type":"boolean","required":false,"visibility":"user-only","description":"Add contacts who recently changed jobs"},"sequence_active_in_other_campaigns":{"type":"boolean","required":false,"visibility":"user-only","description":"Add contacts active in other campaigns"},"sequence_finished_in_other_campaigns":{"type":"boolean","required":false,"visibility":"user-only","description":"Add contacts who finished other campaigns"},"sequence_same_company_in_same_campaign":{"type":"boolean","required":false,"visibility":"user-only","description":"Add contacts even if others from the same company are in the sequence"},"contacts_without_ownership_permission":{"type":"boolean","required":false,"visibility":"user-only","description":"Add contacts without ownership permission"},"add_if_in_queue":{"type":"boolean","required":false,"visibility":"user-only","description":"Add contacts even if they are in the queue"},"contact_verification_skipped":{"type":"boolean","required":false,"visibility":"user-only","description":"Skip contact verification when adding"},"user_id":{"type":"string","required":false,"visibility":"user-only","description":"ID of the user performing the action"},"status":{"type":"string","required":false,"visibility":"user-only","description":"Initial status for added contacts: \\"active\\" or \\"paused\\""},"auto_unpause_at":{"type":"string","required":false,"visibility":"user-only","description":"ISO 8601 datetime to automatically unpause contacts"}},"oauth":{"required":false,"provider":"apollo","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apollo_sequence_search":{"id":"apollo_sequence_search","name":"Apollo Search Sequences","description":"Search for sequences/campaigns in your team\'s Apollo account (master key required)","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key (master key required)"},"q_name":{"type":"string","required":false,"visibility":"user-or-llm","description":"Search sequences by name (e.g., \\"Outbound Q1\\", \\"Follow-up\\")"},"page":{"type":"number","required":false,"visibility":"user-or-llm","description":"Page number for pagination (e.g., 1, 2, 3)"},"per_page":{"type":"number","required":false,"visibility":"user-or-llm","description":"Results per page, max 100 (e.g., 25, 50, 100)"}},"oauth":{"required":false,"provider":"apollo","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apollo_task_create":{"id":"apollo_task_create","name":"Apollo Create Task","description":"Create one or more tasks in Apollo (one task per contact_id, master key required)","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key (master key required)"},"user_id":{"type":"string","required":true,"visibility":"user-or-llm","description":"ID of the Apollo user the task is assigned to"},"contact_ids":{"type":"array","required":true,"visibility":"user-or-llm","description":"Array of contact IDs. One task is created per contact."},"priority":{"type":"string","required":false,"visibility":"user-or-llm","description":"Task priority: \\"high\\", \\"medium\\", or \\"low\\" (defaults to \\"medium\\")"},"due_at":{"type":"string","required":true,"visibility":"user-or-llm","description":"Due date/time in ISO 8601 format (e.g., \\"2024-12-31T23:59:59Z\\")"},"type":{"type":"string","required":true,"visibility":"user-or-llm","description":"Task type: \\"call\\", \\"outreach_manual_email\\", \\"linkedin_step_connect\\", \\"linkedin_step_message\\", \\"linkedin_step_view_profile\\", \\"linkedin_step_interact_post\\", or \\"action_item\\""},"status":{"type":"string","required":true,"visibility":"user-or-llm","description":"Task status: \\"scheduled\\", \\"completed\\", or \\"skipped\\""},"note":{"type":"string","required":false,"visibility":"user-or-llm","description":"Free-form note providing context for the task"}},"oauth":{"required":false,"provider":"apollo","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"apollo_task_search":{"id":"apollo_task_search","name":"Apollo Search Tasks","description":"Search for tasks in Apollo","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Apollo API key (master key required)"},"sort_by_field":{"type":"string","required":false,"visibility":"user-or-llm","description":"Sort field: \\"task_due_at\\" or \\"task_priority\\""},"open_factor_names":{"type":"array","required":false,"visibility":"user-or-llm","description":"Filter by status. Common values: [\\"task_types\\"] for open tasks, [\\"task_completed_at\\"] for completed tasks."},"page":{"type":"number","required":false,"visibility":"user-or-llm","description":"Page number for pagination (e.g., 1, 2, 3)"},"per_page":{"type":"number","required":false,"visibility":"user-or-llm","description":"Results per page, max 100 (e.g., 25, 50, 100)"}},"oauth":{"required":false,"provider":"apollo","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"appconfig_create_application":{"id":"appconfig_create_application","name":"AppConfig Create Application","description":"Create an application in AWS AppConfig","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"name":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the application to create"},"description":{"type":"string","required":false,"visibility":"user-or-llm","description":"Description of the application"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_create_configuration_profile":{"id":"appconfig_create_configuration_profile","name":"AppConfig Create Configuration Profile","description":"Create a configuration profile in an AWS AppConfig application","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID to create the configuration profile in"},"name":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the configuration profile"},"locationUri":{"type":"string","required":true,"visibility":"user-or-llm","description":"Where the configuration is stored. Use \\"hosted\\" for AppConfig-hosted configurations, or an SSM/S3 URI"},"description":{"type":"string","required":false,"visibility":"user-or-llm","description":"Description of the configuration profile"},"retrievalRoleArn":{"type":"string","required":false,"visibility":"user-or-llm","description":"ARN of an IAM role to retrieve the configuration (required for non-hosted URIs)"},"type":{"type":"string","required":false,"visibility":"user-or-llm","description":"Profile type: AWS.Freeform (default) or AWS.AppConfig.FeatureFlags"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_create_environment":{"id":"appconfig_create_environment","name":"AppConfig Create Environment","description":"Create an environment for an AWS AppConfig application","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID to create the environment in"},"name":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the environment to create"},"description":{"type":"string","required":false,"visibility":"user-or-llm","description":"Description of the environment"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_create_hosted_configuration_version":{"id":"appconfig_create_hosted_configuration_version","name":"AppConfig Create Hosted Configuration Version","description":"Create a new hosted configuration version for an AppConfig configuration profile","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID that owns the configuration profile"},"configurationProfileId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The configuration profile ID to add the version to"},"content":{"type":"string","required":true,"visibility":"user-or-llm","description":"The configuration content (e.g., a JSON or YAML document)"},"contentType":{"type":"string","required":true,"visibility":"user-or-llm","description":"Content type of the configuration (e.g., application/json, text/plain)"},"description":{"type":"string","required":false,"visibility":"user-or-llm","description":"Description of the configuration version"},"latestVersionNumber":{"type":"number","required":false,"visibility":"user-or-llm","description":"The version number of the latest version, used for optimistic concurrency"},"versionLabel":{"type":"string","required":false,"visibility":"user-or-llm","description":"A user-defined label for the configuration version"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_delete_application":{"id":"appconfig_delete_application","name":"AppConfig Delete Application","description":"Delete an AWS AppConfig application","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID to delete"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_delete_configuration_profile":{"id":"appconfig_delete_configuration_profile","name":"AppConfig Delete Configuration Profile","description":"Delete an AWS AppConfig configuration profile","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID that owns the configuration profile"},"configurationProfileId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The configuration profile ID to delete"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_delete_environment":{"id":"appconfig_delete_environment","name":"AppConfig Delete Environment","description":"Delete an AWS AppConfig environment","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID that owns the environment"},"environmentId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The environment ID to delete"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_delete_hosted_configuration_version":{"id":"appconfig_delete_hosted_configuration_version","name":"AppConfig Delete Hosted Configuration Version","description":"Delete a specific hosted configuration version from an AppConfig profile","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID that owns the configuration profile"},"configurationProfileId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The configuration profile ID that owns the version"},"versionNumber":{"type":"number","required":true,"visibility":"user-or-llm","description":"The version number to delete"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_get_application":{"id":"appconfig_get_application","name":"AppConfig Get Application","description":"Get details about a single AWS AppConfig application","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID to retrieve"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_get_configuration":{"id":"appconfig_get_configuration","name":"AppConfig Get Configuration","description":"Retrieve the latest deployed configuration for an AppConfig application, environment, and profile","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID or name to retrieve configuration for"},"environmentId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The environment ID or name to retrieve configuration for"},"configurationProfileId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The configuration profile ID or name to retrieve"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_get_configuration_profile":{"id":"appconfig_get_configuration_profile","name":"AppConfig Get Configuration Profile","description":"Get details about a single AWS AppConfig configuration profile","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID that owns the configuration profile"},"configurationProfileId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The configuration profile ID to retrieve"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_get_deployment":{"id":"appconfig_get_deployment","name":"AppConfig Get Deployment","description":"Get details about a specific AWS AppConfig deployment","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID of the deployment"},"environmentId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The environment ID of the deployment"},"deploymentNumber":{"type":"number","required":true,"visibility":"user-or-llm","description":"The sequence number of the deployment"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_get_environment":{"id":"appconfig_get_environment","name":"AppConfig Get Environment","description":"Get details about a single AWS AppConfig environment","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID that owns the environment"},"environmentId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The environment ID to retrieve"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_get_hosted_configuration_version":{"id":"appconfig_get_hosted_configuration_version","name":"AppConfig Get Hosted Configuration Version","description":"Retrieve a specific hosted configuration version from an AppConfig profile","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID that owns the configuration profile"},"configurationProfileId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The configuration profile ID to read the version from"},"versionNumber":{"type":"number","required":true,"visibility":"user-or-llm","description":"The version number to retrieve"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_list_applications":{"id":"appconfig_list_applications","name":"AppConfig List Applications","description":"List applications in AWS AppConfig","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"maxResults":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of applications to return (1-50)"},"nextToken":{"type":"string","required":false,"visibility":"user-or-llm","description":"Pagination token from a previous response"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_list_configuration_profiles":{"id":"appconfig_list_configuration_profiles","name":"AppConfig List Configuration Profiles","description":"List configuration profiles for an AWS AppConfig application","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID that owns the configuration profiles"},"maxResults":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of configuration profiles to return (1-50)"},"nextToken":{"type":"string","required":false,"visibility":"user-or-llm","description":"Pagination token from a previous response"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_list_deployment_strategies":{"id":"appconfig_list_deployment_strategies","name":"AppConfig List Deployment Strategies","description":"List deployment strategies available in AWS AppConfig","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"maxResults":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of deployment strategies to return (1-50)"},"nextToken":{"type":"string","required":false,"visibility":"user-or-llm","description":"Pagination token from a previous response"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_list_deployments":{"id":"appconfig_list_deployments","name":"AppConfig List Deployments","description":"List deployments for an AWS AppConfig environment","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID of the deployments"},"environmentId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The environment ID of the deployments"},"maxResults":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of deployments to return (1-50)"},"nextToken":{"type":"string","required":false,"visibility":"user-or-llm","description":"Pagination token from a previous response"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_list_environments":{"id":"appconfig_list_environments","name":"AppConfig List Environments","description":"List environments for an AWS AppConfig application","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID that owns the environments"},"maxResults":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of environments to return (1-50)"},"nextToken":{"type":"string","required":false,"visibility":"user-or-llm","description":"Pagination token from a previous response"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_list_hosted_configuration_versions":{"id":"appconfig_list_hosted_configuration_versions","name":"AppConfig List Hosted Configuration Versions","description":"List hosted configuration versions for an AWS AppConfig configuration profile","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID that owns the configuration profile"},"configurationProfileId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The configuration profile ID to list versions for"},"maxResults":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of versions to return (1-50)"},"nextToken":{"type":"string","required":false,"visibility":"user-or-llm","description":"Pagination token from a previous response"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_start_deployment":{"id":"appconfig_start_deployment","name":"AppConfig Start Deployment","description":"Start deploying a configuration version to an AWS AppConfig environment","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID to deploy in"},"environmentId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The environment ID to deploy to"},"deploymentStrategyId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The deployment strategy ID to use"},"configurationProfileId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The configuration profile ID to deploy"},"configurationVersion":{"type":"string","required":true,"visibility":"user-or-llm","description":"The configuration version to deploy"},"description":{"type":"string","required":false,"visibility":"user-or-llm","description":"Description of the deployment"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_stop_deployment":{"id":"appconfig_stop_deployment","name":"AppConfig Stop Deployment","description":"Stop an in-progress AWS AppConfig deployment","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID of the deployment"},"environmentId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The environment ID of the deployment"},"deploymentNumber":{"type":"number","required":true,"visibility":"user-or-llm","description":"The sequence number of the deployment to stop"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_update_application":{"id":"appconfig_update_application","name":"AppConfig Update Application","description":"Update the name or description of an AWS AppConfig application","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID to update"},"name":{"type":"string","required":false,"visibility":"user-or-llm","description":"New name for the application"},"description":{"type":"string","required":false,"visibility":"user-or-llm","description":"New description for the application"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_update_configuration_profile":{"id":"appconfig_update_configuration_profile","name":"AppConfig Update Configuration Profile","description":"Update the name, description, or retrieval role of an AppConfig configuration profile","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID that owns the configuration profile"},"configurationProfileId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The configuration profile ID to update"},"name":{"type":"string","required":false,"visibility":"user-or-llm","description":"New name for the configuration profile"},"description":{"type":"string","required":false,"visibility":"user-or-llm","description":"New description for the configuration profile"},"retrievalRoleArn":{"type":"string","required":false,"visibility":"user-or-llm","description":"New ARN of the IAM role used to retrieve the configuration"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"appconfig_update_environment":{"id":"appconfig_update_environment","name":"AppConfig Update Environment","description":"Update the name or description of an AWS AppConfig environment","version":"1.0","params":{"region":{"type":"string","required":true,"visibility":"user-only","description":"AWS region (e.g., us-east-1)"},"accessKeyId":{"type":"string","required":true,"visibility":"user-only","description":"AWS access key ID"},"secretAccessKey":{"type":"string","required":true,"visibility":"user-only","description":"AWS secret access key"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The application ID that owns the environment"},"environmentId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The environment ID to update"},"name":{"type":"string","required":false,"visibility":"user-or-llm","description":"New name for the environment"},"description":{"type":"string","required":false,"visibility":"user-or-llm","description":"New description for the environment"}},"oauth":{"required":false,"provider":"aws","credentialKind":"service-account","credentialSuppliedParams":["accessKeyId","secretAccessKey","awsAccessKeyId","awsSecretAccessKey"]},"hostedApiKey":"none"},"arxiv_get_author_papers":{"id":"arxiv_get_author_papers","name":"ArXiv Get Author Papers","description":"Search for papers by a specific author on ArXiv.","version":"1.0.0","params":{"authorName":{"type":"string","required":true,"visibility":"user-or-llm","description":"Author name to search for"},"maxResults":{"type":"number","required":false,"visibility":"user-only","description":"Maximum number of results to return (default: 10, max: 2000)"}},"hostedApiKey":"none"},"arxiv_get_paper":{"id":"arxiv_get_paper","name":"ArXiv Get Paper","description":"Get detailed information about a specific ArXiv paper by its ID.","version":"1.0.0","params":{"paperId":{"type":"string","required":true,"visibility":"user-or-llm","description":"ArXiv paper ID (e.g., \\"1706.03762\\")"}},"hostedApiKey":"none"},"arxiv_search":{"id":"arxiv_search","name":"ArXiv Search","description":"Search for academic papers on ArXiv by keywords, authors, titles, or other fields.","version":"1.0.0","params":{"searchQuery":{"type":"string","required":true,"visibility":"user-or-llm","description":"The search query to execute"},"searchField":{"type":"string","required":false,"visibility":"user-only","description":"Field to search in: all, ti (title), au (author), abs (abstract), co (comment), jr (journal), cat (category), rn (report number)"},"maxResults":{"type":"number","required":false,"visibility":"user-only","description":"Maximum number of results to return (default: 10, max: 2000)"},"sortBy":{"type":"string","required":false,"visibility":"user-only","description":"Sort by: relevance, lastUpdatedDate, submittedDate (default: relevance)"},"sortOrder":{"type":"string","required":false,"visibility":"user-only","description":"Sort order: ascending, descending (default: descending)"}},"hostedApiKey":"none"},"asana_add_comment":{"id":"asana_add_comment","name":"Asana Add Comment","description":"Add a comment (story) to an Asana task","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token for Asana"},"taskGid":{"type":"string","required":true,"visibility":"user-or-llm","description":"Asana task GID (numeric string)"},"text":{"type":"string","required":true,"visibility":"user-or-llm","description":"The text content of the comment"}},"oauth":{"required":true,"provider":"asana"},"hostedApiKey":"none"},"asana_add_followers":{"id":"asana_add_followers","name":"Asana Add Followers","description":"Add one or more followers to an Asana task","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token for Asana"},"taskGid":{"type":"string","required":true,"visibility":"user-or-llm","description":"GID of the Asana task (numeric string)"},"followers":{"type":"array","required":true,"visibility":"user-or-llm","description":"Array of user GIDs to add as followers to the task"}},"oauth":{"required":true,"provider":"asana"},"hostedApiKey":"none"},"asana_create_project":{"id":"asana_create_project","name":"Asana Create Project","description":"Create a new project in an Asana workspace","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token for Asana"},"workspace":{"type":"string","required":true,"visibility":"user-or-llm","description":"Asana workspace GID (numeric string) where the project will be created"},"name":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the project"},"notes":{"type":"string","required":false,"visibility":"user-or-llm","description":"Notes or description for the project"}},"oauth":{"required":true,"provider":"asana"},"hostedApiKey":"none"},"asana_create_section":{"id":"asana_create_section","name":"Asana Create Section","description":"Create a new section in an Asana project","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token for Asana"},"projectGid":{"type":"string","required":true,"visibility":"user-or-llm","description":"GID of the Asana project (numeric string) to add the section to"},"name":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the section"}},"oauth":{"required":true,"provider":"asana"},"hostedApiKey":"none"},"asana_create_subtask":{"id":"asana_create_subtask","name":"Asana Create Subtask","description":"Create a subtask under an existing Asana task","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token for Asana"},"taskGid":{"type":"string","required":true,"visibility":"user-or-llm","description":"GID of the parent Asana task (numeric string)"},"name":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the subtask"},"notes":{"type":"string","required":false,"visibility":"user-or-llm","description":"Notes or description for the subtask"},"assignee":{"type":"string","required":false,"visibility":"user-or-llm","description":"User GID to assign the subtask to"},"due_on":{"type":"string","required":false,"visibility":"user-or-llm","description":"Due date in YYYY-MM-DD format"}},"oauth":{"required":true,"provider":"asana"},"hostedApiKey":"none"},"asana_create_task":{"id":"asana_create_task","name":"Asana Create Task","description":"Create a new task in Asana","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token for Asana"},"workspace":{"type":"string","required":true,"visibility":"user-or-llm","description":"Asana workspace GID (numeric string) where the task will be created"},"name":{"type":"string","required":true,"visibility":"user-or-llm","description":"Name of the task"},"notes":{"type":"string","required":false,"visibility":"user-or-llm","description":"Notes or description for the task"},"assignee":{"type":"string","required":false,"visibility":"user-or-llm","description":"User GID to assign the task to"},"due_on":{"type":"string","required":false,"visibility":"user-or-llm","description":"Due date in YYYY-MM-DD format"}},"oauth":{"required":true,"provider":"asana"},"hostedApiKey":"none"},"asana_delete_task":{"id":"asana_delete_task","name":"Asana Delete Task","description":"Delete an Asana task by its GID (moves it to the trash)","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token for Asana"},"taskGid":{"type":"string","required":true,"visibility":"user-or-llm","description":"GID of the Asana task to delete (numeric string)"}},"oauth":{"required":true,"provider":"asana"},"hostedApiKey":"none"},"asana_get_project":{"id":"asana_get_project","name":"Asana Get Project","description":"Retrieve a single Asana project by its GID","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token for Asana"},"projectGid":{"type":"string","required":true,"visibility":"user-or-llm","description":"Asana project GID (numeric string) to retrieve"}},"oauth":{"required":true,"provider":"asana"},"hostedApiKey":"none"},"asana_get_projects":{"id":"asana_get_projects","name":"Asana Get Projects","description":"Retrieve all projects from an Asana workspace","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token for Asana"},"workspace":{"type":"string","required":true,"visibility":"user-or-llm","description":"Asana workspace GID (numeric string) to retrieve projects from"}},"oauth":{"required":true,"provider":"asana"},"hostedApiKey":"none"},"asana_get_task":{"id":"asana_get_task","name":"Asana Get Task","description":"Retrieve a single task by GID or get multiple tasks with filters","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token for Asana"},"taskGid":{"type":"string","required":false,"visibility":"user-or-llm","description":"The globally unique identifier (GID) of the task. If not provided, will get multiple tasks."},"workspace":{"type":"string","required":false,"visibility":"user-or-llm","description":"Asana workspace GID (numeric string) to filter tasks (required when not using taskGid)"},"project":{"type":"string","required":false,"visibility":"user-or-llm","description":"Asana project GID (numeric string) to filter tasks"},"limit":{"type":"number","required":false,"visibility":"user-or-llm","description":"Maximum number of tasks to return (default: 50)"}},"oauth":{"required":true,"provider":"asana"},"hostedApiKey":"none"},"asana_list_sections":{"id":"asana_list_sections","name":"Asana List Sections","description":"List all sections in an Asana project","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token for Asana"},"projectGid":{"type":"string","required":true,"visibility":"user-or-llm","description":"GID of the Asana project (numeric string) to list sections from"}},"oauth":{"required":true,"provider":"asana"},"hostedApiKey":"none"},"asana_list_workspaces":{"id":"asana_list_workspaces","name":"Asana List Workspaces","description":"List all Asana workspaces and organizations the authenticated user belongs to","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token for Asana"}},"oauth":{"required":true,"provider":"asana"},"hostedApiKey":"none"},"asana_search_tasks":{"id":"asana_search_tasks","name":"Asana Search Tasks","description":"Search for tasks in an Asana workspace","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token for Asana"},"workspace":{"type":"string","required":true,"visibility":"user-or-llm","description":"Asana workspace GID (numeric string) to search tasks in"},"text":{"type":"string","required":false,"visibility":"user-or-llm","description":"Text to search for in task names"},"assignee":{"type":"string","required":false,"visibility":"user-or-llm","description":"Filter tasks by assignee user GID"},"projects":{"type":"array","required":false,"visibility":"user-or-llm","description":"Array of Asana project GIDs (numeric strings) to filter tasks by"},"completed":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Filter by completion status"}},"oauth":{"required":true,"provider":"asana"},"hostedApiKey":"none"},"asana_update_task":{"id":"asana_update_task","name":"Asana Update Task","description":"Update an existing task in Asana","version":"1.0.0","params":{"accessToken":{"type":"string","required":true,"visibility":"hidden","description":"OAuth access token for Asana"},"taskGid":{"type":"string","required":true,"visibility":"user-or-llm","description":"Asana task GID (numeric string) of the task to update"},"name":{"type":"string","required":false,"visibility":"user-or-llm","description":"Updated name for the task"},"notes":{"type":"string","required":false,"visibility":"user-or-llm","description":"Updated notes or description for the task"},"assignee":{"type":"string","required":false,"visibility":"user-or-llm","description":"Updated assignee user GID"},"completed":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Mark task as completed or not completed"},"due_on":{"type":"string","required":false,"visibility":"user-or-llm","description":"Updated due date in YYYY-MM-DD format"}},"oauth":{"required":true,"provider":"asana"},"hostedApiKey":"none"},"ashby_add_candidate_tag":{"id":"ashby_add_candidate_tag","name":"Ashby Add Candidate Tag","description":"Adds a tag to a candidate in Ashby and returns the updated candidate.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ashby API Key"},"onBehalfOfUserId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Active Ashby user UUID to attribute this mutation to; the API key must permit on-behalf-of calls"},"candidateId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The UUID of the candidate to add the tag to"},"tagId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The UUID of the tag to add"}},"oauth":{"required":false,"provider":"ashby","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ashby_anonymize_candidate":{"id":"ashby_anonymize_candidate","name":"Ashby Anonymize Candidate","description":"Remove personally identifiable information from an Ashby candidate while retaining the candidate record and its applications. This operation does not delete the candidate. Requires the candidatesWrite permission.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ashby API Key"},"onBehalfOfUserId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Active Ashby user UUID to attribute this mutation to; the API key must permit on-behalf-of calls"},"candidateId":{"type":"string","required":true,"visibility":"user-or-llm","description":"UUID of the candidate to anonymize"}},"oauth":{"required":false,"provider":"ashby","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ashby_change_application_source":{"id":"ashby_change_application_source","name":"Ashby Change Application Source","description":"Changes the source attributed to an existing application, so programmatically created applications report correctly on the recruiting side. Requires the candidatesWrite permission.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ashby API Key"},"onBehalfOfUserId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Active Ashby user UUID to attribute this mutation to; the API key must permit on-behalf-of calls"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"UUID of the application whose source should change"},"sourceId":{"type":"string","required":false,"visibility":"user-or-llm","description":"UUID of the source to attribute the application to, as returned by List Sources. Omit only when unsetSource is true."},"unsetSource":{"type":"boolean","required":false,"visibility":"user-or-llm","description":"Set true to deliberately clear the application source. Required to unset, so that a missing or empty sourceId cannot wipe attribution by accident."}},"oauth":{"required":false,"provider":"ashby","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ashby_change_application_stage":{"id":"ashby_change_application_stage","name":"Ashby Change Application Stage","description":"Moves an application to a different interview stage. Requires an archive reason when moving to an Archived stage.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ashby API Key"},"onBehalfOfUserId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Active Ashby user UUID to attribute this mutation to; the API key must permit on-behalf-of calls"},"applicationId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The UUID of the application to update the stage of"},"interviewStageId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The UUID of the interview stage to move the application to"},"archiveReasonId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Archive reason UUID. Required when moving to an Archived stage, ignored otherwise"},"archiveEmail":{"type":"json","required":false,"visibility":"user-or-llm","description":"Archive email configuration with communicationTemplateId and optional sendAt ISO 8601 timestamp. Pass null or omit to send no archive email."}},"oauth":{"required":false,"provider":"ashby","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ashby_create_application":{"id":"ashby_create_application","name":"Ashby Create Application","description":"Creates a new application for a candidate on a job. Optionally specify interview plan, stage, source, and credited user.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ashby API Key"},"onBehalfOfUserId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Active Ashby user UUID to attribute this mutation to; the API key must permit on-behalf-of calls"},"candidateId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The UUID of the candidate to consider for the job"},"jobId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The UUID of the job to consider the candidate for"},"interviewPlanId":{"type":"string","required":false,"visibility":"user-or-llm","description":"UUID of the interview plan to use (defaults to the job default plan)"},"interviewStageId":{"type":"string","required":false,"visibility":"user-or-llm","description":"UUID of the interview stage to place the application in, or FirstPreInterviewScreen (defaults to the first Lead stage)"},"sourceId":{"type":"string","required":false,"visibility":"user-or-llm","description":"UUID of the source to set on the application"},"creditedToUserId":{"type":"string","required":false,"visibility":"user-or-llm","description":"UUID of the user the application is credited to"},"createdAt":{"type":"string","required":false,"visibility":"user-or-llm","description":"ISO 8601 timestamp to set as the application creation date (defaults to now)"},"applicationHistory":{"type":"json","required":false,"visibility":"user-or-llm","description":"Optional documented application history entries to create with the application"}},"oauth":{"required":false,"provider":"ashby","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ashby_create_candidate":{"id":"ashby_create_candidate","name":"Ashby Create Candidate","description":"Creates a new candidate record in Ashby.","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ashby API Key"},"onBehalfOfUserId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Active Ashby user UUID to attribute this mutation to; the API key must permit on-behalf-of calls"},"name":{"type":"string","required":true,"visibility":"user-or-llm","description":"The candidate full name"},"email":{"type":"string","required":false,"visibility":"user-or-llm","description":"Primary email address for the candidate"},"phoneNumber":{"type":"string","required":false,"visibility":"user-or-llm","description":"Primary phone number for the candidate"},"linkedInUrl":{"type":"string","required":false,"visibility":"user-or-llm","description":"LinkedIn profile URL"},"githubUrl":{"type":"string","required":false,"visibility":"user-or-llm","description":"GitHub profile URL"},"website":{"type":"string","required":false,"visibility":"user-or-llm","description":"Personal website URL"},"sourceId":{"type":"string","required":false,"visibility":"user-or-llm","description":"UUID of the source to attribute the candidate to"},"creditedToUserId":{"type":"string","required":false,"visibility":"user-or-llm","description":"UUID of the Ashby user to credit with sourcing this candidate"},"createdAt":{"type":"string","required":false,"visibility":"user-or-llm","description":"Backdated creation timestamp in ISO 8601 (e.g. 2024-01-01T00:00:00Z). Defaults to now."},"alternateEmailAddresses":{"type":"json","required":false,"visibility":"user-or-llm","description":"Array of additional email address strings to add to the candidate, e.g. [\\"a@x.com\\",\\"b@y.com\\"]"},"location":{"type":"json","required":false,"visibility":"user-or-llm","description":"Candidate location object with optional city, region, and country"}},"oauth":{"required":false,"provider":"ashby","credentialKind":"service-account","credentialParams":{"apiKey":"accessToken"},"credentialSuppliedParams":["apiKey"]},"hostedApiKey":"none"},"ashby_create_note":{"id":"ashby_create_note","name":"Ashby Create Note","description":"Creates a note on a candidate in Ashby. Supports plain text and HTML content (bold, italic, underline, links, lists, code).","version":"1.0.0","params":{"apiKey":{"type":"string","required":true,"visibility":"user-only","description":"Ashby API Key"},"onBehalfOfUserId":{"type":"string","required":false,"visibility":"user-or-llm","description":"Active Ashby user UUID to attribute this mutation to; the API key must permit on-behalf-of calls"},"candidateId":{"type":"string","required":true,"visibility":"user-or-llm","description":"The UUID of the candidate to add the note to"},"note":{"type":"string","required":true,"visibility":"user-or-llm","description":"The note content. If noteType is text/html, supports: , , , ,