Skip to content

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

6.2 KB
Raw Blame
import { z } from "zod";

import { GithubOrgSyncConfigsSchema } from "@app/db/schemas";
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 { AuthMode } from "@app/services/auth/auth-type";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";

import { GithubOrgNameCreateSchema, GithubOrgNamePatchSchema } from "./github-org-sync-schema";

const SanitizedGithubOrgSyncSchema = GithubOrgSyncConfigsSchema.pick({
  isActive: true,
  id: true,
  createdAt: true,
  updatedAt: true,
  orgId: true,
  githubOrgName: true
});

export const registerGithubOrgSyncRouter = async (server: FastifyZodProvider) => {
  server.route({
    url: "/",
    method: "POST",
    config: {
      rateLimit: writeLimit
    },
    onRequest: verifyAuth([AuthMode.JWT]),
    schema: {
      operationId: "createGithubOrgSyncConfig",
      body: z.object({
        githubOrgName: GithubOrgNameCreateSchema,
        githubOrgAccessToken: z.string().trim().max(1000).optional(),
        isActive: z.boolean().default(false)
      }),
      response: {
        200: z.object({
          githubOrgSyncConfig: SanitizedGithubOrgSyncSchema
        })
      }
    },
    handler: async (req) => {
      const githubOrgSyncConfig = await server.services.githubOrgSync.createGithubOrgSync({
        orgPermission: req.permission,
        githubOrgName: req.body.githubOrgName,
        githubOrgAccessToken: req.body.githubOrgAccessToken,
        isActive: req.body.isActive
      });

      void server.services.telemetry
        .sendPostHogEvents({
          event: PostHogEventTypes.GitHubOrgSyncConfigured,
          distinctId: getTelemetryDistinctId(req),
          organizationId: req.permission.orgId,
          properties: { githubOrgName: req.body.githubOrgName, isActive: req.body.isActive }
        })
        .catch(() => {});

      return { githubOrgSyncConfig };
    }
  });

  server.route({
    url: "/",
    method: "PATCH",
    config: {
      rateLimit: writeLimit
    },
    onRequest: verifyAuth([AuthMode.JWT]),
    schema: {
      operationId: "updateGithubOrgSyncConfig",
      body: z
        .object({
          githubOrgName: GithubOrgNamePatchSchema,
          githubOrgAccessToken: z.string().trim().max(1000),
          isActive: z.boolean()
        })
        .partial(),
      response: {
        200: z.object({
          githubOrgSyncConfig: SanitizedGithubOrgSyncSchema
        })
      }
    },
    handler: async (req) => {
      const githubOrgSyncConfig = await server.services.githubOrgSync.updateGithubOrgSync({
        orgPermission: req.permission,
        githubOrgName: req.body.githubOrgName,
        githubOrgAccessToken: req.body.githubOrgAccessToken,
        isActive: req.body.isActive
      });

      void server.services.telemetry
        .sendPostHogEvents({
          event: PostHogEventTypes.GitHubOrgSyncUpdated,
          distinctId: getTelemetryDistinctId(req),
          organizationId: req.permission.orgId,
          properties: {
            githubOrgName: githubOrgSyncConfig.githubOrgName,
            isActive: githubOrgSyncConfig.isActive ?? undefined
          }
        })
        .catch(() => {});

      return { githubOrgSyncConfig };
    }
  });

  server.route({
    url: "/",
    method: "DELETE",
    config: {
      rateLimit: writeLimit
    },
    onRequest: verifyAuth([AuthMode.JWT]),
    schema: {
      operationId: "deleteGithubOrgSyncConfig",
      response: {
        200: z.object({
          githubOrgSyncConfig: SanitizedGithubOrgSyncSchema
        })
      }
    },
    handler: async (req) => {
      const githubOrgSyncConfig = await server.services.githubOrgSync.deleteGithubOrgSync({
        orgPermission: req.permission
      });

      void server.services.telemetry
        .sendPostHogEvents({
          event: PostHogEventTypes.GitHubOrgSyncDeleted,
          distinctId: getTelemetryDistinctId(req),
          organizationId: req.permission.orgId,
          properties: {
            githubOrgName: githubOrgSyncConfig.githubOrgName
          }
        })
        .catch(() => {});

      return { githubOrgSyncConfig };
    }
  });

  server.route({
    url: "/",
    method: "GET",
    config: {
      rateLimit: readLimit
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),
    schema: {
      operationId: "getGithubOrgSyncConfig",
      response: {
        200: z.object({
          githubOrgSyncConfig: SanitizedGithubOrgSyncSchema
        })
      }
    },
    handler: async (req) => {
      const githubOrgSyncConfig = await server.services.githubOrgSync.getGithubOrgSync({
        orgPermission: req.permission
      });

      return { githubOrgSyncConfig };
    }
  });

  server.route({
    url: "/sync-all-teams",
    method: "POST",
    config: {
      rateLimit: writeLimit
    },
    onRequest: verifyAuth([AuthMode.JWT]),
    schema: {
      operationId: "syncAllGithubOrgTeams",
      response: {
        200: z.object({
          totalUsers: z.number(),
          errors: z.array(z.string()),
          createdTeams: z.array(z.string()),
          updatedTeams: z.array(z.string()),
          removedMemberships: z.number(),
          syncDuration: z.number()
        })
      }
    },
    handler: async (req) => {
      const result = await server.services.githubOrgSync.syncAllTeams({
        orgPermission: req.permission,
        auditLogInfo: req.auditLogInfo
      });

      void server.services.telemetry
        .sendPostHogEvents({
          event: PostHogEventTypes.GitHubOrgSyncExecuted,
          distinctId: getTelemetryDistinctId(req),
          organizationId: req.permission.orgId,
          properties: {
            totalUsers: result.totalUsers,
            createdTeams: result.createdTeams.length,
            updatedTeams: result.updatedTeams.length,
            syncDuration: result.syncDuration
          }
        })
        .catch(() => {});

      return {
        totalUsers: result.totalUsers,
        errors: result.errors,
        createdTeams: result.createdTeams,
        updatedTeams: result.updatedTeams,
        removedMemberships: result.removedMemberships,
        syncDuration: result.syncDuration
      };
    }
  });
};