Skip to content

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

21.9 KB
Raw Blame
import { FastifyRequest } from "fastify";
import { z } from "zod";

import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { ApiDocsTags, AppConnections } from "@app/lib/api-docs";
import { startsWithVowel } from "@app/lib/fn";
import { logger } from "@app/lib/logger";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { APP_CONNECTION_NAME_MAP } from "@app/services/app-connection/app-connection-maps";
import { TAppConnectionInput, TAppConnectionScope } from "@app/services/app-connection/app-connection-types";
import { TCreateAppConnectionCredentialRotationSchema } from "@app/services/app-connection/credential-rotation/app-connection-credential-rotation-types";
import { AuthMode } from "@app/services/auth/auth-type";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";

type TAppConnectionCreateSchema<I extends TAppConnectionInput> = z.ZodType<{
  name: string;
  method: I["method"];
  credentials: I["credentials"];
  description?: string | null;
  isPlatformManagedCredentials?: boolean;
  isAutoRotationEnabled?: boolean | null;
  gatewayId?: string | null;
  gatewayPoolId?: string | null;
  projectId?: string;
  rotation?: TCreateAppConnectionCredentialRotationSchema | null;
  configuration?: Record<string, unknown>;
}>;

type TAppConnectionUpdateSchema<I extends TAppConnectionInput> = z.ZodType<{
  name?: string;
  credentials?: I["credentials"];
  description?: string | null;
  isPlatformManagedCredentials?: boolean;
  gatewayId?: string | null;
  gatewayPoolId?: string | null;
  isAutoRotationEnabled?: boolean | null;
  rotation?: Partial<TCreateAppConnectionCredentialRotationSchema> | null;
  configuration?: Record<string, unknown>;
}>;

// For routes that belong to one project the caller never names, such as Agent Vault's: the server supplies it.
type TResolveScope = (req: FastifyRequest) => TAppConnectionScope;

type TAppConnectionRouteContext = ReturnType<typeof buildAppConnectionRouteContext>;

export const buildAppConnectionRouteContext = ({
  server,
  app,
  sanitizedResponseSchema,
  operationIdPrefix = "",
  tags = [ApiDocsTags.AppConnections]
}: {
  server: FastifyZodProvider;
  app: AppConnection;
  sanitizedResponseSchema: z.ZodTypeAny;
  operationIdPrefix?: string;
  tags?: ApiDocsTags[];
}) => {
  const appName = APP_CONNECTION_NAME_MAP[app];
  const specialCases: Record<string, string> = {
    [AppConnection.OnePass]: "OnePassword",
    [AppConnection.GitHub]: "GitHub",
    [AppConnection.GitHubRadar]: "GitHubRadar",
    [AppConnection.GitLab]: "GitLab",
    [AppConnection.MsSql]: "MsSql",
    [AppConnection.MySql]: "MySql",
    [AppConnection.OracleDB]: "OracleDb",
    [AppConnection.MongoDB]: "MongoDb",
    [AppConnection.TravisCI]: "TravisCI",
    [AppConnection.ServiceNow]: "ServiceNow"
  };
  const appNameForOpId =
    operationIdPrefix +
    (specialCases[app] ??
      app
        .split("-")
        .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
        .join(""));

  return { server, app, appName, appNameForOpId, sanitizedResponseSchema, tags };
};

export const buildListAppConnectionsRoute = (
  { server, app, appName, appNameForOpId, sanitizedResponseSchema, tags }: TAppConnectionRouteContext,
  {
    description = `List the ${appName} Connections for the current organization or project.`,
    resolveScope
  }: { description?: string; resolveScope?: TResolveScope } = {}
) => {
  server.route({
    method: "GET",
    url: `/`,
    config: {
      rateLimit: readLimit
    },
    schema: {
      hide: false,
      operationId: `list${appNameForOpId}AppConnections`,
      tags,
      description,
      ...(!resolveScope && {
        querystring: z.object({
          projectId: z.string().optional().describe(AppConnections.LIST(app).projectId)
        })
      }),
      response: {
        200: z.object({ appConnections: sanitizedResponseSchema.array() })
      }
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
    handler: async (req) => {
      const projectId = resolveScope ? resolveScope(req).projectId : (req.query as { projectId?: string }).projectId;
      const appConnections = await server.services.appConnection.listAppConnections(req.permission, app, projectId);

      await server.services.auditLog.createAuditLog({
        ...req.auditLogInfo,
        orgId: req.permission.orgId,
        projectId,
        event: {
          type: EventType.GET_APP_CONNECTIONS,
          metadata: {
            app,
            count: appConnections.length,
            connectionIds: appConnections.map((connection) => connection.id)
          }
        }
      });

      return { appConnections };
    }
  });
};

export const buildListAvailableAppConnectionsRoute = (
  { server, app, appName, appNameForOpId, tags }: TAppConnectionRouteContext,
  {
    description = `List the ${appName} Connections the current user has permission to establish connections within this project.`
  }: { description?: string } = {}
) => {
  server.route({
    method: "GET",
    url: "/available",
    config: {
      rateLimit: readLimit
    },
    schema: {
      hide: false,
      operationId: `list${appNameForOpId}AvailableAppConnections`,
      tags,
      description,
      querystring: z.object({
        projectId: z.string().optional().describe(AppConnections.LIST(app).projectId)
      }),
      response: {
        200: z.object({
          appConnections: z
            .object({
              app: z.literal(app),
              name: z.string(),
              id: z.string().uuid(),
              projectId: z.string().nullish(),
              orgId: z.string(),
              gatewayId: z.string().uuid().nullish(),
              gatewayPoolId: z.string().uuid().nullish()
            })
            .array()
        })
      }
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
    handler: async (req) => {
      const { projectId } = req.query;
      const appConnections = await server.services.appConnection.listAvailableAppConnectionsForUser(
        app,
        req.permission,
        projectId
      );

      await server.services.auditLog.createAuditLog({
        ...req.auditLogInfo,
        orgId: req.permission.orgId,
        projectId,
        event: {
          type: EventType.GET_AVAILABLE_APP_CONNECTIONS_DETAILS,
          metadata: {
            app,
            count: appConnections.length,
            connectionIds: appConnections.map((connection) => connection.id)
          }
        }
      });

      return { appConnections };
    }
  });
};

export const buildGetAppConnectionRoute = (
  { server, app, appName, appNameForOpId, sanitizedResponseSchema, tags }: TAppConnectionRouteContext,
  {
    description = `Get the specified ${appName} Connection by ID.`,
    resolveScope
  }: { description?: string; resolveScope?: TResolveScope } = {}
) => {
  server.route({
    method: "GET",
    url: "/:connectionId",
    config: {
      rateLimit: readLimit
    },
    schema: {
      hide: false,
      operationId: `get${appNameForOpId}AppConnection`,
      tags,
      description,
      params: z.object({
        connectionId: z.string().uuid().describe(AppConnections.GET_BY_ID(app).connectionId)
      }),
      response: {
        200: z.object({ appConnection: sanitizedResponseSchema })
      }
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
    handler: async (req) => {
      const { connectionId } = req.params;

      const appConnection = await server.services.appConnection.findAppConnectionById(
        app,
        connectionId,
        req.permission,
        resolveScope?.(req)
      );

      await server.services.auditLog.createAuditLog({
        ...req.auditLogInfo,
        orgId: req.permission.orgId,
        projectId: appConnection.projectId ?? undefined,
        event: {
          type: EventType.GET_APP_CONNECTION,
          metadata: {
            connectionId
          }
        }
      });

      return { appConnection };
    }
  });
};

export const buildGetAppConnectionByNameRoute = (
  { server, app, appName, appNameForOpId, sanitizedResponseSchema, tags }: TAppConnectionRouteContext,
  {
    description = `Get the specified ${appName} Connection by name.`,
    resolveScope
  }: { description?: string; resolveScope?: TResolveScope } = {}
) => {
  server.route({
    method: "GET",
    url: `/connection-name/:connectionName`,
    config: {
      rateLimit: readLimit
    },
    schema: {
      hide: false,
      operationId: `get${appNameForOpId}AppConnectionByName`,
      tags,
      description,
      params: z.object({
        connectionName: z
          .string()
          .trim()
          .min(1, "Connection name required")
          .describe(AppConnections.GET_BY_NAME(app).connectionName)
      }),
      ...(!resolveScope && {
        querystring: z.object({
          projectId: z.string().trim().optional().describe(AppConnections.GET_BY_NAME(app).projectId)
        })
      }),
      response: {
        200: z.object({ appConnection: sanitizedResponseSchema })
      }
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
    handler: async (req) => {
      const { connectionName } = req.params;
      const projectId = resolveScope ? resolveScope(req).projectId : (req.query as { projectId?: string }).projectId;

      const appConnection = await server.services.appConnection.findAppConnectionByName(
        app,
        {
          connectionName,
          projectId
        },
        req.permission
      );

      await server.services.auditLog.createAuditLog({
        ...req.auditLogInfo,
        orgId: req.permission.orgId,
        projectId: appConnection.projectId ?? undefined,
        event: {
          type: EventType.GET_APP_CONNECTION,
          metadata: {
            connectionId: appConnection.id
          }
        }
      });

      return { appConnection };
    }
  });
};

export const buildCreateAppConnectionRoute = <I extends TAppConnectionInput>(
  { server, app, appName, appNameForOpId, sanitizedResponseSchema, tags }: TAppConnectionRouteContext,
  {
    createSchema,
    description = `Create ${startsWithVowel(appName) ? "an" : "a"} ${appName} Connection.`,
    resolveScope
  }: { createSchema: TAppConnectionCreateSchema<I>; description?: string; resolveScope?: TResolveScope }
) => {
  server.route({
    method: "POST",
    url: "/",
    config: {
      rateLimit: writeLimit
    },
    schema: {
      hide: false,
      operationId: `create${appNameForOpId}AppConnection`,
      tags,
      description,
      body: createSchema,
      response: {
        200: z.object({ appConnection: sanitizedResponseSchema })
      }
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
    handler: async (req) => {
      const {
        name,
        method,
        credentials,
        description: connectionDescription,
        isPlatformManagedCredentials,
        gatewayId,
        gatewayPoolId,
        isAutoRotationEnabled,
        rotation,
        configuration
      } = req.body;
      const projectId = resolveScope ? resolveScope(req).projectId : req.body.projectId;

      const appConnection = await server.services.appConnection.createAppConnection(
        {
          name,
          method,
          app,
          credentials,
          description: connectionDescription,
          isPlatformManagedCredentials,
          gatewayId,
          gatewayPoolId,
          projectId,
          rotation,
          isAutoRotationEnabled: isAutoRotationEnabled ?? false,
          configuration
        },
        req.permission
      );

      await server.services.auditLog.createAuditLog({
        ...req.auditLogInfo,
        orgId: req.permission.orgId,
        projectId,
        event: {
          type: EventType.CREATE_APP_CONNECTION,
          metadata: {
            name,
            method,
            app,
            connectionId: appConnection.id,
            isPlatformManagedCredentials
          }
        }
      });

      void server.services.telemetry
        .sendPostHogEvents({
          event: PostHogEventTypes.AppConnectionCreated,
          distinctId: getTelemetryDistinctId(req),
          organizationId: req.permission.orgId,
          properties: {
            appConnectionId: appConnection.id,
            app,
            method: method as string
          }
        })
        .catch((err) => logger.error(err, "Failed to send AppConnectionCreated telemetry event"));

      return { appConnection };
    }
  });
};

export const buildUpdateAppConnectionRoute = <I extends TAppConnectionInput>(
  ctx: TAppConnectionRouteContext,
  {
    updateSchema,
    description = `Update the specified ${ctx.appName} Connection.`,
    resolveScope
  }: { updateSchema: TAppConnectionUpdateSchema<I>; description?: string; resolveScope?: TResolveScope }
) => {
  const { server, app, appNameForOpId, sanitizedResponseSchema, tags } = ctx;
  server.route({
    method: "PATCH",
    url: "/:connectionId",
    config: {
      rateLimit: writeLimit
    },
    schema: {
      hide: false,
      operationId: `update${appNameForOpId}AppConnection`,
      tags,
      description,
      params: z.object({
        connectionId: z.string().uuid().describe(AppConnections.UPDATE(app).connectionId)
      }),
      body: updateSchema,
      response: {
        200: z.object({ appConnection: sanitizedResponseSchema })
      }
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
    handler: async (req) => {
      const {
        name,
        credentials,
        description: connectionDescription,
        isPlatformManagedCredentials,
        gatewayId,
        gatewayPoolId,
        rotation,
        isAutoRotationEnabled,
        configuration
      } = req.body;
      const { connectionId } = req.params;

      const appConnection = await server.services.appConnection.updateAppConnection(
        app,
        {
          name,
          credentials,
          connectionId,
          description: connectionDescription,
          isPlatformManagedCredentials,
          gatewayId,
          gatewayPoolId,
          isAutoRotationEnabled: isAutoRotationEnabled ?? undefined,
          rotation: rotation ?? undefined,
          configuration
        },
        req.permission,
        resolveScope?.(req)
      );

      await server.services.auditLog.createAuditLog({
        ...req.auditLogInfo,
        orgId: req.permission.orgId,
        projectId: appConnection.projectId ?? undefined,
        event: {
          type: EventType.UPDATE_APP_CONNECTION,
          metadata: {
            name,
            description: connectionDescription,
            credentialsUpdated: Boolean(credentials),
            connectionId,
            isPlatformManagedCredentials
          }
        }
      });

      void server.services.telemetry
        .sendPostHogEvents({
          event: PostHogEventTypes.AppConnectionUpdated,
          distinctId: getTelemetryDistinctId(req),
          organizationId: req.permission.orgId,
          properties: { appConnectionId: connectionId, app }
        })
        .catch(() => {});

      return { appConnection };
    }
  });
};

export const buildDeleteAppConnectionRoute = (
  ctx: TAppConnectionRouteContext,
  {
    description = `Delete the specified ${ctx.appName} Connection.`,
    resolveScope
  }: { description?: string; resolveScope?: TResolveScope } = {}
) => {
  const { server, app, appNameForOpId, sanitizedResponseSchema, tags } = ctx;
  server.route({
    method: "DELETE",
    url: `/:connectionId`,
    config: {
      rateLimit: writeLimit
    },
    schema: {
      hide: false,
      operationId: `delete${appNameForOpId}AppConnection`,
      tags,
      description,
      params: z.object({
        connectionId: z.string().uuid().describe(AppConnections.DELETE(app).connectionId)
      }),
      response: {
        200: z.object({ appConnection: sanitizedResponseSchema })
      }
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
    handler: async (req) => {
      const { connectionId } = req.params;

      const appConnection = await server.services.appConnection.deleteAppConnection(
        app,
        connectionId,
        req.permission,
        resolveScope?.(req)
      );

      await server.services.auditLog.createAuditLog({
        ...req.auditLogInfo,
        orgId: req.permission.orgId,
        projectId: appConnection.projectId ?? undefined,
        event: {
          type: EventType.DELETE_APP_CONNECTION,
          metadata: {
            connectionId
          }
        }
      });

      void server.services.telemetry
        .sendPostHogEvents({
          event: PostHogEventTypes.AppConnectionDeleted,
          distinctId: getTelemetryDistinctId(req),
          organizationId: req.permission.orgId,
          properties: {
            appConnectionId: connectionId,
            app
          }
        })
        .catch((err) => logger.error(err, "Failed to send AppConnectionDeleted telemetry event"));

      return { appConnection };
    }
  });
};

export const buildRotateAppConnectionCredentialsRoute = (
  ctx: TAppConnectionRouteContext,
  {
    description = `Rotate the credentials for the specified ${ctx.appName} Connection.`,
    resolveScope
  }: { description?: string; resolveScope?: TResolveScope } = {}
) => {
  const { server, app, appNameForOpId, sanitizedResponseSchema, tags } = ctx;
  server.route({
    method: "POST",
    url: "/:connectionId/rotate-credentials",
    config: {
      rateLimit: writeLimit
    },
    schema: {
      hide: false,
      operationId: `rotate${appNameForOpId}AppConnectionCredentials`,
      tags,
      description,
      params: z.object({
        connectionId: z.string().uuid().describe(AppConnections.ROTATE_CREDENTIALS(app).connectionId)
      }),
      response: {
        200: z.object({ appConnection: sanitizedResponseSchema })
      }
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
    handler: async (req) => {
      const { connectionId } = req.params;

      await server.services.appConnection.triggerCredentialRotation(
        { app, connectionId },
        req.permission,
        resolveScope?.(req)
      );

      const appConnection = await server.services.appConnection.findAppConnectionById(
        app,
        connectionId,
        req.permission,
        resolveScope?.(req)
      );

      await server.services.auditLog.createAuditLog({
        ...req.auditLogInfo,
        orgId: req.permission.orgId,
        projectId: appConnection.projectId ?? undefined,
        event: {
          type: EventType.ROTATE_APP_CONNECTION_CREDENTIALS,
          metadata: {
            connectionId
          }
        }
      });

      return { appConnection };
    }
  });
};

export const registerAppConnectionEndpoints = <I extends TAppConnectionInput>({
  server,
  app,
  createSchema,
  updateSchema,
  sanitizedResponseSchema
}: {
  app: AppConnection;
  server: FastifyZodProvider;
  createSchema: TAppConnectionCreateSchema<I>;
  updateSchema: TAppConnectionUpdateSchema<I>;
  sanitizedResponseSchema: z.ZodTypeAny;
}) => {
  const ctx = buildAppConnectionRouteContext({ server, app, sanitizedResponseSchema });

  buildListAppConnectionsRoute(ctx);
  buildListAvailableAppConnectionsRoute(ctx);
  buildGetAppConnectionRoute(ctx);
  buildGetAppConnectionByNameRoute(ctx);
  buildCreateAppConnectionRoute(ctx, { createSchema });
  buildUpdateAppConnectionRoute(ctx, { updateSchema });
  buildDeleteAppConnectionRoute(ctx);
  buildRotateAppConnectionCredentialsRoute(ctx);

  // scott: we will need this once we have individual app connection page and may want to expose to API
  // server.route({
  //   method: "GET",
  //   url: `/:connectionId/usage`,
  //   config: {
  //     rateLimit: readLimit
  //   },
  //   schema: {
  //     hide: true, // scott: we could expose this in the future but just for UI right now
  //     tags: [ApiDocsTags.AppConnections],
  //     params: z.object({
  //       connectionId: z.string().uuid()
  //     }),
  //     response: {
  //       200: z.object({
  //         projects: z
  //           .object({
  //             id: z.string(),
  //             name: z.string(),
  //             type: z.nativeEnum(ProjectType),
  //             slug: z.string(),
  //             resources: z.object({
  //               secretSyncs: z
  //                 .object({
  //                   id: z.string(),
  //                   name: z.string()
  //                 })
  //                 .array(),
  //               secretRotations: z
  //                 .object({
  //                   id: z.string(),
  //                   name: z.string()
  //                 })
  //                 .array(),
  //               externalCas: z
  //                 .object({
  //                   id: z.string(),
  //                   name: z.string()
  //                 })
  //                 .array(),
  //               dataSources: z
  //                 .object({
  //                   id: z.string(),
  //                   name: z.string()
  //                 })
  //                 .array()
  //             })
  //           })
  //           .array()
  //       })
  //     }
  //   },
  //   onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
  //   handler: async (req) => {
  //     const { connectionId } = req.params;
  //
  //     const projects = await server.services.appConnection.findAppConnectionUsageById(
  //       app,
  //       connectionId,
  //       req.permission
  //     );
  //
  //     await server.services.auditLog.createAuditLog({
  //       ...req.auditLogInfo,
  //       orgId: req.permission.orgId,
  //       event: {
  //         type: EventType.GET_APP_CONNECTION_USAGE,
  //         metadata: {
  //           connectionId
  //         }
  //       }
  //     });
  //
  //     return { projects };
  //   }
  // });
};