Skip to content

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

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

import { IdentityAuthMethod, IdentityOidcAuthsSchema } from "@app/db/schemas";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { ApiDocsTags, OIDC_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 {
  rejectTemplateManagedOidcFields,
  validateOidcAuthAudiencesField,
  validateOidcAuthAudiencesFieldOptional,
  validateOidcBoundClaimsField
} from "@app/services/identity-oidc-auth/identity-oidc-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 IdentityOidcAuthResponseSchema = IdentityOidcAuthsSchema.pick({
  id: true,
  accessTokenTTL: true,
  accessTokenMaxTTL: true,
  accessTokenNumUsesLimit: true,
  accessTokenTrustedIps: true,
  identityId: true,
  oidcDiscoveryUrl: true,
  boundIssuer: true,
  boundAudiences: true,
  boundClaims: true,
  claimMetadataMapping: true,
  boundSubject: true,
  templateId: true,
  createdAt: true,
  updatedAt: true
}).extend({
  caCert: z.string()
});

const MAX_OIDC_CLAIM_SIZE = 32_768;

export const registerIdentityOidcAuthRouter = async (server: FastifyZodProvider) => {
  server.route({
    method: "POST",
    url: "/oidc-auth/login",
    config: {
      rateLimit: writeLimit
    },
    schema: {
      hide: false,
      operationId: "loginWithOidcAuth",
      tags: [ApiDocsTags.OidcAuth],
      description: "Login with OIDC Auth for machine identity",
      body: z.object({
        identityId: z.string().trim().describe(OIDC_AUTH.LOGIN.identityId),
        jwt: z.string().trim(),
        organizationSlug: slugSchema().optional().describe(OIDC_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 { identityOidcAuth, accessToken, identityAccessToken, identity, oidcTokenData } =
          await server.services.identityOidcAuth.login(req.body);

        await server.services.auditLog.createAuditLog({
          ...req.auditLogInfo,
          actor: {
            type: ActorType.IDENTITY,
            metadata: {
              identityId: identityOidcAuth.identityId,
              name: identity.name
            }
          },
          orgId: identity.orgId,
          event: {
            type: EventType.LOGIN_IDENTITY_OIDC_AUTH,
            metadata: {
              identityId: identityOidcAuth.identityId,
              identityAccessTokenId: identityAccessToken.id,
              identityOidcAuthId: identityOidcAuth.id,
              oidcClaimsReceived:
                Buffer.from(JSON.stringify(oidcTokenData), "utf8").byteLength < MAX_OIDC_CLAIM_SIZE
                  ? oidcTokenData
                  : { payload: "Error: Payload exceeds 32KB, provided oidc claim not recorded in audit log." }
            }
          }
        });

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

        return {
          accessToken,
          tokenType: "Bearer" as const,
          expiresIn: identityOidcAuth.accessTokenTTL,
          accessTokenMaxTTL: identityOidcAuth.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_OIDC_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: "/oidc-auth/identities/:identityId",
    config: {
      rateLimit: writeLimit
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
    schema: {
      hide: false,
      operationId: "attachOidcAuth",
      tags: [ApiDocsTags.OidcAuth],
      description: "Attach OIDC Auth configuration onto machine identity",
      security: [
        {
          bearerAuth: []
        }
      ],
      params: z.object({
        identityId: z.string().trim().describe(OIDC_AUTH.ATTACH.identityId)
      }),
      body: z
        .object({
          templateId: z.string().uuid().optional().describe(OIDC_AUTH.ATTACH.templateId),
          // no zod defaults on the template-managed fields: a default would make them
          // indistinguishable from caller-supplied values, so template attaches could not
          // reject them; the service defaults them on the custom path
          oidcDiscoveryUrl: z.string().url().min(1).optional().describe(OIDC_AUTH.ATTACH.oidcDiscoveryUrl),
          caCert: z.string().trim().optional().describe(OIDC_AUTH.ATTACH.caCert),
          boundIssuer: z.string().min(1).optional().describe(OIDC_AUTH.ATTACH.boundIssuer),
          boundAudiences: validateOidcAuthAudiencesFieldOptional.describe(OIDC_AUTH.ATTACH.boundAudiences),
          boundClaims: validateOidcBoundClaimsField.describe(OIDC_AUTH.ATTACH.boundClaims),
          claimMetadataMapping: validateOidcBoundClaimsField.describe(OIDC_AUTH.ATTACH.claimMetadataMapping).optional(),
          boundSubject: z.string().optional().default("").describe(OIDC_AUTH.ATTACH.boundSubject),
          accessTokenTrustedIps: z
            .object({
              ipAddress: z.string().trim()
            })
            .array()
            .min(1)
            .default([{ ipAddress: "0.0.0.0/0" }, { ipAddress: "::/0" }])
            .describe(OIDC_AUTH.ATTACH.accessTokenTrustedIps),
          accessTokenTTL: z
            .number()
            .int()
            .min(0)
            .max(315360000)
            .default(2592000)
            .describe(OIDC_AUTH.ATTACH.accessTokenTTL),
          accessTokenMaxTTL: z
            .number()
            .int()
            .min(0)
            .max(315360000)
            .default(2592000)
            .describe(OIDC_AUTH.ATTACH.accessTokenMaxTTL),
          accessTokenNumUsesLimit: z.number().int().min(0).default(0).describe(OIDC_AUTH.ATTACH.accessTokenNumUsesLimit)
        })
        .superRefine((data, ctx) => {
          if (data.templateId) {
            rejectTemplateManagedOidcFields(data, ctx);
            // the template only pins the issuer; without a per-identity binding, any
            // token that issuer signs could authenticate as this identity
            if (!data.boundSubject && Object.keys(data.boundClaims ?? {}).length === 0) {
              ctx.addIssue({
                path: ["boundSubject"],
                code: z.ZodIssueCode.custom,
                message:
                  "When using an auth template, set a subject or at least one claim binding to restrict which workloads can authenticate as this identity."
              });
            }
          } else {
            if (data.oidcDiscoveryUrl === undefined) {
              ctx.addIssue({
                path: ["oidcDiscoveryUrl"],
                code: z.ZodIssueCode.custom,
                message: "OIDC discovery URL is required when not using an auth template"
              });
            }
            if (data.boundIssuer === undefined) {
              ctx.addIssue({
                path: ["boundIssuer"],
                code: z.ZodIssueCode.custom,
                message: "Issuer is required when not using an auth template"
              });
            }
          }

          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({
          identityOidcAuth: IdentityOidcAuthResponseSchema
        })
      }
    },
    handler: async (req) => {
      const identityOidcAuth = await server.services.identityOidcAuth.attachOidcAuth({
        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: identityOidcAuth.orgId,
        event: {
          type: EventType.ADD_IDENTITY_OIDC_AUTH,
          metadata: {
            identityId: identityOidcAuth.identityId,
            templateId: identityOidcAuth.templateId,
            templateName: identityOidcAuth.templateName,
            oidcDiscoveryUrl: identityOidcAuth.oidcDiscoveryUrl,
            caCert: identityOidcAuth.caCert,
            boundIssuer: identityOidcAuth.boundIssuer,
            boundAudiences: identityOidcAuth.boundAudiences,
            boundClaims: identityOidcAuth.boundClaims as Record<string, string>,
            claimMetadataMapping: identityOidcAuth.claimMetadataMapping as Record<string, string>,
            boundSubject: identityOidcAuth.boundSubject as string,
            accessTokenTTL: identityOidcAuth.accessTokenTTL,
            accessTokenMaxTTL: identityOidcAuth.accessTokenMaxTTL,
            accessTokenTrustedIps: identityOidcAuth.accessTokenTrustedIps as TIdentityTrustedIp[],
            accessTokenNumUsesLimit: identityOidcAuth.accessTokenNumUsesLimit
          }
        }
      });

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

      return {
        identityOidcAuth
      };
    }
  });

  server.route({
    method: "PATCH",
    url: "/oidc-auth/identities/:identityId",
    config: {
      rateLimit: writeLimit
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
    schema: {
      hide: false,
      operationId: "updateOidcAuth",
      tags: [ApiDocsTags.OidcAuth],
      description: "Update OIDC Auth configuration on machine identity",
      security: [
        {
          bearerAuth: []
        }
      ],
      params: z.object({
        identityId: z.string().trim().describe(OIDC_AUTH.UPDATE.identityId)
      }),
      body: z
        .object({
          oidcDiscoveryUrl: z.string().url().min(1).describe(OIDC_AUTH.UPDATE.oidcDiscoveryUrl),
          caCert: z.string().trim().default("").describe(OIDC_AUTH.UPDATE.caCert),
          boundIssuer: z.string().min(1).describe(OIDC_AUTH.UPDATE.boundIssuer),
          boundAudiences: validateOidcAuthAudiencesField.describe(OIDC_AUTH.UPDATE.boundAudiences),
          boundClaims: validateOidcBoundClaimsField.describe(OIDC_AUTH.UPDATE.boundClaims),
          claimMetadataMapping: validateOidcBoundClaimsField.describe(OIDC_AUTH.UPDATE.claimMetadataMapping).optional(),
          boundSubject: z.string().optional().default("").describe(OIDC_AUTH.UPDATE.boundSubject),
          accessTokenTrustedIps: z
            .object({
              ipAddress: z.string().trim()
            })
            .array()
            .min(1)
            .default([{ ipAddress: "0.0.0.0/0" }, { ipAddress: "::/0" }])
            .describe(OIDC_AUTH.UPDATE.accessTokenTrustedIps),
          accessTokenTTL: z
            .number()
            .int()
            .min(0)
            .max(315360000)
            .default(2592000)
            .describe(OIDC_AUTH.UPDATE.accessTokenTTL),
          accessTokenMaxTTL: z
            .number()
            .int()
            .min(0)
            .max(315360000)
            .default(2592000)
            .describe(OIDC_AUTH.UPDATE.accessTokenMaxTTL),
          accessTokenNumUsesLimit: z.number().int().min(0).default(0).describe(OIDC_AUTH.UPDATE.accessTokenNumUsesLimit)
        })
        .partial()
        .extend({
          templateId: z.string().uuid().nullable().optional().describe(OIDC_AUTH.UPDATE.templateId)
        })
        .superRefine((data, ctx) => {
          if (data.templateId) {
            rejectTemplateManagedOidcFields(data, ctx);
          }
          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({
          identityOidcAuth: IdentityOidcAuthResponseSchema
        })
      }
    },
    handler: async (req) => {
      const identityOidcAuth = await server.services.identityOidcAuth.updateOidcAuth({
        actor: req.permission.type,
        actorId: req.permission.id,
        actorOrgId: req.permission.orgId,
        actorAuthMethod: req.permission.authMethod,
        ...req.body,
        identityId: req.params.identityId,
        isActorSuperAdmin: isSuperAdmin(req.auth)
      });

      await server.services.auditLog.createAuditLog({
        ...req.auditLogInfo,
        orgId: identityOidcAuth.orgId,
        event: {
          type: EventType.UPDATE_IDENTITY_OIDC_AUTH,
          metadata: {
            identityId: identityOidcAuth.identityId,
            templateId: identityOidcAuth.templateId,
            templateName: identityOidcAuth.templateName,
            oidcDiscoveryUrl: identityOidcAuth.oidcDiscoveryUrl,
            caCert: identityOidcAuth.caCert,
            boundIssuer: identityOidcAuth.boundIssuer,
            boundAudiences: identityOidcAuth.boundAudiences,
            boundClaims: identityOidcAuth.boundClaims as Record<string, string>,
            claimMetadataMapping: identityOidcAuth.claimMetadataMapping as Record<string, string>,
            boundSubject: identityOidcAuth.boundSubject as string,
            accessTokenTTL: identityOidcAuth.accessTokenTTL,
            accessTokenMaxTTL: identityOidcAuth.accessTokenMaxTTL,
            accessTokenTrustedIps: identityOidcAuth.accessTokenTrustedIps as TIdentityTrustedIp[],
            accessTokenNumUsesLimit: identityOidcAuth.accessTokenNumUsesLimit
          }
        }
      });

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

      return { identityOidcAuth };
    }
  });

  server.route({
    method: "GET",
    url: "/oidc-auth/identities/:identityId",
    config: {
      rateLimit: readLimit
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
    schema: {
      hide: false,
      operationId: "getOidcAuth",
      tags: [ApiDocsTags.OidcAuth],
      description: "Retrieve OIDC Auth configuration on machine identity",
      security: [
        {
          bearerAuth: []
        }
      ],
      params: z.object({
        identityId: z.string().describe(OIDC_AUTH.RETRIEVE.identityId)
      }),
      response: {
        200: z.object({
          identityOidcAuth: IdentityOidcAuthResponseSchema
        })
      }
    },
    handler: async (req) => {
      const identityOidcAuth = await server.services.identityOidcAuth.getOidcAuth({
        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: identityOidcAuth.orgId,
        event: {
          type: EventType.GET_IDENTITY_OIDC_AUTH,
          metadata: {
            identityId: identityOidcAuth.identityId
          }
        }
      });

      return { identityOidcAuth };
    }
  });

  server.route({
    method: "DELETE",
    url: "/oidc-auth/identities/:identityId",
    config: {
      rateLimit: writeLimit
    },
    onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
    schema: {
      hide: false,
      operationId: "deleteOidcAuth",
      tags: [ApiDocsTags.OidcAuth],
      description: "Delete OIDC Auth configuration on machine identity",
      security: [
        {
          bearerAuth: []
        }
      ],
      params: z.object({
        identityId: z.string().describe(OIDC_AUTH.REVOKE.identityId)
      }),
      response: {
        200: z.object({
          identityOidcAuth: IdentityOidcAuthResponseSchema.omit({
            caCert: true
          })
        })
      }
    },
    handler: async (req) => {
      const identityOidcAuth = await server.services.identityOidcAuth.revokeOidcAuth({
        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: identityOidcAuth.orgId,
        event: {
          type: EventType.REVOKE_IDENTITY_OIDC_AUTH,
          metadata: {
            identityId: identityOidcAuth.identityId
          }
        }
      });

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

      return { identityOidcAuth };
    }
  });
};