Skip to content

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

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

import { IdentityAuthMethod, IdentityKubernetesAuthsSchema } from "@app/db/schemas";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { ApiDocsTags, KUBERNETES_AUTH } from "@app/lib/api-docs";
import { UnauthorizedError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { slugSchema } from "@app/server/lib/schemas";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { ActorType, AuthMode } from "@app/services/auth/auth-type";
import { IdentityKubernetesAuthTokenReviewMode } from "@app/services/identity-kubernetes-auth/identity-kubernetes-auth-types";
import {
  kubernetesHostSchema,
  rejectTemplateManagedKubernetesFields,
  superRefineKubernetesConnectionFields
} from "@app/services/identity-kubernetes-auth/identity-kubernetes-auth-validators";
import { TIdentityTrustedIp } from "@app/services/identity/identity-types";
import { isSuperAdmin } from "@app/services/super-admin/super-admin-fns";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";

const IdentityKubernetesAuthResponseSchema = IdentityKubernetesAuthsSchema.pick({
  id: true,
  accessTokenTTL: true,
  accessTokenMaxTTL: true,
  accessTokenNumUsesLimit: true,
  accessTokenTrustedIps: true,
  createdAt: true,
  updatedAt: true,
  tokenReviewMode: true,
  identityId: true,
  kubernetesHost: true,
  allowedNamespaces: true,
  allowedNames: true,
  allowedAudience: true,
  gatewayPoolId: true,
  verifyTlsCertificate: true,
  templateId: true,
  // template-sourced JWTs read back as "" (write-only), so this flag is the only way a
  // client can tell "no stored JWT" from "hidden JWT that must be kept, replaced, or
  // explicitly cleared with tokenReviewerJwt: null"
  isTokenReviewerJwtTemplateSourced: true
}).extend({
  caCert: z.string(),
  tokenReviewerJwt: z.string().optional().nullable(),
  // declared rather than picked: the row's own gatewayId is the retired v1 column, and the
  // service fills this field from gatewayV2Id so the API name stays unchanged
  gatewayId: z.string().uuid().optional().nullable()
});

export const registerIdentityKubernetesRouter = async (server: FastifyZodProvider) => {
  server.route({
    method: "POST",
    url: "/kubernetes-auth/login",
    config: {
      rateLimit: writeLimit
    },
    schema: {
      hide: false,
      operationId: "loginWithKubernetesAuth",
      tags: [ApiDocsTags.KubernetesAuth],
      description: "Login with Kubernetes Auth for machine identity",
      body: z.object({
        identityId: z.string().trim().describe(KUBERNETES_AUTH.LOGIN.identityId),
        jwt: z.string().trim(),
        organizationSlug: slugSchema().optional().describe(KUBERNETES_AUTH.LOGIN.organizationSlug)
      }),
      response: {
        200: z.object({
          accessToken: z.string(),
          expiresIn: z.coerce.number(),
          accessTokenMaxTTL: z.coerce.number(),
          tokenType: z.literal("Bearer")
        })
      }
    },
    handler: async (req) => {
      try {
        const { identityKubernetesAuth, accessToken, identityAccessToken, identity } =
          await server.services.identityKubernetesAuth.login(req.body);

        await server.services.auditLog.createAuditLog({
          ...req.auditLogInfo,
          actor: {
            type: ActorType.IDENTITY,
            metadata: {
              identityId: identityKubernetesAuth.identityId,
              name: identity.name
            }
          },
          orgId: identity.orgId,
          event: {
            type: EventType.LOGIN_IDENTITY_KUBERNETES_AUTH,
            metadata: {
              identityId: identityKubernetesAuth.identityId,
              identityAccessTokenId: identityAccessToken.id,
              identityKubernetesAuthId: identityKubernetesAuth.id
            }
          }
        });

        void server.services.telemetry
          .sendPostHogEvents({
            event: PostHogEventTypes.MachineIdentityLogin,
            distinctId: `identity-${identityKubernetesAuth.identityId}`,
            organizationId: identity.orgId,
            properties: {
              identityId: identityKubernetesAuth.identityId,
              orgId: identity.orgId,
              authMethod: IdentityAuthMethod.KUBERNETES_AUTH
            }
          })
          .catch((error) => {
            logger.error(error, `Failed to send telemetry event [identityId=${identityKubernetesAuth.identityId}]`);
          });

        return {
          accessToken,
          tokenType: "Bearer" as const,
          expiresIn: identityKubernetesAuth.accessTokenTTL,
          accessTokenMaxTTL: identityKubernetesAuth.accessTokenMaxTTL
        };
      } catch (error) {
        if (
          error instanceof UnauthorizedError &&
          error.detail?.orgId &&
          error.detail?.identityId &&
          error.detail?.identityName
        ) {
          await server.services.auditLog.createAuditLog({
            ...req.auditLogInfo,
            actor: {
              type: ActorType.IDENTITY,
              metadata: {
                identityId: error.detail.identityId as string,
                name: error.detail.identityName as string
              }
            },
            orgId: error.detail.orgId as string,
            event: {
              type: EventType.LOGIN_IDENTITY_KUBERNETES_AUTH_FAILED,
              metadata: {
                identityId: error.detail.identityId as string,
                reasonCode: error.detail.reasonCode as string,
                message: error.message
              }
            }
          });
        }
        throw error;
      }
    }
  });

  server.route({
    method: "POST",
    url: "/kubernetes-auth/identities/:identityId",
    config: {
      rateLimit: writeLimit
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
    schema: {
      hide: false,
      operationId: "attachKubernetesAuth",
      tags: [ApiDocsTags.KubernetesAuth],
      description: "Attach Kubernetes Auth configuration onto machine identity",
      security: [
        {
          bearerAuth: []
        }
      ],
      params: z.object({
        identityId: z.string().trim().describe(KUBERNETES_AUTH.ATTACH.identityId)
      }),
      body: z
        .object({
          templateId: z.string().uuid().optional().describe(KUBERNETES_AUTH.ATTACH.templateId),
          kubernetesHost: kubernetesHostSchema.nullish().describe(KUBERNETES_AUTH.ATTACH.kubernetesHost),
          caCert: z.string().trim().optional().describe(KUBERNETES_AUTH.ATTACH.caCert),
          verifyTlsCertificate: z.boolean().optional().describe(KUBERNETES_AUTH.ATTACH.verifyTlsCertificate),
          tokenReviewerJwt: z.string().trim().optional().describe(KUBERNETES_AUTH.ATTACH.tokenReviewerJwt),
          // no zod defaults on tokenReviewMode/allowedAudience: a default would make them
          // indistinguishable from caller-supplied values, so template attaches could not
          // reject them; the service defaults them (api / "") on the custom path
          tokenReviewMode: z
            .nativeEnum(IdentityKubernetesAuthTokenReviewMode)
            .optional()
            .describe(KUBERNETES_AUTH.ATTACH.tokenReviewMode),
          allowedNamespaces: z.string().describe(KUBERNETES_AUTH.ATTACH.allowedNamespaces), // TODO: validation
          allowedNames: z.string().describe(KUBERNETES_AUTH.ATTACH.allowedNames),
          allowedAudience: z.string().trim().max(1000).optional().describe(KUBERNETES_AUTH.ATTACH.allowedAudience),
          gatewayId: z.string().uuid().optional().nullable().describe(KUBERNETES_AUTH.ATTACH.gatewayId),
          gatewayPoolId: z.string().uuid().optional().nullable(),
          accessTokenTrustedIps: z
            .object({
              ipAddress: z.string().trim()
            })
            .array()
            .min(1)
            .default([{ ipAddress: "0.0.0.0/0" }, { ipAddress: "::/0" }])
            .describe(KUBERNETES_AUTH.ATTACH.accessTokenTrustedIps),
          accessTokenTTL: z
            .number()
            .int()
            .min(0)
            .max(315360000)
            .default(2592000)
            .describe(KUBERNETES_AUTH.ATTACH.accessTokenTTL),
          accessTokenMaxTTL: z
            .number()
            .int()
            .min(0)
            .max(315360000)
            .default(2592000)
            .describe(KUBERNETES_AUTH.ATTACH.accessTokenMaxTTL),
          accessTokenNumUsesLimit: z
            .number()
            .int()
            .min(0)
            .default(0)
            .describe(KUBERNETES_AUTH.ATTACH.accessTokenNumUsesLimit)
        })
        .superRefine((data, ctx) => {
          if (data.templateId) {
            rejectTemplateManagedKubernetesFields(data, ctx);
          } else {
            superRefineKubernetesConnectionFields(data, ctx);
          }

          if (data.accessTokenTTL > data.accessTokenMaxTTL) {
            ctx.addIssue({
              path: ["accessTokenTTL"],
              code: z.ZodIssueCode.custom,
              message: "Access Token TTL cannot be greater than Access Token Max TTL."
            });
          }
        }),
      response: {
        200: z.object({
          identityKubernetesAuth: IdentityKubernetesAuthResponseSchema
        })
      }
    },
    handler: async (req) => {
      const identityKubernetesAuth = await server.services.identityKubernetesAuth.attachKubernetesAuth({
        actor: req.permission.type,
        actorId: req.permission.id,
        actorAuthMethod: req.permission.authMethod,
        actorOrgId: req.permission.orgId,
        ...req.body,
        identityId: req.params.identityId,
        isActorSuperAdmin: isSuperAdmin(req.auth)
      });

      await server.services.auditLog.createAuditLog({
        ...req.auditLogInfo,
        orgId: identityKubernetesAuth.orgId,
        event: {
          type: EventType.ADD_IDENTITY_KUBERNETES_AUTH,
          metadata: {
            identityId: identityKubernetesAuth.identityId,
            templateId: identityKubernetesAuth.templateId,
            kubernetesHost: identityKubernetesAuth.kubernetesHost ?? "",
            allowedNamespaces: identityKubernetesAuth.allowedNamespaces,
            allowedNames: identityKubernetesAuth.allowedNames,
            accessTokenTTL: identityKubernetesAuth.accessTokenTTL,
            accessTokenMaxTTL: identityKubernetesAuth.accessTokenMaxTTL,
            accessTokenTrustedIps: identityKubernetesAuth.accessTokenTrustedIps as TIdentityTrustedIp[],
            accessTokenNumUsesLimit: identityKubernetesAuth.accessTokenNumUsesLimit
          }
        }
      });

      void server.services.telemetry
        .sendPostHogEvents({
          event: PostHogEventTypes.MachineIdentityAuthMethodAttached,
          distinctId: getTelemetryDistinctId(req),
          organizationId: identityKubernetesAuth.orgId,
          properties: {
            identityId: identityKubernetesAuth.identityId,
            orgId: identityKubernetesAuth.orgId,
            authMethod: IdentityAuthMethod.KUBERNETES_AUTH
          }
        })
        .catch((error) => {
          logger.error(error, `Failed to send telemetry event [identityId=${identityKubernetesAuth.identityId}]`);
        });

      return { identityKubernetesAuth: IdentityKubernetesAuthResponseSchema.parse(identityKubernetesAuth) };
    }
  });

  server.route({
    method: "PATCH",
    url: "/kubernetes-auth/identities/:identityId",
    config: {
      rateLimit: writeLimit
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
    schema: {
      hide: false,
      operationId: "updateKubernetesAuth",
      tags: [ApiDocsTags.KubernetesAuth],
      description: "Update Kubernetes Auth configuration on machine identity",
      security: [
        {
          bearerAuth: []
        }
      ],
      params: z.object({
        identityId: z.string().describe(KUBERNETES_AUTH.UPDATE.identityId)
      }),
      body: z
        .object({
          templateId: z.string().uuid().nullable().optional().describe(KUBERNETES_AUTH.UPDATE.templateId),
          kubernetesHost: kubernetesHostSchema.nullish().describe(KUBERNETES_AUTH.UPDATE.kubernetesHost),
          caCert: z.string().trim().optional().describe(KUBERNETES_AUTH.UPDATE.caCert),
          verifyTlsCertificate: z.boolean().optional().describe(KUBERNETES_AUTH.UPDATE.verifyTlsCertificate),
          tokenReviewerJwt: z.string().trim().nullable().optional().describe(KUBERNETES_AUTH.UPDATE.tokenReviewerJwt),
          tokenReviewMode: z
            .nativeEnum(IdentityKubernetesAuthTokenReviewMode)
            .optional()
            .describe(KUBERNETES_AUTH.UPDATE.tokenReviewMode),
          allowedNamespaces: z.string().optional().describe(KUBERNETES_AUTH.UPDATE.allowedNamespaces), // TODO: validation
          allowedNames: z.string().optional().describe(KUBERNETES_AUTH.UPDATE.allowedNames),
          allowedAudience: z.string().trim().max(1000).optional().describe(KUBERNETES_AUTH.UPDATE.allowedAudience),
          gatewayId: z.string().uuid().optional().nullable().describe(KUBERNETES_AUTH.UPDATE.gatewayId),
          gatewayPoolId: z.string().uuid().optional().nullable(),
          accessTokenTrustedIps: z
            .object({
              ipAddress: z.string().trim()
            })
            .array()
            .min(1)
            .optional()
            .describe(KUBERNETES_AUTH.UPDATE.accessTokenTrustedIps),
          accessTokenTTL: z
            .number()
            .int()
            .min(0)
            .max(315360000)
            .optional()
            .describe(KUBERNETES_AUTH.UPDATE.accessTokenTTL),
          accessTokenNumUsesLimit: z
            .number()
            .int()
            .min(0)
            .optional()
            .describe(KUBERNETES_AUTH.UPDATE.accessTokenNumUsesLimit),
          accessTokenMaxTTL: z
            .number()
            .int()
            .min(0)
            .max(315360000)
            .optional()
            .describe(KUBERNETES_AUTH.UPDATE.accessTokenMaxTTL)
        })
        .superRefine((data, ctx) => {
          if (data.templateId) {
            rejectTemplateManagedKubernetesFields(data, ctx);
          } else {
            if (
              data.tokenReviewMode &&
              data.tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Gateway &&
              !data.gatewayId &&
              !data.gatewayPoolId
            ) {
              ctx.addIssue({
                path: ["gatewayId"],
                code: z.ZodIssueCode.custom,
                message: "When token review mode is set to Gateway, a gateway or gateway pool must be selected"
              });
            }
            if (data.gatewayId && data.gatewayPoolId) {
              ctx.addIssue({
                path: ["gatewayPoolId"],
                code: z.ZodIssueCode.custom,
                message: "Cannot specify both a gateway and a gateway pool"
              });
            }
          }
          if (data.accessTokenMaxTTL && data.accessTokenTTL ? data.accessTokenTTL > data.accessTokenMaxTTL : false) {
            ctx.addIssue({
              path: ["accessTokenTTL"],
              code: z.ZodIssueCode.custom,
              message: "Access Token TTL cannot be greater than Access Token Max TTL."
            });
          }
        }),
      response: {
        200: z.object({
          identityKubernetesAuth: IdentityKubernetesAuthResponseSchema
        })
      }
    },
    handler: async (req) => {
      const identityKubernetesAuth = await server.services.identityKubernetesAuth.updateKubernetesAuth({
        actor: req.permission.type,
        actorId: req.permission.id,
        actorAuthMethod: req.permission.authMethod,
        actorOrgId: req.permission.orgId,
        ...req.body,
        identityId: req.params.identityId,
        isActorSuperAdmin: isSuperAdmin(req.auth)
      });

      await server.services.auditLog.createAuditLog({
        ...req.auditLogInfo,
        orgId: identityKubernetesAuth.orgId,
        event: {
          type: EventType.UPDATE_IDENTITY_KUBENETES_AUTH,
          metadata: {
            identityId: identityKubernetesAuth.identityId,
            templateId: identityKubernetesAuth.templateId,
            kubernetesHost: identityKubernetesAuth.kubernetesHost ?? "",
            allowedNamespaces: identityKubernetesAuth.allowedNamespaces,
            allowedNames: identityKubernetesAuth.allowedNames,
            accessTokenTTL: identityKubernetesAuth.accessTokenTTL,
            accessTokenMaxTTL: identityKubernetesAuth.accessTokenMaxTTL,
            accessTokenTrustedIps: identityKubernetesAuth.accessTokenTrustedIps as TIdentityTrustedIp[],
            accessTokenNumUsesLimit: identityKubernetesAuth.accessTokenNumUsesLimit
          }
        }
      });

      void server.services.telemetry
        .sendPostHogEvents({
          event: PostHogEventTypes.MachineIdentityAuthMethodUpdated,
          distinctId: getTelemetryDistinctId(req),
          organizationId: identityKubernetesAuth.orgId,
          properties: {
            identityId: identityKubernetesAuth.identityId,
            orgId: identityKubernetesAuth.orgId,
            authMethod: IdentityAuthMethod.KUBERNETES_AUTH
          }
        })
        .catch((error) => {
          logger.error(error, `Failed to send telemetry event [identityId=${identityKubernetesAuth.identityId}]`);
        });

      return { identityKubernetesAuth };
    }
  });

  server.route({
    method: "GET",
    url: "/kubernetes-auth/identities/:identityId",
    config: {
      rateLimit: readLimit
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
    schema: {
      hide: false,
      operationId: "getKubernetesAuth",
      tags: [ApiDocsTags.KubernetesAuth],
      description: "Retrieve Kubernetes Auth configuration on machine identity",
      security: [
        {
          bearerAuth: []
        }
      ],
      params: z.object({
        identityId: z.string().describe(KUBERNETES_AUTH.RETRIEVE.identityId)
      }),
      response: {
        200: z.object({
          identityKubernetesAuth: IdentityKubernetesAuthResponseSchema
        })
      }
    },
    handler: async (req) => {
      const identityKubernetesAuth = await server.services.identityKubernetesAuth.getKubernetesAuth({
        identityId: req.params.identityId,
        actor: req.permission.type,
        actorId: req.permission.id,
        actorOrgId: req.permission.orgId,
        actorAuthMethod: req.permission.authMethod
      });

      await server.services.auditLog.createAuditLog({
        ...req.auditLogInfo,
        orgId: identityKubernetesAuth.orgId,
        event: {
          type: EventType.GET_IDENTITY_KUBERNETES_AUTH,
          metadata: {
            identityId: identityKubernetesAuth.identityId
          }
        }
      });

      return { identityKubernetesAuth: IdentityKubernetesAuthResponseSchema.parse(identityKubernetesAuth) };
    }
  });

  server.route({
    method: "DELETE",
    url: "/kubernetes-auth/identities/:identityId",
    config: {
      rateLimit: writeLimit
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
    schema: {
      hide: false,
      operationId: "deleteKubernetesAuth",
      tags: [ApiDocsTags.KubernetesAuth],
      description: "Delete Kubernetes Auth configuration on machine identity",
      security: [
        {
          bearerAuth: []
        }
      ],
      params: z.object({
        identityId: z.string().describe(KUBERNETES_AUTH.REVOKE.identityId)
      }),
      response: {
        200: z.object({
          identityKubernetesAuth: IdentityKubernetesAuthResponseSchema.omit({
            caCert: true,
            tokenReviewerJwt: true
          })
        })
      }
    },
    handler: async (req) => {
      const identityKubernetesAuth = await server.services.identityKubernetesAuth.revokeIdentityKubernetesAuth({
        actor: req.permission.type,
        actorId: req.permission.id,
        actorAuthMethod: req.permission.authMethod,
        actorOrgId: req.permission.orgId,
        identityId: req.params.identityId,
        isActorSuperAdmin: isSuperAdmin(req.auth)
      });

      await server.services.auditLog.createAuditLog({
        ...req.auditLogInfo,
        orgId: identityKubernetesAuth.orgId,
        event: {
          type: EventType.REVOKE_IDENTITY_KUBERNETES_AUTH,
          metadata: {
            identityId: identityKubernetesAuth.identityId
          }
        }
      });

      void server.services.telemetry
        .sendPostHogEvents({
          event: PostHogEventTypes.MachineIdentityAuthMethodRevoked,
          distinctId: getTelemetryDistinctId(req),
          organizationId: identityKubernetesAuth.orgId,
          properties: {
            identityId: identityKubernetesAuth.identityId,
            orgId: identityKubernetesAuth.orgId,
            authMethod: IdentityAuthMethod.KUBERNETES_AUTH
          }
        })
        .catch((error) => {
          logger.error(error, `Failed to send telemetry event [identityId=${identityKubernetesAuth.identityId}]`);
        });

      return { identityKubernetesAuth };
    }
  });
};