Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
address ai code review
adilson13898deb291b
diff --git a/backend/src/services/app-connection/servicenow/servicenow-connection-fns.test.ts b/backend/src/services/app-connection/servicenow/servicenow-connection-fns.test.tsnew file mode 100644index 0000000000..e6801a9ff8--- /dev/null+++ b/backend/src/services/app-connection/servicenow/servicenow-connection-fns.test.ts@@ -0,0 +1,122 @@+import { AxiosError, AxiosResponse } from "axios";+import { beforeEach, describe, expect, test, vi } from "vitest";++import { BadRequestError } from "@app/lib/errors";+import { safeRequest } from "@app/lib/validator/safe-request";+import { AppConnection } from "@app/services/app-connection/app-connection-enums";++import { ServiceNowConnectionMethod } from "./servicenow-connection-enums";+import { validateServiceNowConnectionCredentials } from "./servicenow-connection-fns";+import { ServiceNowConnectionBasicAuthCredentialsSchema } from "./servicenow-connection-schemas";++vi.mock("@app/lib/logger", async () => ({+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },+ sanitizeUrlForLog: (+ await vi.importActual<typeof import("@app/lib/logger/sanitize-url")>("@app/lib/logger/sanitize-url")+ ).sanitizeUrlForLog+}));++vi.mock("@app/lib/validator/safe-request", () => ({ safeRequest: { get: vi.fn() } }));++const mockedGet = vi.mocked(safeRequest.get);++const INSTANCE_URL = "https://dev12345.service-now.com";++const config = {+ app: AppConnection.ServiceNow as const,+ method: ServiceNowConnectionMethod.BasicAuth as const,+ orgId: "org-1",+ credentials: { instanceUrl: INSTANCE_URL, username: "integration.user", password: "password" }+};++const upstreamError = (status: number, headers: Record<string, string> = {}) =>+ new AxiosError(`Request failed with status code ${status}`, "ERR_BAD_RESPONSE", undefined, undefined, {+ status,+ data: "",+ statusText: "",+ headers,+ config: {} as AxiosResponse["config"]+ });++const validationError = async () => {+ try {+ await validateServiceNowConnectionCredentials(config);+ } catch (error) {+ return error as BadRequestError;+ }+ throw new Error("expected validation to fail");+};++describe("validateServiceNowConnectionCredentials", () => {+ beforeEach(() => {+ mockedGet.mockReset();+ });++ test.each([401, 403])("reports a %i as a credentials problem", async (status) => {+ mockedGet.mockRejectedValueOnce(upstreamError(status));++ const error = await validationError();++ expect(error).toBeInstanceOf(BadRequestError);+ expect(error.message).toMatch(/verify the username and password/);+ });++ test("reports a redirect as an instance URL problem naming the redirect host", async () => {+ mockedGet.mockRejectedValueOnce(+ upstreamError(302, { location: "https://developer.servicenow.com/dev.do?token=abc#!/home" })+ );++ const error = await validationError();++ expect(error).toBeInstanceOf(BadRequestError);+ expect(error.message).toMatch(/the instance URL redirected to 'developer\.servicenow\.com'/);+ expect(error.message).not.toMatch(/username and password/);+ expect(error.message).not.toMatch(/token=abc|dev\.do/);+ });++ test("resolves a relative redirect against the instance URL", async () => {+ mockedGet.mockRejectedValueOnce(upstreamError(301, { location: "/login.do" }));++ expect((await validationError()).message).toMatch(/redirected to 'dev12345\.service-now\.com'/);+ });++ test("reports a redirect without a location header without naming a host", async () => {+ mockedGet.mockRejectedValueOnce(upstreamError(302));++ const error = await validationError();++ expect(error.message).toMatch(/the instance URL returned a redirect/);+ expect(error.message).not.toMatch(/username and password/);+ });+});++describe("ServiceNowConnectionBasicAuthCredentialsSchema", () => {+ const parse = (instanceUrl: string) =>+ ServiceNowConnectionBasicAuthCredentialsSchema.safeParse({ instanceUrl, username: "user", password: "password" });++ test("rejects an instance URL without a scheme instead of throwing", () => {+ const result = parse("dev12345.service-now.com");++ expect(result.success).toBe(false);+ expect(result.error?.issues.map((issue) => issue.message)).toContain("Invalid Instance URL");+ expect(result.error?.issues.map((issue) => issue.message)).not.toContain(+ "Instance URL must be the base URL of your ServiceNow instance, without a path or query string"+ );+ });++ test("rejects an instance URL with a path", () => {+ const result = parse(`${INSTANCE_URL}/now/nav/ui`);++ expect(result.success).toBe(false);+ expect(result.error?.issues.map((issue) => issue.message)).toContain(+ "Instance URL must be the base URL of your ServiceNow instance, without a path or query string"+ );+ });++ test("accepts the base URL and strips its trailing slash", () => {+ const result = parse(`${INSTANCE_URL}/`);++ expect(result.success).toBe(true);+ expect(result.data?.instanceUrl).toBe(INSTANCE_URL);+ });+});diff --git a/backend/src/services/app-connection/servicenow/servicenow-connection-fns.ts b/backend/src/services/app-connection/servicenow/servicenow-connection-fns.tsindex 9773454ac4..097e0816d8 100644--- a/backend/src/services/app-connection/servicenow/servicenow-connection-fns.ts+++ b/backend/src/services/app-connection/servicenow/servicenow-connection-fns.ts@@ -16,6 +16,17 @@ export const getServiceNowConnectionListItem = () => {};};+const getRedirectHost = (error: unknown, instanceUrl: string) => {+ const location = error instanceof AxiosError ? (error.response?.headers?.location as unknown) : undefined;+ if (typeof location !== "string") return undefined;++ try {+ return new URL(location, instanceUrl).host;+ } catch {+ return undefined;+ }+};+export const validateServiceNowConnectionCredentials = async (config: TServiceNowConnectionConfig) => {const { instanceUrl, username, password } = config.credentials;@@ -38,15 +49,23 @@ export const validateServiceNowConnectionCredentials = async (config: TServiceNo`Failed to validate ServiceNow connection [instanceUrl=${sanitizeUrlForLog(instanceUrl)}] [status=${status ?? "none"}]`);- // ServiceNow answers an unauthenticated request with a 302 to its login page, and safeRequest- // does not follow redirects, so a rejected credential arrives here as a 3xx rather than a 401.- if (status === 401 || status === 403 || (status && status >= 300 && status < 400)) {+ if (status === 401 || status === 403) {throw new BadRequestError({message:"Unable to connect to ServiceNow: verify the username and password of the integration user, and that the account is active."});}+ // safeRequest does not follow redirects, so a moved, mistyped, or hibernating instance arrives here as a 3xx.+ if (status && status >= 300 && status < 400) {+ const redirectHost = getRedirectHost(error, instanceUrl);+ throw new BadRequestError({+ message: `Unable to connect to ServiceNow: the instance URL ${+ redirectHost ? `redirected to '${redirectHost}'` : "returned a redirect"+ }. Verify that the instance URL is the base URL of your ServiceNow instance, and that the instance is active and not hibernating.`+ });+ }+throw new BadRequestError({message:"Unable to connect to ServiceNow: verify the instance URL is correct and that the instance is reachable from Infisical."diff --git a/backend/src/services/app-connection/servicenow/servicenow-connection-schemas.ts b/backend/src/services/app-connection/servicenow/servicenow-connection-schemas.tsindex 787abf17c9..916c49cdd1 100644--- a/backend/src/services/app-connection/servicenow/servicenow-connection-schemas.ts+++ b/backend/src/services/app-connection/servicenow/servicenow-connection-schemas.ts@@ -20,8 +20,14 @@ export const ServiceNowConnectionBasicAuthCredentialsSchema = z.object({.url("Invalid Instance URL").refine((value) => value.startsWith("https://"), "Instance URL must use HTTPS").refine((value) => {- const { pathname, search, hash } = new URL(value);- return (pathname === "" || pathname === "/") && !search && !hash;+ let url: URL;+ try {+ url = new URL(value);+ } catch {+ // zod runs refinements even after `.url()` fails, and `.url()` has already reported this value+ return true;+ }+ return (url.pathname === "" || url.pathname === "/") && !url.search && !url.hash;}, "Instance URL must be the base URL of your ServiceNow instance, without a path or query string").transform(removeTrailingSlash).describe(AppConnections.CREDENTIALS.SERVICENOW.instanceUrl),diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/ServiceNowConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/ServiceNowConnectionForm.tsxindex 90aea293a8..a13539ddbe 100644--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/ServiceNowConnectionForm.tsx+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/ServiceNowConnectionForm.tsx@@ -49,8 +49,14 @@ const formSchema = z.discriminatedUnion("method", [.max(512, "Instance URL cannot exceed 512 characters").refine((value) => value.startsWith("https://"), "Instance URL must use HTTPS").refine((value) => {- const { pathname, search, hash } = new URL(value);- return (pathname === "" || pathname === "/") && !search && !hash;+ let url: URL;+ try {+ url = new URL(value);+ } catch {+ // zod runs refinements even after `.url()` fails, and `.url()` has already reported this value+ return true;+ }+ return (url.pathname === "" || url.pathname === "/") && !url.search && !url.hash;}, "Enter the base URL of your instance, without a path"),username: z.string()