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
feat(platform): jira app connection
Andrey024ce30358e2
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex a4c40edf18..7425c41270 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -3138,6 +3138,16 @@ export const AppConnections = {"Whether or not to reject untrusted SSL certificates (true/false). Set to false for iLO interfaces using self-signed certificates.",sslCertificate: "The CA certificate (PEM format) used to verify the iLO interface's TLS certificate."},+ JIRA: {+ instanceUrl:+ "The URL of your Jira site (e.g., 'https://your-domain.atlassian.net' for Jira Cloud or 'https://jira.example.com' for Jira Data Center).",+ email: "The email address of the Atlassian account that owns the API token.",+ apiToken: "The Atlassian API token used to authenticate with Jira Cloud.",+ personalAccessToken: "The personal access token used to authenticate with Jira Data Center.",+ sslRejectUnauthorized:+ "Whether or not to reject untrusted SSL certificates (true/false). Set to false for Jira Data Center sites using self-signed certificates.",+ sslCertificate: "The CA certificate (PEM format) used to verify the Jira Data Center site's TLS certificate."+ },DBT: {apiToken: "The API token used to authenticate with DBT.",accountId: "The account ID of your DBT account.",diff --git a/backend/src/server/routes/v1/app-connection-routers/app-connection-router.ts b/backend/src/server/routes/v1/app-connection-routers/app-connection-router.tsindex e4245f3b15..f9525c2759 100644--- a/backend/src/server/routes/v1/app-connection-routers/app-connection-router.ts+++ b/backend/src/server/routes/v1/app-connection-routers/app-connection-router.ts@@ -146,6 +146,7 @@ import {HumanitecConnectionListItemSchema,SanitizedHumanitecConnectionSchema} from "@app/services/app-connection/humanitec";+import { JiraConnectionListItemSchema, SanitizedJiraConnectionSchema } from "@app/services/app-connection/jira";import { KeeperConnectionListItemSchema, SanitizedKeeperConnectionSchema } from "@app/services/app-connection/keeper";import {KempLoadMasterConnectionListItemSchema,@@ -376,7 +377,8 @@ const SanitizedAppConnectionSchema = z.union([...SanitizedDaytonaConnectionSchema.options,...SanitizedStripeConnectionSchema.options,...SanitizedKeeperConnectionSchema.options,- ...SanitizedHpeIloConnectionSchema.options+ ...SanitizedHpeIloConnectionSchema.options,+ ...SanitizedJiraConnectionSchema.options]);const AppConnectionOptionsSchema = z.discriminatedUnion("app", [@@ -470,7 +472,8 @@ const AppConnectionOptionsSchema = z.discriminatedUnion("app", [DaytonaConnectionListItemSchema,StripeConnectionListItemSchema,KeeperConnectionListItemSchema,- HpeIloConnectionListItemSchema+ HpeIloConnectionListItemSchema,+ JiraConnectionListItemSchema]);export const registerAppConnectionRouter = async (server: FastifyZodProvider) => {diff --git a/backend/src/server/routes/v1/app-connection-routers/index.ts b/backend/src/server/routes/v1/app-connection-routers/index.tsindex 769fa7b752..35010568be 100644--- a/backend/src/server/routes/v1/app-connection-routers/index.ts+++ b/backend/src/server/routes/v1/app-connection-routers/index.ts@@ -45,6 +45,7 @@ import { registerHCVaultConnectionRouter } from "./hc-vault-connection-router";import { registerHerokuConnectionRouter } from "./heroku-connection-router";import { registerHpeIloConnectionRouter } from "./hpe-ilo-connection-router";import { registerHumanitecConnectionRouter } from "./humanitec-connection-router";+import { registerJiraConnectionRouter } from "./jira-connection-router";import { registerKeeperConnectionRouter } from "./keeper-connection-router";import { registerKempLoadMasterConnectionRouter } from "./kemp-loadmaster-connection-router";import { registerLaravelForgeConnectionRouter } from "./laravel-forge-connection-router";@@ -186,5 +187,6 @@ export const APP_CONNECTION_REGISTER_ROUTER_MAP: Record<AppConnection, (server:[AppConnection.Daytona]: registerDaytonaConnectionRouter,[AppConnection.Stripe]: registerStripeConnectionRouter,[AppConnection.Keeper]: registerKeeperConnectionRouter,- [AppConnection.HpeIloRedFish]: registerHpeIloConnectionRouter+ [AppConnection.HpeIloRedFish]: registerHpeIloConnectionRouter,+ [AppConnection.Jira]: registerJiraConnectionRouter};diff --git a/backend/src/server/routes/v1/app-connection-routers/jira-connection-router.ts b/backend/src/server/routes/v1/app-connection-routers/jira-connection-router.tsnew file mode 100644index 0000000000..c97ea547c7--- /dev/null+++ b/backend/src/server/routes/v1/app-connection-routers/jira-connection-router.ts@@ -0,0 +1,18 @@+import { AppConnection } from "@app/services/app-connection/app-connection-enums";+import {+ CreateJiraConnectionSchema,+ SanitizedJiraConnectionSchema,+ UpdateJiraConnectionSchema+} from "@app/services/app-connection/jira";++import { registerAppConnectionEndpoints } from "./app-connection-endpoints";++export const registerJiraConnectionRouter = async (server: FastifyZodProvider) => {+ registerAppConnectionEndpoints({+ app: AppConnection.Jira,+ server,+ sanitizedResponseSchema: SanitizedJiraConnectionSchema,+ createSchema: CreateJiraConnectionSchema,+ updateSchema: UpdateJiraConnectionSchema+ });+};diff --git a/backend/src/services/app-connection/app-connection-enums.ts b/backend/src/services/app-connection/app-connection-enums.tsindex 5fd008ec49..f4a47d44da 100644--- a/backend/src/services/app-connection/app-connection-enums.ts+++ b/backend/src/services/app-connection/app-connection-enums.ts@@ -89,7 +89,8 @@ export enum AppConnection {Daytona = "daytona",Stripe = "stripe",Keeper = "keeper",- HpeIloRedFish = "hpe-ilo"+ HpeIloRedFish = "hpe-ilo",+ Jira = "jira"}export enum AWSRegion {diff --git a/backend/src/services/app-connection/app-connection-fns.ts b/backend/src/services/app-connection/app-connection-fns.tsindex cf66449ad0..717e87bbb1 100644--- a/backend/src/services/app-connection/app-connection-fns.ts+++ b/backend/src/services/app-connection/app-connection-fns.ts@@ -189,6 +189,7 @@ import {HumanitecConnectionMethod,validateHumanitecConnectionCredentials} from "./humanitec";+import { getJiraConnectionListItem, JiraConnectionMethod, validateJiraConnectionCredentials } from "./jira";import { getKeeperConnectionListItem, KeeperConnectionMethod, validateKeeperConnectionCredentials } from "./keeper";import {getKempLoadMasterConnectionListItem,@@ -490,7 +491,8 @@ export const listAppConnectionOptions = (projectType?: ProjectType) => {getDaytonaConnectionListItem(),getStripeConnectionListItem(),getKeeperConnectionListItem(),- getHpeIloConnectionListItem()+ getHpeIloConnectionListItem(),+ getJiraConnectionListItem()].filter((option) => isAppConnectionAllowedInProject(option.app, projectType)).sort((a, b) => a.name.localeCompare(b.name));@@ -732,7 +734,8 @@ export const validateAppConnectionCredentials = async ([AppConnection.Daytona]: validateDaytonaConnectionCredentials as TAppConnectionCredentialsValidator,[AppConnection.Stripe]: validateStripeConnectionCredentials as TAppConnectionCredentialsValidator,[AppConnection.Keeper]: validateKeeperConnectionCredentials as TAppConnectionCredentialsValidator,- [AppConnection.HpeIloRedFish]: validateHpeIloConnectionCredentials as TAppConnectionCredentialsValidator+ [AppConnection.HpeIloRedFish]: validateHpeIloConnectionCredentials as TAppConnectionCredentialsValidator,+ [AppConnection.Jira]: validateJiraConnectionCredentials as TAppConnectionCredentialsValidator};return VALIDATE_APP_CONNECTION_CREDENTIALS_MAP[appConnection.app](appConnection, gatewayV2Service);@@ -788,7 +791,10 @@ export const getAppConnectionMethodName = (method: TAppConnection["method"]) =>case RundeckConnectionMethod.ApiToken:case PortainerConnectionMethod.ApiToken:case DatadogConnectionMethod.Token:+ case JiraConnectionMethod.ApiToken:return "API Token";+ case JiraConnectionMethod.PersonalAccessToken:+ return "Personal Access Token";case DNSMadeEasyConnectionMethod.APIKeySecret:case SpaceliftConnectionMethod.ApiKeySecret:return "API Key & Secret";@@ -1018,7 +1024,8 @@ export const TRANSITION_CONNECTION_CREDENTIALS_TO_PLATFORM: Record<[AppConnection.Daytona]: platformManagedCredentialsNotSupported,[AppConnection.Stripe]: platformManagedCredentialsNotSupported,[AppConnection.Keeper]: platformManagedCredentialsNotSupported,- [AppConnection.HpeIloRedFish]: platformManagedCredentialsNotSupported+ [AppConnection.HpeIloRedFish]: platformManagedCredentialsNotSupported,+ [AppConnection.Jira]: platformManagedCredentialsNotSupported};export const enterpriseAppCheck = async (diff --git a/backend/src/services/app-connection/app-connection-maps.ts b/backend/src/services/app-connection/app-connection-maps.tsindex b0cb3abc50..b4ec5795ba 100644--- a/backend/src/services/app-connection/app-connection-maps.ts+++ b/backend/src/services/app-connection/app-connection-maps.ts@@ -91,7 +91,8 @@ export const APP_CONNECTION_NAME_MAP: Record<AppConnection, string> = {[AppConnection.MicrosoftIntune]: "Microsoft Intune",[AppConnection.Stripe]: "Stripe",[AppConnection.Keeper]: "Keeper",- [AppConnection.HpeIloRedFish]: "HPE iLO"+ [AppConnection.HpeIloRedFish]: "HPE iLO",+ [AppConnection.Jira]: "Jira"};export const APP_CONNECTION_PLAN_MAP: Record<AppConnection, AppConnectionPlanType> = {@@ -185,5 +186,6 @@ export const APP_CONNECTION_PLAN_MAP: Record<AppConnection, AppConnectionPlanTyp[AppConnection.MicrosoftIntune]: AppConnectionPlanType.Enterprise,[AppConnection.Stripe]: AppConnectionPlanType.Regular,[AppConnection.Keeper]: AppConnectionPlanType.Regular,- [AppConnection.HpeIloRedFish]: AppConnectionPlanType.Regular+ [AppConnection.HpeIloRedFish]: AppConnectionPlanType.Regular,+ [AppConnection.Jira]: AppConnectionPlanType.Regular};diff --git a/backend/src/services/app-connection/app-connection-service.ts b/backend/src/services/app-connection/app-connection-service.tsindex 9287e8dfdf..8d7963b0ad 100644--- a/backend/src/services/app-connection/app-connection-service.ts+++ b/backend/src/services/app-connection/app-connection-service.ts@@ -137,6 +137,7 @@ import { herokuConnectionService } from "./heroku/heroku-connection-service";import { ValidateHpeIloConnectionCredentialsSchema } from "./hpe-ilo";import { ValidateHumanitecConnectionCredentialsSchema } from "./humanitec";import { humanitecConnectionService } from "./humanitec/humanitec-connection-service";+import { ValidateJiraConnectionCredentialsSchema } from "./jira";import { ValidateKeeperConnectionCredentialsSchema } from "./keeper";import { keeperConnectionService } from "./keeper/keeper-connection-service";import { ValidateKempLoadMasterConnectionCredentialsSchema } from "./kemp-loadmaster";@@ -335,7 +336,8 @@ const VALIDATE_APP_CONNECTION_CREDENTIALS_MAP: Record<AppConnection, TValidateAp[AppConnection.Daytona]: ValidateDaytonaConnectionCredentialsSchema,[AppConnection.Stripe]: ValidateStripeConnectionCredentialsSchema,[AppConnection.Keeper]: ValidateKeeperConnectionCredentialsSchema,- [AppConnection.HpeIloRedFish]: ValidateHpeIloConnectionCredentialsSchema+ [AppConnection.HpeIloRedFish]: ValidateHpeIloConnectionCredentialsSchema,+ [AppConnection.Jira]: ValidateJiraConnectionCredentialsSchema};export const appConnectionServiceFactory = ({diff --git a/backend/src/services/app-connection/app-connection-types.ts b/backend/src/services/app-connection/app-connection-types.tsindex 082181270a..580a081e51 100644--- a/backend/src/services/app-connection/app-connection-types.ts+++ b/backend/src/services/app-connection/app-connection-types.ts@@ -273,6 +273,12 @@ import {THumanitecConnectionInput,TValidateHumanitecConnectionCredentialsSchema} from "./humanitec";+import {+ TJiraConnection,+ TJiraConnectionConfig,+ TJiraConnectionInput,+ TValidateJiraConnectionCredentialsSchema+} from "./jira";import {TKeeperConnection,TKeeperConnectionConfig,@@ -633,6 +639,7 @@ export type TAppConnection = { id: string; configuration?: TAppConnectionConfigu| TStripeConnection| TKeeperConnection| THpeIloConnection+ | TJiraConnection);export type TAppConnectionRaw = NonNullable<Awaited<ReturnType<TAppConnectionDALFactory["findById"]>>>;@@ -735,6 +742,7 @@ export type TAppConnectionInput = { id: string } & (| TStripeConnectionInput| TKeeperConnectionInput| THpeIloConnectionInput+ | TJiraConnectionInput);export type TSqlConnectionInput =@@ -870,7 +878,8 @@ export type TAppConnectionConfig =| TDaytonaConnectionConfig| TStripeConnectionConfig| TKeeperConnectionConfig- | THpeIloConnectionConfig;+ | THpeIloConnectionConfig+ | TJiraConnectionConfig;export type TValidateAppConnectionCredentialsSchema =| TValidateAwsConnectionCredentialsSchema@@ -963,7 +972,8 @@ export type TValidateAppConnectionCredentialsSchema =| TValidateDaytonaConnectionCredentialsSchema| TValidateStripeConnectionCredentialsSchema| TValidateKeeperConnectionCredentialsSchema- | TValidateHpeIloConnectionCredentialsSchema;+ | TValidateHpeIloConnectionCredentialsSchema+ | TValidateJiraConnectionCredentialsSchema;export type TListAwsConnectionKmsKeys = {connectionId: string;diff --git a/backend/src/services/app-connection/jira/index.ts b/backend/src/services/app-connection/jira/index.tsnew file mode 100644index 0000000000..e2eb4a51cb--- /dev/null+++ b/backend/src/services/app-connection/jira/index.ts@@ -0,0 +1,18 @@+export { JiraConnectionMethod } from "./jira-connection-enums";+export * from "./jira-connection-fns";+export {+ CreateJiraConnectionSchema,+ JiraConnectionListItemSchema,+ SanitizedJiraConnectionSchema,+ UpdateJiraConnectionSchema,+ ValidateJiraConnectionCredentialsSchema+} from "./jira-connection-schemas";+export type {+ TJiraApproval,+ TJiraConnection,+ TJiraConnectionConfig,+ TJiraConnectionInput,+ TJiraIssue,+ TJiraUser,+ TValidateJiraConnectionCredentialsSchema+} from "./jira-connection-types";diff --git a/backend/src/services/app-connection/jira/jira-connection-enums.ts b/backend/src/services/app-connection/jira/jira-connection-enums.tsnew file mode 100644index 0000000000..fe145dfa80--- /dev/null+++ b/backend/src/services/app-connection/jira/jira-connection-enums.ts@@ -0,0 +1,6 @@+export enum JiraConnectionMethod {+ // Jira Cloud+ ApiToken = "api-token",+ // Jira Data Center+ PersonalAccessToken = "personal-access-token"+}diff --git a/backend/src/services/app-connection/jira/jira-connection-fns.ts b/backend/src/services/app-connection/jira/jira-connection-fns.tsnew file mode 100644index 0000000000..cc89288dd4--- /dev/null+++ b/backend/src/services/app-connection/jira/jira-connection-fns.ts@@ -0,0 +1,460 @@+import { AxiosError, AxiosRequestConfig, isAxiosError } from "axios";++import { verifyHostInputValidity } from "@app/ee/services/dynamic-secret/dynamic-secret-fns";+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";+import { request } from "@app/lib/config/request";+import { BadRequestError, NotFoundError } from "@app/lib/errors";+import { removeTrailingSlash } from "@app/lib/fn";+import { getMissingGatewayMessage } from "@app/lib/gateway-v2/gateway-errors";+import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";+import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";+import { logger, sanitizeUrlForLog } from "@app/lib/logger";+import { DiscriminativePick } from "@app/lib/types";+import { getSharedHttpsAgent, safeRequest } from "@app/lib/validator/safe-request";+import { AppConnection } from "@app/services/app-connection/app-connection-enums";++import { JiraConnectionMethod } from "./jira-connection-enums";+import { TJiraApproval, TJiraConnectionConfig, TJiraIssue, TJiraNamedOption, TJiraUser } from "./jira-connection-types";++export const JIRA_REQUEST_TIMEOUT_MS = 15_000;+const JIRA_MAX_RESPONSE_BYTES = 10 * 1024 * 1024;+const JIRA_PAGE_SIZE = 50;+const JIRA_MAX_PAGES = 10;+const JIRA_MAX_ERROR_DETAIL_LENGTH = 300;++export type TJiraGatewayDeps = {+ gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;+};++export type TJiraRequestConfig = DiscriminativePick<+ TJiraConnectionConfig,+ "method" | "credentials" | "gatewayId" | "gatewayPoolId"+>;++type TJiraRequest = {+ path: string;+ params?: Record<string, string | number | undefined>;+};++export const getJiraConnectionListItem = () => ({+ name: "Jira" as const,+ app: AppConnection.Jira as const,+ methods: Object.values(JiraConnectionMethod) as [+ JiraConnectionMethod.ApiToken,+ JiraConnectionMethod.PersonalAccessToken+ ]+});++export const isJiraCloud = (config: Pick<TJiraConnectionConfig, "method">) =>+ config.method === JiraConnectionMethod.ApiToken;++// Jira Data Center only serves v2 of the REST API+const getJiraRestApiPath = (config: Pick<TJiraConnectionConfig, "method">) =>+ isJiraCloud(config) ? "/rest/api/3" : "/rest/api/2";++const getJiraAuthorizationHeader = (config: TJiraRequestConfig) => {+ if (config.method === JiraConnectionMethod.ApiToken) {+ const { email, apiToken } = config.credentials;+ return `Basic ${Buffer.from(`${email}:${apiToken}`).toString("base64")}`;+ }++ return `Bearer ${config.credentials.personalAccessToken}`;+};++const getJiraTlsOptions = (config: TJiraRequestConfig) => {+ if (config.method === JiraConnectionMethod.PersonalAccessToken) {+ return {+ ca: config.credentials.sslCertificate,+ rejectUnauthorized: config.credentials.sslRejectUnauthorized ?? true+ };+ }++ return { ca: undefined, rejectUnauthorized: true };+};++export const jiraRequest = async <T>(+ config: TJiraRequestConfig,+ { path, params }: TJiraRequest,+ { gatewayV2Service, gatewayPoolService }: TJiraGatewayDeps = {}+): Promise<T> => {+ const { gatewayId: directGatewayId, gatewayPoolId } = config;++ if (gatewayPoolId && !gatewayPoolService) {+ throw new BadRequestError({+ message: "This Jira connection uses a gateway pool, which is not supported on this operation"+ });+ }++ const gatewayId =+ gatewayPoolId && gatewayPoolService+ ? await gatewayPoolService.resolveEffectiveGatewayId({ gatewayId: directGatewayId, gatewayPoolId })+ : directGatewayId;++ // a pinned gateway must never fall through to the direct request below+ if (gatewayId && !gatewayV2Service) {+ throw new NotFoundError({ message: getMissingGatewayMessage(gatewayId) });+ }++ const url = new URL(`${removeTrailingSlash(config.credentials.instanceUrl)}${path}`);+ const headers = { Authorization: getJiraAuthorizationHeader(config), Accept: "application/json" };+ const { ca, rejectUnauthorized } = getJiraTlsOptions(config);++ const baseRequestConfig: AxiosRequestConfig = {+ method: "GET",+ params,+ timeout: JIRA_REQUEST_TIMEOUT_MS,+ maxContentLength: JIRA_MAX_RESPONSE_BYTES+ };++ if (!gatewayId || !gatewayV2Service) {+ const { data } = await safeRequest.request<T>({+ ...baseRequestConfig,+ url: url.toString(),+ headers,+ ca,+ rejectUnauthorized+ });++ return data;+ }++ const [targetHost] = await verifyHostInputValidity({ host: url.hostname, isGateway: true, isDynamicSecret: false });+ const isHttps = url.protocol === "https:";+ const targetPort = url.port ? Number(url.port) : (isHttps && 443) || 80;++ const platformConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({+ gatewayId,+ targetHost,+ targetPort+ });++ if (!platformConnectionDetails) {+ throw new NotFoundError({ message: getMissingGatewayMessage(gatewayId) });+ }++ const outcome = await withGatewayV2Proxy<{ data: T } | { error: AxiosError }>(+ async (proxyPort) => {+ const proxiedUrl = new URL(url.toString());+ proxiedUrl.host = `localhost:${proxyPort}`;++ try {+ const { data } = await request.request<T>({+ ...baseRequestConfig,+ url: proxiedUrl.toString(),+ headers: { ...headers, Host: url.host },+ maxRedirects: 0,+ ...(isHttps && {+ httpsAgent: getSharedHttpsAgent({ servername: targetHost, ca, rejectUnauthorized })+ })+ });+ return { data };+ } catch (error) {+ // The proxy reduces a thrown error to its message, so Jira's own responses are passed out whole+ if (isAxiosError(error) && error.response) return { error };+ throw error;+ }+ },+ {+ protocol: GatewayProxyProtocol.Tcp,+ ...platformConnectionDetails+ }+ );++ if ("error" in outcome) throw outcome.error;+ return outcome.data;+};++export const isJiraNotFoundError = (error: unknown) => isAxiosError(error) && error.response?.status === 404;++export const getJiraErrorMessage = (error: unknown) => {+ if (error instanceof BadRequestError || error instanceof NotFoundError) return error.message;++ if (isAxiosError(error)) {+ if (error.code === "ECONNABORTED" || error.code === "ETIMEDOUT") {+ return `Jira did not respond within ${JIRA_REQUEST_TIMEOUT_MS / 1000} seconds`;+ }++ const status = error.response?.status;+ if (status === 401) return "Jira rejected the connection's credentials";+ if (status === 403) return "The connection's Jira account doesn't have permission for this";+ if (status && status >= 300 && status < 400) {+ return "Jira redirected the request, so the instance URL is likely wrong. Use your Jira site's base URL";+ }++ const body = error.response?.data as { errorMessages?: unknown[]; errors?: Record<string, unknown> } | undefined;+ const detail = [...(body?.errorMessages ?? []), ...Object.values(body?.errors ?? {})].find(+ (message): message is string => typeof message === "string" && Boolean(message.trim())+ );+ if (detail) return detail.slice(0, JIRA_MAX_ERROR_DETAIL_LENGTH);++ if (status) return `Jira responded with status ${status}`;+ if (error.code) return `Couldn't reach Jira (${error.code})`;+ }++ return "Couldn't reach Jira";+};++const logJiraError = (error: unknown, action: string) => {+ logger.error(+ {+ status: isAxiosError(error) ? error.response?.status : undefined,+ code: isAxiosError(error) ? error.code : undefined,+ url: isAxiosError(error) && error.config?.url ? sanitizeUrlForLog(error.config.url) : undefined,+ message: error instanceof Error ? error.message : String(error)+ },+ `Jira request failed [action=${action}]`+ );+};++export const validateJiraConnectionCredentials = async (+ config: TJiraConnectionConfig,+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">+) => {+ let myself: TJiraUser | undefined;++ try {+ myself = await jiraRequest<TJiraUser>(+ config,+ { path: `${getJiraRestApiPath(config)}/myself` },+ { gatewayV2Service }+ );+ } catch (error) {+ if (error instanceof NotFoundError) throw error;++ logJiraError(error, "validate-credentials");++ // A failure past the gateway arrives as a bare message, such as "socket hang up"+ if (error instanceof BadRequestError) {+ throw new BadRequestError({+ message: `Unable to validate connection: ${config.gatewayId ? "couldn't reach Jira through the gateway: " : ""}${error.message}`+ });+ }++ if (isJiraNotFoundError(error)) {+ throw new BadRequestError({+ message: `Unable to validate connection: Jira returned 404. Verify the instance URL points to your Jira site, and use ${+ isJiraCloud(config) ? "a personal access token for Jira Data Center" : "an API token for Jira Cloud"+ } if that is what you are connecting to.`+ });+ }++ if (isAxiosError(error) && error.response?.status === 401) {+ throw new BadRequestError({+ message: isJiraCloud(config)+ ? "Unable to validate connection: Jira rejected the email and API token. Check both, and use a personal access token instead if this is Jira Data Center."+ : "Unable to validate connection: Jira rejected the personal access token. Check that it hasn't expired or been revoked."+ });+ }++ throw new BadRequestError({ message: `Unable to validate connection: ${getJiraErrorMessage(error)}` });+ }++ if (!myself || typeof myself !== "object" || !(myself.accountId || myself.key || myself.name)) {+ throw new BadRequestError({+ message:+ "Unable to validate connection: the instance URL did not return a Jira user. Verify it points to your Jira site."+ });+ }++ return config.credentials;+};++export const getJiraIssue = async (+ config: TJiraRequestConfig,+ issueKey: string,+ fields: string[],+ deps: TJiraGatewayDeps+) =>+ jiraRequest<TJiraIssue>(+ config,+ {+ path: `${getJiraRestApiPath(config)}/issue/${encodeURIComponent(issueKey)}`,+ params: { fields: fields.join(",") }+ },+ deps+ );++const matchesSearch = (search: string | undefined, ...values: string[]) => {+ if (!search) return true;+ const needle = search.toLowerCase();+ return values.some((value) => value.toLowerCase().includes(needle));+};++const dedupeByName = (options: TJiraNamedOption[]) => {+ const byName = new Map<string, TJiraNamedOption>();+ options.forEach((option) => {+ const key = option.name.toLowerCase();+ if (!byName.has(key)) byName.set(key, option);+ });+ return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));+};++export const listJiraProjects = async (+ config: TJiraRequestConfig,+ { search }: { search?: string },+ deps: TJiraGatewayDeps+): Promise<{ key: string; name: string }[]> => {+ if (!isJiraCloud(config)) {+ // Data Center returns every visible project in one response+ const projects = await jiraRequest<{ key: string; name: string }[]>(+ config,+ { path: `${getJiraRestApiPath(config)}/project` },+ deps+ );+ return (Array.isArray(projects) ? projects : [])+ .filter((project) => matchesSearch(search, project.key, project.name))+ .map(({ key, name }) => ({ key, name }));+ }++ const projects: { key: string; name: string }[] = [];+ let startAt = 0;+ let isLast = false;+ let page = 0;++ while (!isLast && page < JIRA_MAX_PAGES) {+ // eslint-disable-next-line no-await-in-loop+ const data = await jiraRequest<{ values?: { key: string; name: string }[]; isLast?: boolean }>(+ config,+ {+ path: `${getJiraRestApiPath(config)}/project/search`,+ params: { query: search || undefined, startAt, maxResults: JIRA_PAGE_SIZE, orderBy: "key" }+ },+ deps+ );+ const values = data?.values ?? [];+ projects.push(...values.map(({ key, name }) => ({ key, name })));+ isLast = data?.isLast ?? values.length < JIRA_PAGE_SIZE;+ startAt += values.length;+ page += 1;+ }++ if (!isLast) {+ logger.warn(`listJiraProjects: stopped after ${JIRA_MAX_PAGES} pages [projects=${projects.length}]`);+ }++ return projects;+};++export const listJiraStatuses = async (+ config: TJiraRequestConfig,+ { projectKeys }: { projectKeys: string[] },+ deps: TJiraGatewayDeps+): Promise<TJiraNamedOption[]> => {+ const apiPath = getJiraRestApiPath(config);++ if (!projectKeys.length) {+ const statuses = await jiraRequest<TJiraNamedOption[]>(config, { path: `${apiPath}/status` }, deps);+ return dedupeByName(Array.isArray(statuses) ? statuses : []);+ }++ const perProject = await Promise.all(+ projectKeys.map((projectKey) =>+ jiraRequest<{ statuses?: TJiraNamedOption[] }[]>(+ config,+ { path: `${apiPath}/project/${encodeURIComponent(projectKey)}/statuses` },+ deps+ )+ )+ );++ return dedupeByName(+ perProject.flatMap((issueTypes) => (Array.isArray(issueTypes) ? issueTypes : [])).flatMap((t) => t.statuses ?? [])+ );+};++export const listJiraIssueTypes = async (+ config: TJiraRequestConfig,+ { projectKeys }: { projectKeys: string[] },+ deps: TJiraGatewayDeps+): Promise<TJiraNamedOption[]> => {+ const apiPath = getJiraRestApiPath(config);++ if (!projectKeys.length) {+ const issueTypes = await jiraRequest<TJiraNamedOption[]>(config, { path: `${apiPath}/issuetype` }, deps);+ return dedupeByName(Array.isArray(issueTypes) ? issueTypes : []);+ }++ const projects = await Promise.all(+ projectKeys.map((projectKey) =>+ jiraRequest<{ issueTypes?: TJiraNamedOption[] }>(+ config,+ { path: `${apiPath}/project/${encodeURIComponent(projectKey)}` },+ deps+ )+ )+ );++ return dedupeByName(projects.flatMap((project) => project?.issueTypes ?? []));+};++export const searchJiraLabels = async (+ config: TJiraRequestConfig,+ { search }: { search?: string },+ deps: TJiraGatewayDeps+): Promise<string[]> => {+ const data = await jiraRequest<{ results?: { value?: string }[] }>(+ config,+ {+ path: `${getJiraRestApiPath(config)}/jql/autocompletedata/suggestions`,+ params: { fieldName: "labels", fieldValue: search ?? "" }+ },+ deps+ );++ return [...new Set((data?.results ?? []).map((result) => result.value).filter((value): value is string => !!value))];+};++export const findJiraUsersByEmail = async (+ config: TJiraRequestConfig,+ email: string,+ deps: TJiraGatewayDeps+): Promise<TJiraUser[]> => {+ const users = await jiraRequest<TJiraUser[]>(+ config,+ {+ path: `${getJiraRestApiPath(config)}/user/search`,+ // Cloud matches query against display names and emails; Data Center matches username against both+ params: isJiraCloud(config) ? { query: email, maxResults: 20 } : { username: email, maxResults: 20 }+ },+ deps+ );++ return Array.isArray(users) ? users : [];+};++// Jira Service Management approvals, which only an approver can decide, unlike an issue's status+export const listJiraIssueApprovals = async (+ config: TJiraRequestConfig,+ issueKey: string,+ deps: TJiraGatewayDeps+): Promise<TJiraApproval[]> => {+ const approvals: TJiraApproval[] = [];+ let start = 0;+ let isLastPage = false;+ let page = 0;++ while (!isLastPage && page < JIRA_MAX_PAGES) {+ // eslint-disable-next-line no-await-in-loop+ const data = await jiraRequest<{ values?: TJiraApproval[]; isLastPage?: boolean }>(+ config,+ {+ path: `/rest/servicedeskapi/request/${encodeURIComponent(issueKey)}/approval`,+ params: { start, limit: JIRA_PAGE_SIZE }+ },+ deps+ );+ const values = data?.values ?? [];+ approvals.push(...values);+ isLastPage = data?.isLastPage ?? values.length < JIRA_PAGE_SIZE;+ start += values.length;+ page += 1;+ }++ if (!isLastPage) {+ logger.warn(`listJiraIssueApprovals: stopped after ${JIRA_MAX_PAGES} pages [issueKey=${issueKey}]`);+ }++ return approvals;+};diff --git a/backend/src/services/app-connection/jira/jira-connection-schemas.ts b/backend/src/services/app-connection/jira/jira-connection-schemas.tsnew file mode 100644index 0000000000..d72310e777--- /dev/null+++ b/backend/src/services/app-connection/jira/jira-connection-schemas.ts@@ -0,0 +1,134 @@+import z from "zod";++import { AppConnections } from "@app/lib/api-docs";+import { AppConnection } from "@app/services/app-connection/app-connection-enums";+import {+ BaseAppConnectionSchema,+ GenericCreateAppConnectionFieldsSchema,+ GenericUpdateAppConnectionFieldsSchema+} from "@app/services/app-connection/app-connection-schemas";++import { APP_CONNECTION_NAME_MAP } from "../app-connection-maps";+import { JiraConnectionMethod } from "./jira-connection-enums";++const isValidInstanceUrl = (value: string) => {+ try {+ const url = new URL(value);+ return ["http:", "https:"].includes(url.protocol) && !url.username && !url.password && !url.search && !url.hash;+ } catch {+ return false;+ }+};++const InstanceUrlSchema = z+ .string()+ .trim()+ .min(1, "Instance URL required")+ .max(512, "Instance URL cannot exceed 512 characters")+ .refine(isValidInstanceUrl, "Instance URL must be an http or https URL without credentials, a query, or a fragment")+ .describe(AppConnections.CREDENTIALS.JIRA.instanceUrl);++export const JiraConnectionApiTokenCredentialsSchema = z.object({+ instanceUrl: InstanceUrlSchema,+ email: z+ .string()+ .trim()+ .min(1, "Email required")+ .max(320, "Email cannot exceed 320 characters")+ .email("Email must be a valid email address")+ .describe(AppConnections.CREDENTIALS.JIRA.email),+ apiToken: z+ .string()+ .trim()+ .min(1, "API token required")+ .max(1024, "API token cannot exceed 1024 characters")+ .describe(AppConnections.CREDENTIALS.JIRA.apiToken)+});++export const JiraConnectionPersonalAccessTokenCredentialsSchema = z.object({+ instanceUrl: InstanceUrlSchema,+ personalAccessToken: z+ .string()+ .trim()+ .min(1, "Personal access token required")+ .max(1024, "Personal access token cannot exceed 1024 characters")+ .describe(AppConnections.CREDENTIALS.JIRA.personalAccessToken),+ sslRejectUnauthorized: z.boolean().optional().describe(AppConnections.CREDENTIALS.JIRA.sslRejectUnauthorized),+ sslCertificate: z+ .string()+ .trim()+ .max(16384, "SSL certificate cannot exceed 16384 characters")+ .transform((value) => value || undefined)+ .optional()+ .describe(AppConnections.CREDENTIALS.JIRA.sslCertificate)+});++const BaseJiraConnectionSchema = BaseAppConnectionSchema.extend({ app: z.literal(AppConnection.Jira) });++export const JiraConnectionSchema = z.intersection(+ BaseJiraConnectionSchema,+ z.discriminatedUnion("method", [+ z.object({+ method: z.literal(JiraConnectionMethod.ApiToken),+ credentials: JiraConnectionApiTokenCredentialsSchema+ }),+ z.object({+ method: z.literal(JiraConnectionMethod.PersonalAccessToken),+ credentials: JiraConnectionPersonalAccessTokenCredentialsSchema+ })+ ])+);++export const SanitizedJiraConnectionSchema = z.discriminatedUnion("method", [+ BaseJiraConnectionSchema.extend({+ method: z.literal(JiraConnectionMethod.ApiToken),+ credentials: JiraConnectionApiTokenCredentialsSchema.pick({+ instanceUrl: true,+ email: true+ })+ }).describe(JSON.stringify({ title: `${APP_CONNECTION_NAME_MAP[AppConnection.Jira]} (API Token)` })),+ BaseJiraConnectionSchema.extend({+ method: z.literal(JiraConnectionMethod.PersonalAccessToken),+ credentials: JiraConnectionPersonalAccessTokenCredentialsSchema.pick({+ instanceUrl: true,+ sslRejectUnauthorized: true,+ sslCertificate: true+ })+ }).describe(JSON.stringify({ title: `${APP_CONNECTION_NAME_MAP[AppConnection.Jira]} (Personal Access Token)` }))+]);++export const ValidateJiraConnectionCredentialsSchema = z.discriminatedUnion("method", [+ z.object({+ method: z.literal(JiraConnectionMethod.ApiToken).describe(AppConnections.CREATE(AppConnection.Jira).method),+ credentials: JiraConnectionApiTokenCredentialsSchema.describe(AppConnections.CREATE(AppConnection.Jira).credentials)+ }),+ z.object({+ method: z+ .literal(JiraConnectionMethod.PersonalAccessToken)+ .describe(AppConnections.CREATE(AppConnection.Jira).method),+ credentials: JiraConnectionPersonalAccessTokenCredentialsSchema.describe(+ AppConnections.CREATE(AppConnection.Jira).credentials+ )+ })+]);++export const CreateJiraConnectionSchema = ValidateJiraConnectionCredentialsSchema.and(+ GenericCreateAppConnectionFieldsSchema(AppConnection.Jira, { supportsGateways: true })+);++export const UpdateJiraConnectionSchema = z+ .object({+ credentials: z+ .union([JiraConnectionApiTokenCredentialsSchema, JiraConnectionPersonalAccessTokenCredentialsSchema])+ .optional()+ .describe(AppConnections.UPDATE(AppConnection.Jira).credentials)+ })+ .and(GenericUpdateAppConnectionFieldsSchema(AppConnection.Jira, { supportsGateways: true }));++export const JiraConnectionListItemSchema = z+ .object({+ name: z.literal("Jira"),+ app: z.literal(AppConnection.Jira),+ methods: z.nativeEnum(JiraConnectionMethod).array()+ })+ .describe(JSON.stringify({ title: APP_CONNECTION_NAME_MAP[AppConnection.Jira] }));diff --git a/backend/src/services/app-connection/jira/jira-connection-types.ts b/backend/src/services/app-connection/jira/jira-connection-types.tsnew file mode 100644index 0000000000..72678bf96f--- /dev/null+++ b/backend/src/services/app-connection/jira/jira-connection-types.ts@@ -0,0 +1,59 @@+import z from "zod";++import { DiscriminativePick } from "@app/lib/types";++import { AppConnection } from "../app-connection-enums";+import {+ CreateJiraConnectionSchema,+ JiraConnectionSchema,+ ValidateJiraConnectionCredentialsSchema+} from "./jira-connection-schemas";++export type TJiraConnection = z.infer<typeof JiraConnectionSchema>;++export type TJiraConnectionInput = z.infer<typeof CreateJiraConnectionSchema> & {+ app: AppConnection.Jira;+};++export type TValidateJiraConnectionCredentialsSchema = typeof ValidateJiraConnectionCredentialsSchema;++export type TJiraConnectionConfig = DiscriminativePick<+ TJiraConnectionInput,+ "method" | "app" | "credentials" | "gatewayId" | "gatewayPoolId"+> & {+ orgId: string;+};++export type TJiraUser = {+ // Jira Cloud identifies users by accountId, Jira Data Center by key+ accountId?: string;+ key?: string;+ name?: string;+ emailAddress?: string;+ displayName?: string;+ active?: boolean;+};++export type TJiraIssue = {+ id: string;+ key: string;+ fields: {+ status?: { id: string; name: string } | null;+ project?: { id: string; key: string; name: string } | null;+ issuetype?: { id: string; name: string } | null;+ labels?: string[] | null;+ assignee?: TJiraUser | null;+ };+};++export type TJiraApprovalDecision = "approved" | "declined" | "pending";++export type TJiraApproval = {+ id: string;+ name?: string;+ finalDecision: TJiraApprovalDecision;+ createdDate?: { epochMillis?: number; iso8601?: string };+ completedDate?: { epochMillis?: number; iso8601?: string };+};++export type TJiraNamedOption = { id: string; name: string };diff --git a/docs/api-reference/endpoints/app-connections/jira/available.mdx b/docs/api-reference/endpoints/app-connections/jira/available.mdxnew file mode 100644index 0000000000..73987c8cd7--- /dev/null+++ b/docs/api-reference/endpoints/app-connections/jira/available.mdx@@ -0,0 +1,4 @@+---+title: "Available"+openapi: "GET /api/v1/app-connections/jira/available"+---diff --git a/docs/api-reference/endpoints/app-connections/jira/create.mdx b/docs/api-reference/endpoints/app-connections/jira/create.mdxnew file mode 100644index 0000000000..1582d7dde6--- /dev/null+++ b/docs/api-reference/endpoints/app-connections/jira/create.mdx@@ -0,0 +1,8 @@+---+title: "Create"+openapi: "POST /api/v1/app-connections/jira"+---++<Note>+ Check out the configuration docs for [Jira Connections](/integrations/app-connections/jira) to learn how to obtain the required credentials.+</Note>diff --git a/docs/api-reference/endpoints/app-connections/jira/delete.mdx b/docs/api-reference/endpoints/app-connections/jira/delete.mdxnew file mode 100644index 0000000000..90dee2e8c6--- /dev/null+++ b/docs/api-reference/endpoints/app-connections/jira/delete.mdx@@ -0,0 +1,4 @@+---+title: "Delete"+openapi: "DELETE /api/v1/app-connections/jira/{connectionId}"+---diff --git a/docs/api-reference/endpoints/app-connections/jira/get-by-id.mdx b/docs/api-reference/endpoints/app-connections/jira/get-by-id.mdxnew file mode 100644index 0000000000..5dd1f714b0--- /dev/null+++ b/docs/api-reference/endpoints/app-connections/jira/get-by-id.mdx@@ -0,0 +1,4 @@+---+title: "Get by ID"+openapi: "GET /api/v1/app-connections/jira/{connectionId}"+---diff --git a/docs/api-reference/endpoints/app-connections/jira/get-by-name.mdx b/docs/api-reference/endpoints/app-connections/jira/get-by-name.mdxnew file mode 100644index 0000000000..1f7bb363c3--- /dev/null+++ b/docs/api-reference/endpoints/app-connections/jira/get-by-name.mdx@@ -0,0 +1,4 @@+---+title: "Get by name"+openapi: "GET /api/v1/app-connections/jira/connection-name/{connectionName}"+---diff --git a/docs/api-reference/endpoints/app-connections/jira/list.mdx b/docs/api-reference/endpoints/app-connections/jira/list.mdxnew file mode 100644index 0000000000..6517f4d500--- /dev/null+++ b/docs/api-reference/endpoints/app-connections/jira/list.mdx@@ -0,0 +1,4 @@+---+title: "List"+openapi: "GET /api/v1/app-connections/jira"+---diff --git a/docs/api-reference/endpoints/app-connections/jira/update.mdx b/docs/api-reference/endpoints/app-connections/jira/update.mdxnew file mode 100644index 0000000000..a75a4fdd93--- /dev/null+++ b/docs/api-reference/endpoints/app-connections/jira/update.mdx@@ -0,0 +1,8 @@+---+title: "Update"+openapi: "PATCH /api/v1/app-connections/jira/{connectionId}"+---++<Note>+ Check out the configuration docs for [Jira Connections](/integrations/app-connections/jira) to learn how to obtain the required credentials.+</Note>diff --git a/docs/docs.json b/docs/docs.jsonindex 732f8ec921..d1c7f615a3 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -1054,6 +1054,7 @@"integrations/app-connections/heroku","integrations/app-connections/hpe-ilo","integrations/app-connections/humanitec",+ "integrations/app-connections/jira","integrations/app-connections/keeper","integrations/app-connections/kemp-loadmaster","integrations/app-connections/external-infisical",@@ -2092,6 +2093,18 @@"api-reference/endpoints/app-connections/external-infisical/delete"]},+ {+ "group": "Jira",+ "pages": [+ "api-reference/endpoints/app-connections/jira/list",+ "api-reference/endpoints/app-connections/jira/available",+ "api-reference/endpoints/app-connections/jira/get-by-id",+ "api-reference/endpoints/app-connections/jira/get-by-name",+ "api-reference/endpoints/app-connections/jira/create",+ "api-reference/endpoints/app-connections/jira/update",+ "api-reference/endpoints/app-connections/jira/delete"+ ]+ },{"group": "Keeper","pages": [diff --git a/docs/integrations/app-connections/jira.mdx b/docs/integrations/app-connections/jira.mdxnew file mode 100644index 0000000000..702ed593f4--- /dev/null+++ b/docs/integrations/app-connections/jira.mdx@@ -0,0 +1,96 @@+---+title: "Jira connection"+sidebarTitle: "Jira"+description: "Learn how to configure a Jira connection for Infisical."+---++import ConnectionFormFields from "/snippets/app-connections/jira/form-fields.mdx";++A Jira connection authenticates Infisical to Jira Cloud with an [API token](https://support.atlassian.com/atlassian-account/docs/manage-api-tokens-for-your-atlassian-account/), or to Jira Data Center with a [personal access token](https://confluence.atlassian.com/enterprise/using-personal-access-tokens-1026032365.html), so Infisical can read your Jira tickets.++Infisical acts as the Jira user who owns the token, so Infisical can only read the tickets that user can see.++## Prerequisites++- A Jira Cloud site, or a Jira Data Center instance that Infisical can reach directly or through a [Gateway](/documentation/platform/gateways/overview)+- A Jira user for Infisical to act as, and a Jira admin who can change that user's permissions++## Step 1: Create an API token or personal access token++The token's user needs these permissions in Jira:++- **Browse spaces** in Jira Cloud, or **Browse projects** in Jira Data Center, on every project whose tickets you want Infisical to read+- **Browse users and groups**, so Infisical can look up a ticket's assignee when Jira hides the assignee's email address+- Permission to view customer requests in your Jira Service Management projects, so Infisical can read a request's approvals++Then create the token as that user:++<Tabs>+ <Tab title="Jira Cloud">+ <Steps>+ <Step>+ Sign in to Atlassian as the user, then go to **Security** > **API tokens** in your Atlassian account settings.+ </Step>+ <Step>+ Select **Create API token**. Infisical connects to your Jira site's URL, and Atlassian only accepts tokens without scopes there.+ </Step>+ <Step>+ Enter a name, such as `infisical`, choose an expiration date, and select **Create**. Before the token expires, create a new one and enter it with **Edit Credentials** in the connection's menu on the **App Connections** tab.+ </Step>+ <Step>+ Copy the token. Atlassian shows it only once.+ </Step>+ </Steps>+ </Tab>+ <Tab title="Jira Data Center">+ <Steps>+ <Step>+ Sign in to Jira as the user, then go to **Profile** > **Personal Access Tokens**.+ </Step>+ <Step>+ Select **Create token**, enter a name, such as `infisical`, and create the token.+ </Step>+ <Step>+ Copy the token. Jira shows it only once.+ </Step>+ </Steps>+ </Tab>+</Tabs>++## Step 2: Create the app connection++Next, create the app connection in Infisical.++<Tip>+ To create the connection using the API, use the [Create Jira Connection](/api-reference/endpoints/app-connections/jira/create) endpoint.+</Tip>++<Steps>+ <Step>+ In the sidebar, select **Integrations**, then open the **App Connections** tab.+ </Step>+ <Step>+ Select **Add Connection** and choose **Jira**.+ </Step>+ <Step>+ Fill out the form's fields:++ <ConnectionFormFields />++ Then, select **Connect to Jira**.+ </Step>+</Steps>++When you select **Connect to Jira**, Infisical verifies that Jira accepts the token, and doesn't save the connection if Jira rejects it. Infisical doesn't check the permissions from [Step 1](#step-1-create-an-api-token-or-personal-access-token) until it reads a ticket.++<Check>+ Your Jira app connection is ready to use.+</Check>++## Step 3: Configure integrations++Now that your Jira app connection is configured, you can use it to set up the following integrations:++<Card title="PAM auto-approval" icon="zap" href="/documentation/platform/pam/access-requests/auto-approval">+ Approve PAM access requests when a linked Jira ticket passes a folder's rules.+</Card>diff --git a/docs/snippets/app-connections/jira/form-fields.mdx b/docs/snippets/app-connections/jira/form-fields.mdxnew file mode 100644index 0000000000..e14fdd1425--- /dev/null+++ b/docs/snippets/app-connections/jira/form-fields.mdx@@ -0,0 +1,23 @@+{/* The tab titles match the tabs in Step 1 of the Jira connection page. Keep them identical. */}++<Tabs>+ <Tab title="Jira Cloud">+ - **Name**: A descriptive name for the connection+ - **Description** (optional): A note for future reference+ - **Gateway** (optional): The [Gateway](/documentation/platform/gateways/overview) Infisical connects through, if Infisical can't reach your Jira site directly+ - **Method**: **API Token (Jira Cloud)**+ - **Instance URL**: The URL of your Jira site without a path, such as `https://your-domain.atlassian.net`+ - **Email**: The email address of the Atlassian account that owns the API token+ - **API Token**: The API token you [created in Step 1](#step-1-create-an-api-token-or-personal-access-token)+ </Tab>+ <Tab title="Jira Data Center">+ - **Name**: A descriptive name for the connection+ - **Description** (optional): A note for future reference+ - **Gateway** (optional): The [Gateway](/documentation/platform/gateways/overview) Infisical connects through, if Infisical can't reach your Jira instance directly, such as when the instance is behind a firewall+ - **Method**: **Personal Access Token (Jira Data Center)**+ - **Instance URL**: The URL of your Jira instance, including the context path if Jira runs under one, such as `https://jira.example.com/jira`+ - **Personal Access Token**: The personal access token you [created in Step 1](#step-1-create-an-api-token-or-personal-access-token)+ - **SSL Certificate** (optional): On the **SSL** tab, the CA certificate in PEM format that signed your Jira instance's TLS certificate+ - **Reject Unauthorized**: On the **SSL** tab, whether Infisical refuses to connect when it can't verify the instance's TLS certificate (on by default; for a self-signed certificate, enter its CA certificate in **SSL Certificate** instead of turning this off)+ </Tab>+</Tabs>diff --git a/docs/snippets/catalogs/app-connections.jsx b/docs/snippets/catalogs/app-connections.jsxindex 179dcb8f33..6b9cac22fb 100644--- a/docs/snippets/catalogs/app-connections.jsx+++ b/docs/snippets/catalogs/app-connections.jsx@@ -699,4 +699,12 @@ export const appConnections = ["Learn how to connect Keeper Commander Service Mode to sync secrets from Infisical.",category: "Security",},+ {+ name: "Jira",+ slug: "jira",+ path: "/integrations/app-connections/jira",+ description:+ "Learn how to connect Jira Cloud or Jira Data Center so Infisical can read your Jira tickets.",+ category: "SaaS",+ },];diff --git a/frontend/src/helpers/appConnections.ts b/frontend/src/helpers/appConnections.tsindex 6453ab8ada..3588698518 100644--- a/frontend/src/helpers/appConnections.ts+++ b/frontend/src/helpers/appConnections.ts@@ -74,6 +74,7 @@ import { GoDaddyConnectionMethod } from "@app/hooks/api/appConnections/types/godimport { HasuraCloudConnectionMethod } from "@app/hooks/api/appConnections/types/hasura-cloud-connection";import { HerokuConnectionMethod } from "@app/hooks/api/appConnections/types/heroku-connection";import { HpeIloConnectionMethod } from "@app/hooks/api/appConnections/types/hpe-ilo-connection";+import { JiraConnectionMethod } from "@app/hooks/api/appConnections/types/jira-connection";import { KeeperConnectionMethod } from "@app/hooks/api/appConnections/types/keeper-connection";import { KempLoadMasterConnectionMethod } from "@app/hooks/api/appConnections/types/kemp-loadmaster-connection";import { LaravelForgeConnectionMethod } from "@app/hooks/api/appConnections/types/laravel-forge-connection";@@ -680,6 +681,12 @@ export const APP_CONNECTION_MAP: Record<image: "Daytona.png",category: "PLATFORM",description: "Organization secret access for Daytona sandboxes."+ },+ [AppConnection.Jira]: {+ name: "Jira",+ image: "Jira.svg",+ category: "PRODUCTIVITY",+ description: "Atlassian Jira Cloud and Data Center."}};@@ -699,6 +706,7 @@ export const getAppConnectionMethodDetails = (method: TAppConnection["method"])return { name: "GitHub App", icon: GithubIcon };case GitHubConnectionMethod.Pat:case OnaConnectionMethod.PersonalAccessToken:+ case JiraConnectionMethod.PersonalAccessToken:return { name: "Personal Access Token", icon: KeyRoundIcon };case AzureKeyVaultConnectionMethod.OAuth:case AzureAppConfigurationConnectionMethod.OAuth:@@ -738,6 +746,7 @@ export const getAppConnectionMethodDetails = (method: TAppConnection["method"])case DopplerConnectionMethod.ApiToken:case RundeckConnectionMethod.ApiToken:case PortainerConnectionMethod.ApiToken:+ case JiraConnectionMethod.ApiToken:return { name: "API Token", icon: KeyRoundIcon };case VenafiConnectionMethod.ApiKey:return { name: "API Key", icon: KeyRoundIcon };diff --git a/frontend/src/hooks/api/appConnections/enums.ts b/frontend/src/hooks/api/appConnections/enums.tsindex 3edf7aef6f..b8dfab0603 100644--- a/frontend/src/hooks/api/appConnections/enums.ts+++ b/frontend/src/hooks/api/appConnections/enums.ts@@ -89,5 +89,6 @@ export enum AppConnection {Daytona = "daytona",Stripe = "stripe",Keeper = "keeper",- HpeIloRedFish = "hpe-ilo"+ HpeIloRedFish = "hpe-ilo",+ Jira = "jira"}diff --git a/frontend/src/hooks/api/appConnections/types/app-options.ts b/frontend/src/hooks/api/appConnections/types/app-options.tsindex b39fcb4db8..da2cb81eb4 100644--- a/frontend/src/hooks/api/appConnections/types/app-options.ts+++ b/frontend/src/hooks/api/appConnections/types/app-options.ts@@ -379,6 +379,10 @@ export type TDaytonaConnectionOption = TAppConnectionOptionBase & {app: AppConnection.Daytona;};+export type TJiraConnectionOption = TAppConnectionOptionBase & {+ app: AppConnection.Jira;+};+export type TAppConnectionOption =| TAwsConnectionOption| TGitHubConnectionOption@@ -470,7 +474,8 @@ export type TAppConnectionOption =| TFireworksConnectionOption| TNutanixPrismCentralConnectionOption| TSpaceliftConnectionOption- | TDaytonaConnectionOption;+ | TDaytonaConnectionOption+ | TJiraConnectionOption;export type TAppConnectionOptionMap = {[AppConnection.AWS]: TAwsConnectionOption;@@ -564,4 +569,5 @@ export type TAppConnectionOptionMap = {[AppConnection.NutanixPrismCentral]: TNutanixPrismCentralConnectionOption;[AppConnection.Spacelift]: TSpaceliftConnectionOption;[AppConnection.Daytona]: TDaytonaConnectionOption;+ [AppConnection.Jira]: TJiraConnectionOption;};diff --git a/frontend/src/hooks/api/appConnections/types/index.ts b/frontend/src/hooks/api/appConnections/types/index.tsindex 8c0f1f5f8d..d49e52807e 100644--- a/frontend/src/hooks/api/appConnections/types/index.ts+++ b/frontend/src/hooks/api/appConnections/types/index.ts@@ -43,6 +43,7 @@ import { THCVaultConnection } from "./hc-vault-connection";import { THerokuConnection } from "./heroku-connection";import { THpeIloConnection } from "./hpe-ilo-connection";import { THumanitecConnection } from "./humanitec-connection";+import { TJiraConnection } from "./jira-connection";import { TKeeperConnection } from "./keeper-connection";import { TKempLoadMasterConnection } from "./kemp-loadmaster-connection";import { TLaravelForgeConnection } from "./laravel-forge-connection";@@ -132,6 +133,7 @@ export * from "./hc-vault-connection";export * from "./heroku-connection";export * from "./hpe-ilo-connection";export * from "./humanitec-connection";+export * from "./jira-connection";export * from "./keeper-connection";export * from "./kemp-loadmaster-connection";export * from "./laravel-forge-connection";@@ -272,7 +274,8 @@ export type TAppConnection =| TDaytonaConnection| TStripeConnection| TKeeperConnection- | THpeIloConnection;+ | THpeIloConnection+ | TJiraConnection;export type TAvailableAppConnection = Pick<TAppConnection, "name" | "id" | "projectId">;diff --git a/frontend/src/hooks/api/appConnections/types/jira-connection.ts b/frontend/src/hooks/api/appConnections/types/jira-connection.tsnew file mode 100644index 0000000000..87219a310f--- /dev/null+++ b/frontend/src/hooks/api/appConnections/types/jira-connection.ts@@ -0,0 +1,27 @@+import { AppConnection } from "@app/hooks/api/appConnections/enums";+import { TRootAppConnection } from "@app/hooks/api/appConnections/types/root-connection";++export enum JiraConnectionMethod {+ ApiToken = "api-token",+ PersonalAccessToken = "personal-access-token"+}++export type TJiraConnection = TRootAppConnection & { app: AppConnection.Jira } & (+ | {+ method: JiraConnectionMethod.ApiToken;+ credentials: {+ instanceUrl: string;+ email: string;+ apiToken: string;+ };+ }+ | {+ method: JiraConnectionMethod.PersonalAccessToken;+ credentials: {+ instanceUrl: string;+ personalAccessToken: string;+ sslRejectUnauthorized?: boolean;+ sslCertificate?: string;+ };+ }+ );diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AppConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AppConnectionForm.tsxindex 9f68a00b4d..510bdf5681 100644--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AppConnectionForm.tsx+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AppConnectionForm.tsx@@ -58,6 +58,7 @@ import { HCVaultConnectionForm } from "./HCVaultConnectionForm";import { HerokuConnectionForm } from "./HerokuAppConnectionForm";import { HpeIloConnectionForm } from "./HpeIloConnectionForm";import { HumanitecConnectionForm } from "./HumanitecConnectionForm";+import { JiraConnectionForm } from "./JiraConnectionForm";import { KeeperConnectionForm } from "./KeeperConnectionForm";import { KempLoadMasterConnectionForm } from "./KempLoadMasterConnectionForm";import { LaravelForgeConnectionForm } from "./LaravelForgeConnectionForm";@@ -379,6 +380,8 @@ const CreateForm = ({ app, onComplete, projectId, projectType }: CreateFormPropsreturn <F5BigIpConnectionForm onSubmit={onSubmit} />;case AppConnection.HpeIloRedFish:return <HpeIloConnectionForm onSubmit={onSubmit} />;+ case AppConnection.Jira:+ return <JiraConnectionForm onSubmit={onSubmit} />;case AppConnection.Convex:return <ConvexConnectionForm onSubmit={onSubmit} />;case AppConnection.Rundeck:@@ -680,6 +683,8 @@ const UpdateForm = ({ appConnection, onComplete }: UpdateFormProps) => {return <F5BigIpConnectionForm onSubmit={onSubmit} appConnection={appConnection} />;case AppConnection.HpeIloRedFish:return <HpeIloConnectionForm onSubmit={onSubmit} appConnection={appConnection} />;+ case AppConnection.Jira:+ return <JiraConnectionForm onSubmit={onSubmit} appConnection={appConnection} />;case AppConnection.Convex:return <ConvexConnectionForm onSubmit={onSubmit} appConnection={appConnection} />;case AppConnection.Rundeck:diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/JiraConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/JiraConnectionForm.tsxnew file mode 100644index 0000000000..30c9634752--- /dev/null+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/JiraConnectionForm.tsx@@ -0,0 +1,383 @@+import { useState } from "react";+import { Controller, FormProvider, useForm } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";+import { Info } from "lucide-react";+import { z } from "zod";++import { OrgPermissionCan } from "@app/components/permissions";+import {+ Field,+ FieldContent,+ FieldDescription,+ FieldError,+ FieldLabel,+ Input,+ Label,+ SecretInput,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+ Tabs,+ TabsContent,+ TabsList,+ TabsTrigger,+ TextArea,+ Toggle,+ Tooltip,+ TooltipContent,+ TooltipTrigger+} from "@app/components/v3";+import { GatewayPicker } from "@app/components/v3/platform/GatewayPicker";+import { OrgPermissionSubjects } from "@app/context";+import { OrgGatewayPermissionActions } from "@app/context/OrgPermissionContext/types";+import { APP_CONNECTION_MAP, getAppConnectionMethodDetails } from "@app/helpers/appConnections";+import { useScopeVariant } from "@app/hooks";+import { JiraConnectionMethod, TJiraConnection } from "@app/hooks/api/appConnections";+import { AppConnection } from "@app/hooks/api/appConnections/enums";++import { AppConnectionFormFooter } from "./AppConnectionFormFooter";+import {+ genericAppConnectionFieldsSchema,+ GenericAppConnectionsFields+} from "./GenericAppConnectionFields";++type Props = {+ appConnection?: TJiraConnection;+ onSubmit: (formData: FormData) => Promise<void>;+};++const DEPLOYMENT_BY_METHOD: Record<+ JiraConnectionMethod,+ { name: string; instanceUrlPlaceholder: string }+> = {+ [JiraConnectionMethod.ApiToken]: {+ name: "Jira Cloud",+ instanceUrlPlaceholder: "https://your-domain.atlassian.net"+ },+ [JiraConnectionMethod.PersonalAccessToken]: {+ name: "Jira Data Center",+ instanceUrlPlaceholder: "https://jira.example.com"+ }+};++const isValidInstanceUrl = (value: string) => {+ try {+ const url = new URL(value);+ return (+ ["http:", "https:"].includes(url.protocol) &&+ !url.username &&+ !url.password &&+ !url.search &&+ !url.hash+ );+ } catch {+ return false;+ }+};++const instanceUrlSchema = z+ .string()+ .trim()+ .min(1, "Instance URL required")+ .max(512, "Instance URL cannot exceed 512 characters")+ .refine(+ isValidInstanceUrl,+ "Instance URL must be an http or https URL without credentials, a query, or a fragment"+ );++const rootSchema = genericAppConnectionFieldsSchema.extend({+ app: z.literal(AppConnection.Jira)+});++const formSchema = z.discriminatedUnion("method", [+ rootSchema.extend({+ method: z.literal(JiraConnectionMethod.ApiToken),+ credentials: z.object({+ instanceUrl: instanceUrlSchema,+ email: z+ .string()+ .trim()+ .min(1, "Email required")+ .max(320, "Email cannot exceed 320 characters")+ .email("Email must be a valid email address"),+ apiToken: z+ .string()+ .trim()+ .min(1, "API token required")+ .max(1024, "API token cannot exceed 1024 characters")+ })+ }),+ rootSchema.extend({+ method: z.literal(JiraConnectionMethod.PersonalAccessToken),+ credentials: z.object({+ instanceUrl: instanceUrlSchema,+ personalAccessToken: z+ .string()+ .trim()+ .min(1, "Personal access token required")+ .max(1024, "Personal access token cannot exceed 1024 characters"),+ sslRejectUnauthorized: z.boolean().default(true),+ sslCertificate: z+ .string()+ .trim()+ .max(16384, "SSL certificate cannot exceed 16384 characters")+ .transform((value) => value || undefined)+ .optional()+ })+ })+]);++type FormData = z.infer<typeof formSchema>;++export const JiraConnectionForm = ({ appConnection, onSubmit }: Props) => {+ const isUpdate = Boolean(appConnection);+ const [selectedTab, setSelectedTab] = useState("configuration");++ const form = useForm<FormData>({+ resolver: zodResolver(formSchema),+ defaultValues: appConnection ?? {+ app: AppConnection.Jira,+ method: JiraConnectionMethod.ApiToken,+ gatewayId: null,+ gatewayPoolId: null+ }+ });++ const { handleSubmit, control, setValue, watch } = form;+ const scopeVariant = useScopeVariant();++ const method = watch("method");+ const gatewayId = watch("gatewayId");+ const gatewayPoolId = watch("gatewayPoolId");++ const instanceUrlField = (+ <Controller+ name="credentials.instanceUrl"+ control={control}+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <Field className="mb-4">+ <FieldLabel htmlFor="instance-url">Instance URL</FieldLabel>+ {method === JiraConnectionMethod.PersonalAccessToken && (+ <FieldDescription>+ Include the context path if Jira runs under one, such as /jira.+ </FieldDescription>+ )}+ <Input+ id="instance-url"+ value={value}+ onChange={(e) => onChange(e.target.value)}+ placeholder={DEPLOYMENT_BY_METHOD[method].instanceUrlPlaceholder}+ isError={Boolean(error?.message)}+ />+ <FieldError errors={[error]} />+ </Field>+ )}+ />+ );++ return (+ <FormProvider {...form}>+ <form onSubmit={handleSubmit(onSubmit)}>+ {!isUpdate && <GenericAppConnectionsFields />}+ <OrgPermissionCan+ I={OrgGatewayPermissionActions.AttachGateways}+ a={OrgPermissionSubjects.Gateway}+ >+ {(isAllowed) => {+ const picker = (+ <GatewayPicker+ isDisabled={!isAllowed}+ value={{ gatewayId: gatewayId ?? null, gatewayPoolId: gatewayPoolId ?? null }}+ onChange={({ gatewayId: newGwId, gatewayPoolId: newPoolId }) => {+ setValue("gatewayId", newGwId, { shouldDirty: true });+ setValue("gatewayPoolId", newPoolId, { shouldDirty: true });+ }}+ />+ );++ return (+ <Field className="mb-4">+ <FieldLabel>Gateway</FieldLabel>+ <FieldDescription>+ Route requests through a Gateway when your Jira instance is not reachable from the+ internet.+ </FieldDescription>+ {isAllowed ? (+ picker+ ) : (+ <Tooltip>+ <TooltipTrigger asChild>+ <span className="block w-full cursor-not-allowed">{picker}</span>+ </TooltipTrigger>+ <TooltipContent>+ Restricted access. You don't have permission to attach gateways to+ resources.+ </TooltipContent>+ </Tooltip>+ )}+ </Field>+ );+ }}+ </OrgPermissionCan>+ <Controller+ name="method"+ control={control}+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <Field className="mb-4">+ <FieldLabel htmlFor="method">+ Method+ <Tooltip>+ <TooltipTrigger asChild>+ <Info />+ </TooltipTrigger>+ <TooltipContent className="max-w-sm">+ {`The method you would like to use to connect with ${+ APP_CONNECTION_MAP[AppConnection.Jira].name+ }. This field cannot be changed after creation.`}+ </TooltipContent>+ </Tooltip>+ </FieldLabel>+ <Select disabled={isUpdate} value={value} onValueChange={(val) => onChange(val)}>+ <SelectTrigger id="method" className="w-full" isError={Boolean(error)}>+ <SelectValue placeholder="Select a method..." />+ </SelectTrigger>+ <SelectContent position="popper">+ {Object.values(JiraConnectionMethod).map((m) => (+ <SelectItem value={m} key={m}>+ {getAppConnectionMethodDetails(m).name} ({DEPLOYMENT_BY_METHOD[m].name})+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FieldError errors={[error]} />+ </Field>+ )}+ />+ {method === JiraConnectionMethod.ApiToken ? (+ <>+ {instanceUrlField}+ <Controller+ name="credentials.email"+ control={control}+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <Field className="mb-4">+ <FieldLabel htmlFor="email">Email</FieldLabel>+ <Input+ id="email"+ value={value}+ onChange={(e) => onChange(e.target.value)}+ placeholder="[email protected]"+ isError={Boolean(error?.message)}+ />+ <FieldError errors={[error]} />+ </Field>+ )}+ />+ <Controller+ name="credentials.apiToken"+ control={control}+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <Field className="mb-4">+ <FieldLabel htmlFor="api-token">API Token</FieldLabel>+ <FieldDescription>+ Create one in your Atlassian account settings under Security > API tokens.+ </FieldDescription>+ <SecretInput+ aria-describedby={error ? "api-token-error" : undefined}+ isError={Boolean(error)}+ id="api-token"+ value={value}+ onChange={(e) => onChange(e.target.value)}+ />+ <FieldError id="api-token-error" errors={[error]} />+ </Field>+ )}+ />+ </>+ ) : (+ <Tabs value={selectedTab} onValueChange={setSelectedTab} className="mb-4">+ <TabsList variant={scopeVariant}>+ <TabsTrigger value="configuration">Configuration</TabsTrigger>+ <TabsTrigger value="ssl">SSL</TabsTrigger>+ </TabsList>+ <TabsContent value="configuration">+ {instanceUrlField}+ <Controller+ name="credentials.personalAccessToken"+ control={control}+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <Field className="mb-4">+ <FieldLabel htmlFor="personal-access-token">Personal Access Token</FieldLabel>+ <FieldDescription>+ Create one in Jira under Profile > Personal Access Tokens.+ </FieldDescription>+ <SecretInput+ aria-describedby={error ? "personal-access-token-error" : undefined}+ isError={Boolean(error)}+ id="personal-access-token"+ value={value}+ onChange={(e) => onChange(e.target.value)}+ />+ <FieldError id="personal-access-token-error" errors={[error]} />+ </Field>+ )}+ />+ </TabsContent>+ <TabsContent value="ssl">+ <Controller+ name="credentials.sslCertificate"+ control={control}+ render={({ field, fieldState: { error } }) => (+ <Field className="mb-4">+ <FieldLabel htmlFor="ssl-certificate">+ SSL Certificate <span className="text-muted">(optional)</span>+ </FieldLabel>+ <TextArea+ id="ssl-certificate"+ className="h-[3.6rem] resize-none!"+ {...field}+ placeholder="-----BEGIN CERTIFICATE----- ... -----END CERTIFICATE-----"+ isError={Boolean(error?.message)}+ />+ <FieldError errors={[error]} />+ </Field>+ )}+ />+ <Controller+ name="credentials.sslRejectUnauthorized"+ control={control}+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <Field>+ <Field orientation="horizontal">+ <FieldContent>+ <Label htmlFor="ssl-reject-unauthorized">Reject Unauthorized</Label>+ <FieldDescription>+ If enabled, Infisical will only connect if Jira presents a valid, trusted+ SSL certificate. Disable this for self-signed certificates or provide a CA+ certificate above.+ </FieldDescription>+ </FieldContent>+ <Toggle+ aria-invalid={Boolean(error)}+ id="ssl-reject-unauthorized"+ variant={scopeVariant}+ checked={value ?? true}+ onCheckedChange={onChange}+ />+ </Field>+ <FieldError errors={[error]} />+ </Field>+ )}+ />+ </TabsContent>+ </Tabs>+ )}+ <AppConnectionFormFooter+ submitLabel={isUpdate ? "Update Credentials" : "Connect to Jira"}+ />+ </form>+ </FormProvider>+ );+};