Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

fix(salesforce): accept only instance paths for links in Salesforce responses (#9054)

Vlad Ligaia691b4b274ac
diff --git a/backend/src/ee/services/secret-rotation-v2/salesforce-oauth-credentials/salesforce-oauth-credentials-rotation-fns.test.ts b/backend/src/ee/services/secret-rotation-v2/salesforce-oauth-credentials/salesforce-oauth-credentials-rotation-fns.test.ts
new file mode 100644
index 0000000000..cf432a8c1f
--- /dev/null
+++ b/backend/src/ee/services/secret-rotation-v2/salesforce-oauth-credentials/salesforce-oauth-credentials-rotation-fns.test.ts
@@ -0,0 +1,112 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { TSecretRotationV2Raw } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-types";
+
+import { salesforceOauthCredentialsRotationFactory } from "./salesforce-oauth-credentials-rotation-fns";
+import { TSalesforceOauthCredentialsRotationWithConnection } from "./salesforce-oauth-credentials-rotation-types";
+
+const salesforce = vi.hoisted(() => ({
+ requested: [] as string[],
+ links: { consumer: "", staged: "" }
+}));
+
+vi.mock("@app/lib/validator", () => ({ blockLocalAndPrivateIpAddresses: vi.fn() }));
+vi.mock("@app/lib/logger", () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));
+vi.mock("@app/lib/config/request", () => ({
+ request: {
+ request: async ({ method, url }: { method: string; url: string }) => {
+ salesforce.requested.push(`${method} ${url}`);
+ if (url.endsWith("/services/oauth2/token")) return { data: { token_type: "Bearer", access_token: "token" } };
+ if (method === "GET") {
+ return { data: { consumers: [{ key: "app-key", stagedCredentialsUrl: salesforce.links.consumer }] } };
+ }
+ if (method === "POST") {
+ return {
+ data: { stagedCredentials: [{ url: salesforce.links.staged, key: "new-key", secret: "new-secret" }] }
+ };
+ }
+ return { data: {} };
+ }
+ }
+}));
+
+const INSTANCE_URL = "https://acme.my.salesforce.com";
+const CONSUMER_LINK = "/services/data/v65.0/apps/oauth/credentials/app-id/consumer-id/staged";
+const STAGED_LINK = `${CONSUMER_LINK}/staged-id`;
+const OUTSIDE_INSTANCE_MESSAGE = "Salesforce returned a link outside the connection's instance URL.";
+const TOKEN_REQUEST = `POST ${INSTANCE_URL}/services/oauth2/token`;
+
+const COMMITTED = "committed" as unknown as TSecretRotationV2Raw;
+
+// The factory reads the connection credentials, parameters and secrets mapping and nothing else.
+const rotation = {
+ connection: { credentials: { instanceUrl: INSTANCE_URL, consumerKey: "connection-key", consumerSecret: "secret" } },
+ parameters: { appId: "app-id", appName: "App" },
+ secretsMapping: { consumerKey: "CONSUMER_KEY", consumerSecret: "CONSUMER_SECRET" }
+} as unknown as TSalesforceOauthCredentialsRotationWithConnection;
+
+const makeFactory = () =>
+ salesforceOauthCredentialsRotationFactory(
+ rotation,
+ ...([{}, {}, {}, {}, {}] as unknown as [
+ Parameters<typeof salesforceOauthCredentialsRotationFactory>[1],
+ Parameters<typeof salesforceOauthCredentialsRotationFactory>[2],
+ Parameters<typeof salesforceOauthCredentialsRotationFactory>[3],
+ Parameters<typeof salesforceOauthCredentialsRotationFactory>[4],
+ Parameters<typeof salesforceOauthCredentialsRotationFactory>[5]
+ ])
+ );
+
+const requestedHosts = () => [...new Set(salesforce.requested.map((entry) => new URL(entry.split(" ")[1]).host))];
+
+describe("Salesforce OAuth credentials rotation links", () => {
+ beforeEach(() => {
+ salesforce.requested = [];
+ salesforce.links = { consumer: CONSUMER_LINK, staged: STAGED_LINK };
+ });
+
+ it("issues a new consumer secret through links on the instance", async () => {
+ const callback = vi.fn().mockResolvedValue(COMMITTED);
+
+ await makeFactory().issueCredentials(callback);
+
+ expect(callback).toHaveBeenCalledWith({
+ consumerKey: "new-key",
+ consumerSecret: "new-secret",
+ stagedCredentialUrl: STAGED_LINK
+ });
+ expect(salesforce.requested).toEqual([
+ TOKEN_REQUEST,
+ `GET ${INSTANCE_URL}/services/data/v65.0/apps/oauth/credentials/app-id`,
+ `POST ${INSTANCE_URL}${CONSUMER_LINK}`,
+ `PATCH ${INSTANCE_URL}${STAGED_LINK}`
+ ]);
+ });
+
+ it.each([
+ ["the consumer's staged credentials link", "consumer"],
+ ["the staged credential link", "staged"]
+ ] as const)("refuses to issue a secret when %s is outside the instance", async (_, link) => {
+ salesforce.links[link] = `@internal.example${STAGED_LINK}`;
+ const callback = vi.fn();
+
+ await expect(makeFactory().issueCredentials(callback)).rejects.toThrow(OUTSIDE_INSTANCE_MESSAGE);
+ expect(requestedHosts()).toEqual(["acme.my.salesforce.com"]);
+ expect(callback).not.toHaveBeenCalled();
+ });
+
+ it("refuses a rotation whose stored link is outside the instance before issuing a new secret", async () => {
+ const callback = vi.fn();
+ const previous = {
+ consumerKey: "old-key",
+ consumerSecret: "old-secret",
+ stagedCredentialUrl: `@internal.example${STAGED_LINK}`
+ };
+
+ await expect(makeFactory().rotateCredentials(previous, callback, previous)).rejects.toThrow(
+ OUTSIDE_INSTANCE_MESSAGE
+ );
+ expect(salesforce.requested).toEqual([TOKEN_REQUEST]);
+ expect(callback).not.toHaveBeenCalled();
+ });
+});
diff --git a/backend/src/ee/services/secret-rotation-v2/salesforce-oauth-credentials/salesforce-oauth-credentials-rotation-fns.ts b/backend/src/ee/services/secret-rotation-v2/salesforce-oauth-credentials/salesforce-oauth-credentials-rotation-fns.ts
index 12f2d80afc..f1f5d11ea6 100644
--- a/backend/src/ee/services/secret-rotation-v2/salesforce-oauth-credentials/salesforce-oauth-credentials-rotation-fns.ts
+++ b/backend/src/ee/services/secret-rotation-v2/salesforce-oauth-credentials/salesforce-oauth-credentials-rotation-fns.ts
@@ -13,6 +13,7 @@ import { BadRequestError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import {
getSalesforceConnectionAccessToken,
+ resolveSalesforcePath,
SALESFORCE_API_VERSION
} from "@app/services/app-connection/salesforce/salesforce-connection-fns";
@@ -45,14 +46,9 @@ export const salesforceOauthCredentialsRotationFactory: TRotationFactory<
};
};
- const $deleteStagedCredential = async (stagedCredentialUrl: string) => {
- const { instanceUrl, headers } = await $authedRequest();
+ const $deleteStagedCredential = async (url: string, headers: Record<string, string>) => {
try {
- await request.request({
- method: "DELETE",
- url: `${instanceUrl}${stagedCredentialUrl}`,
- headers
- });
+ await request.request({ method: "DELETE", url, headers });
} catch (error) {
// 404 means the credential was already gone (manually deleted, or auto-expired past Salesforce's grace window)
if (error instanceof AxiosError && error.response?.status === 404) return;
@@ -85,7 +81,7 @@ export const salesforceOauthCredentialsRotationFactory: TRotationFactory<
const { data: stagedData } = await request.request<TSalesforceStagedCredentialsResponse>({
method: "POST",
- url: `${instanceUrl}${consumer.stagedCredentialsUrl}`,
+ url: resolveSalesforcePath(instanceUrl, consumer.stagedCredentialsUrl),
headers
});
@@ -93,24 +89,23 @@ export const salesforceOauthCredentialsRotationFactory: TRotationFactory<
if (!staged?.url || !staged.key || !staged.secret) {
throw new Error("Salesforce did not return a staged credential after POST");
}
+ const stagedUrl = resolveSalesforcePath(instanceUrl, staged.url);
try {
await request.request({
method: "PATCH",
- url: `${instanceUrl}${staged.url}`,
+ url: stagedUrl,
headers,
data: { command: "rotate" }
});
} catch (error) {
// best-effort cleanup of the staged credential we just created
- await request
- .request({ method: "DELETE", url: `${instanceUrl}${staged.url}`, headers })
- .catch((cleanupError: Error) => {
- logger.warn(
- { err: cleanupError },
- `Failed to clean up Salesforce staged credential after PATCH rotate failure [stagedUrl=${staged.url}]`
- );
- });
+ await request.request({ method: "DELETE", url: stagedUrl, headers }).catch((cleanupError: Error) => {
+ logger.warn(
+ { err: cleanupError },
+ `Failed to clean up Salesforce staged credential after PATCH rotate failure [stagedUrl=${staged.url}]`
+ );
+ });
throw error;
}
@@ -167,13 +162,19 @@ export const salesforceOauthCredentialsRotationFactory: TRotationFactory<
const rotateCredentials: TRotationFactoryRotateCredentials<
TSalesforceOauthCredentialsRotationGeneratedCredentials
> = async (credentialToRevoke, callback) => {
+ // Resolve the stored link before issuing, so a refused link fails before Salesforce rotates the secret
+ const { instanceUrl, headers } = await $authedRequest();
+ const revokeUrl = credentialToRevoke?.stagedCredentialUrl
+ ? resolveSalesforcePath(instanceUrl, credentialToRevoke.stagedCredentialUrl)
+ : undefined;
+
const credentials = await $issueConsumerSecret();
// Salesforce keeps the previously-active credential valid for a grace period after PATCH rotate,
// which is why this rotation is dual-credentials. Once a credential ages out of the array (one
// generation past "previous"), DELETE it from Salesforce to prevent stale credentials from
// remaining authentic-able beyond their Infisical lifespan.
- if (credentialToRevoke?.stagedCredentialUrl) {
- await $deleteStagedCredential(credentialToRevoke.stagedCredentialUrl);
+ if (revokeUrl) {
+ await $deleteStagedCredential(revokeUrl, headers);
}
return callback(credentials);
};
diff --git a/backend/src/services/app-connection/salesforce/salesforce-connection-fns.test.ts b/backend/src/services/app-connection/salesforce/salesforce-connection-fns.test.ts
new file mode 100644
index 0000000000..b039198f40
--- /dev/null
+++ b/backend/src/services/app-connection/salesforce/salesforce-connection-fns.test.ts
@@ -0,0 +1,59 @@
+import { beforeEach, describe, expect, test, vi } from "vitest";
+
+import { listSalesforceConnectionOauthApps } from "./salesforce-connection-fns";
+import { TSalesforceConnection } from "./salesforce-connection-types";
+
+const salesforce = vi.hoisted(() => ({
+ requested: [] as string[],
+ pages: {} as Record<string, { apps: { identifier: string; developerName: string }[]; nextPageUrl: string | null }>
+}));
+
+vi.mock("@app/lib/validator", () => ({ blockLocalAndPrivateIpAddresses: vi.fn() }));
+vi.mock("@app/lib/config/request", () => ({
+ request: {
+ request: async ({ url }: { url: string }) => {
+ salesforce.requested.push(url);
+ if (url.endsWith("/services/oauth2/token")) return { data: { token_type: "Bearer", access_token: "token" } };
+ return { data: salesforce.pages[url] };
+ }
+ }
+}));
+
+const INSTANCE_URL = "https://acme.my.salesforce.com";
+const FIRST_PAGE = "/services/data/v65.0/apps/oauth/usage";
+const OUTSIDE_INSTANCE_MESSAGE = "Salesforce returned a link outside the connection's instance URL.";
+
+const connection = {
+ credentials: { instanceUrl: INSTANCE_URL, consumerKey: "key", consumerSecret: "secret" }
+} as TSalesforceConnection;
+
+const app = (identifier: string) => ({ identifier, developerName: identifier });
+
+describe("listSalesforceConnectionOauthApps", () => {
+ beforeEach(() => {
+ salesforce.requested = [];
+ salesforce.pages = {};
+ });
+
+ test("follows the next page link on the instance", async () => {
+ salesforce.pages[`${INSTANCE_URL}${FIRST_PAGE}`] = { apps: [app("first")], nextPageUrl: `${FIRST_PAGE}?page=2` };
+ salesforce.pages[`${INSTANCE_URL}${FIRST_PAGE}?page=2`] = { apps: [app("second")], nextPageUrl: null };
+
+ const apps = await listSalesforceConnectionOauthApps(connection);
+
+ expect(apps.map(({ identifier }) => identifier)).toEqual(["first", "second"]);
+ });
+
+ test("refuses a next page link outside the instance without requesting it", async () => {
+ salesforce.pages[`${INSTANCE_URL}${FIRST_PAGE}`] = {
+ apps: [app("first")],
+ nextPageUrl: `@internal.example${FIRST_PAGE}?page=2`
+ };
+
+ await expect(listSalesforceConnectionOauthApps(connection)).rejects.toThrow(OUTSIDE_INSTANCE_MESSAGE);
+ expect(salesforce.requested.map((url) => new URL(url).host)).toEqual([
+ "acme.my.salesforce.com",
+ "acme.my.salesforce.com"
+ ]);
+ });
+});
diff --git a/backend/src/services/app-connection/salesforce/salesforce-connection-fns.ts b/backend/src/services/app-connection/salesforce/salesforce-connection-fns.ts
index bb4e28c53e..1d6202f889 100644
--- a/backend/src/services/app-connection/salesforce/salesforce-connection-fns.ts
+++ b/backend/src/services/app-connection/salesforce/salesforce-connection-fns.ts
@@ -18,6 +18,17 @@ export const SALESFORCE_API_VERSION = "v65.0";
const normalizeInstanceUrl = (instanceUrl: string) =>
removeTrailingSlash(instanceUrl.startsWith("http") ? instanceUrl : `https://${instanceUrl}`);
+// Salesforce returns its links as paths on the instance the connection authenticated with
+export const resolveSalesforcePath = (instanceUrl: string, path: string) => {
+ if (!path.startsWith("/")) {
+ throw new BadRequestError({
+ message:
+ "Salesforce returned a link outside the connection's instance URL. Check that the instance URL points to your Salesforce org."
+ });
+ }
+ return `${instanceUrl}${path}`;
+};
+
export const getSalesforceConnectionListItem = () => {
return {
name: "Salesforce" as const,
@@ -66,7 +77,7 @@ export const listSalesforceConnectionOauthApps = async (
let nextUrl: string | null = `/services/data/${SALESFORCE_API_VERSION}/apps/oauth/usage`;
for (let page = 0; page < SALESFORCE_OAUTH_APPS_PAGE_LIMIT && nextUrl; page += 1) {
- const url: string = `${instanceUrl}${nextUrl}`;
+ const url = resolveSalesforcePath(instanceUrl, nextUrl);
// eslint-disable-next-line no-await-in-loop
const response = await request.request<TSalesforceOauthUsageResponse>({
method: "GET",