Skip to content

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

21.9 KB
Raw Blame
import { ForbiddenError, subject } from "@casl/ability";
import { requestContext } from "@fastify/request-context";

import { AccessScope, ActionProjectType, IdentityAuthMethod, OrganizationActionScope } from "@app/db/schemas";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { OrgPermissionIdentityActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { ProjectPermissionIdentityActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
import { TKeyStoreFactory } from "@app/keystore/keystore";
import { getConfig } from "@app/lib/config/env";
import { BadRequestError, ForbiddenRequestError, NotFoundError, UnauthorizedError } from "@app/lib/errors";
import { extractIPDetails, isValidIpOrCidr, TIp } from "@app/lib/ip";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { RequestContextKey } from "@app/lib/request-context/request-context-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
import {
  AuthAttemptAuthMethod,
  AuthAttemptAuthResult,
  authAttemptCounter,
  recordAuthAttemptMetric
} from "@app/lib/telemetry/metrics";
import { TEventEmitter } from "@app/services/event-outbox/event-outbox-types";
import {
  emitIdentityAuthMethodChanged,
  IdentityAuthMethodChange
} from "@app/services/identity/identity-auth-method-events";

import { ActorType } from "../auth/auth-type";
import { TIdentityAccessTokenDALFactory } from "../identity-access-token/identity-access-token-dal";
import { TIdentityAccessTokenServiceFactory } from "../identity-access-token/identity-access-token-service";
import { assertIdentityAuthAccessAllowed } from "../identity/identity-auth-permission-fns";
import { TIdentityDALFactory } from "../identity/identity-dal";
import { TMembershipIdentityDALFactory } from "../membership-identity/membership-identity-dal";
import { recordIdentityLastLoginDebounced } from "../membership-identity/membership-identity-fns";
import { TOrgDALFactory } from "../org/org-dal";
import { validateIdentityUpdateForSuperAdminPrivileges } from "../super-admin/super-admin-fns";
import { TIdentityAzureAuthDALFactory } from "./identity-azure-auth-dal";
import { validateAzureIdentity } from "./identity-azure-auth-fns";
import {
  TAttachAzureAuthDTO,
  TGetAzureAuthDTO,
  TLoginAzureAuthDTO,
  TRevokeAzureAuthDTO,
  TUpdateAzureAuthDTO
} from "./identity-azure-auth-types";

type TIdentityAzureAuthServiceFactoryDep = {
  identityDAL: Pick<TIdentityDALFactory, "findById">;
  identityAzureAuthDAL: Pick<
    TIdentityAzureAuthDALFactory,
    "findOne" | "transaction" | "create" | "updateById" | "delete"
  >;
  membershipIdentityDAL: Pick<TMembershipIdentityDALFactory, "findOne" | "update" | "getIdentityById">;
  keyStore: Pick<TKeyStoreFactory, "setItemWithExpiryNX">;
  identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "delete">;
  permissionService: Pick<
    TPermissionServiceFactory,
    "getOrgPermission" | "getProjectPermission" | "getActorGrantAbilities"
  >;
  licenseService: Pick<TLicenseServiceFactory, "getPlan">;
  orgDAL: Pick<TOrgDALFactory, "findById" | "findOne" | "findEffectiveOrgMembership">;
  identityAccessTokenService: Pick<
    TIdentityAccessTokenServiceFactory,
    "issueIdentityAccessToken" | "revokeTokensForIdentityAuthMethod" | "invalidateTrustedIpsCache"
  >;
  eventEmitter: TEventEmitter;
};

export type TIdentityAzureAuthServiceFactory = ReturnType<typeof identityAzureAuthServiceFactory>;

export const identityAzureAuthServiceFactory = ({
  identityDAL,
  identityAzureAuthDAL,
  membershipIdentityDAL,
  keyStore,
  identityAccessTokenDAL,
  permissionService,
  licenseService,
  orgDAL,
  identityAccessTokenService,
  eventEmitter
}: TIdentityAzureAuthServiceFactoryDep) => {
  const login = async ({ identityId, jwt: azureJwt, organizationSlug }: TLoginAzureAuthDTO) => {
    const authMetricStartTime = performance.now();
    const appCfg = getConfig();
    const identityAzureAuth = await identityAzureAuthDAL.findOne({ identityId });
    if (!identityAzureAuth) {
      throw new NotFoundError({ message: "Azure auth method not found for identity, did you configure Azure Auth?" });
    }

    const identity = await requestMemoize(requestMemoKeys.identityFindById(identityAzureAuth.identityId), () =>
      identityDAL.findById(identityAzureAuth.identityId)
    );
    if (!identity)
      throw new UnauthorizedError({
        message: "Identity not found"
      });

    const org = await requestMemoize(requestMemoKeys.orgFindById(identity.orgId), () =>
      orgDAL.findById(identity.orgId)
    );
    const isSubOrgIdentity = Boolean(org.rootOrgId);

    // If the identity is a sub-org identity, then the scope is always the org.id, and if it's a root org identity, then we need to resolve the scope if a organizationSlug is specified
    let subOrganizationId = isSubOrgIdentity ? org.id : null;

    try {
      const azureIdentity = await validateAzureIdentity({
        tenantId: identityAzureAuth.tenantId,
        resource: identityAzureAuth.resource,
        jwt: azureJwt
      });

      if (azureIdentity.tid !== identityAzureAuth.tenantId)
        throw new UnauthorizedError({
          message: "Tenant ID mismatch",
          detail: {
            reasonCode: "tenant_id_mismatch",
            identityId: identity.id,
            orgId: identity.orgId,
            identityName: identity.name
          }
        });

      if (identityAzureAuth.allowedServicePrincipalIds) {
        // validate if the service principal id is in the list of allowed service principal ids

        const isServicePrincipalAllowed = identityAzureAuth.allowedServicePrincipalIds
          .split(",")
          .map((servicePrincipalId) => servicePrincipalId.trim())
          .some((servicePrincipalId) => servicePrincipalId === azureIdentity.oid);

        if (!isServicePrincipalAllowed) {
          throw new UnauthorizedError({
            message: `Service principal '${azureIdentity.oid}' not allowed`,
            detail: {
              reasonCode: "service_principal_not_allowed",
              identityId: identity.id,
              orgId: identity.orgId,
              identityName: identity.name
            }
          });
        }
      }

      if (organizationSlug && org.slug !== organizationSlug) {
        if (!isSubOrgIdentity) {
          const subOrg = await orgDAL.findOne({ rootOrgId: org.id, slug: organizationSlug });

          if (!subOrg) {
            throw new NotFoundError({ message: `Sub organization with slug ${organizationSlug} not found` });
          }

          const subOrgMembership = await orgDAL.findEffectiveOrgMembership({
            actorType: ActorType.IDENTITY,
            actorId: identity.id,
            orgId: subOrg.id
          });

          if (!subOrgMembership) {
            throw new UnauthorizedError({
              message: `Identity not authorized to access sub organization ${organizationSlug}`,
              detail: {
                reasonCode: "sub_org_unauthorized",
                identityId: identity.id,
                orgId: identity.orgId,
                identityName: identity.name
              }
            });
          }

          subOrganizationId = subOrg.id;
        }
      }

      await recordIdentityLastLoginDebounced({
        keyStore,
        membershipIdentityDAL,
        identity,
        lastLoginAuthMethod: IdentityAuthMethod.AZURE_AUTH
      });

      const subOrgDetails =
        subOrganizationId && subOrganizationId !== org.id ? await orgDAL.findById(subOrganizationId) : null;
      const tokenScopeOrg = subOrgDetails ?? org;
      const tokenRootOrgId = tokenScopeOrg.rootOrgId ?? tokenScopeOrg.id;
      const tokenParentOrgId = tokenScopeOrg.parentOrgId ?? tokenRootOrgId;

      const { accessToken, identityAccessToken } = await identityAccessTokenService.issueIdentityAccessToken({
        identityId: identityAzureAuth.identityId,
        identityName: identity.name,
        authMethod: IdentityAuthMethod.AZURE_AUTH,
        orgId: tokenScopeOrg.id,
        rootOrgId: tokenRootOrgId,
        parentOrgId: tokenParentOrgId,
        subOrganizationId,
        accessTokenTTL: Number(identityAzureAuth.accessTokenTTL),
        accessTokenMaxTTL: Number(identityAzureAuth.accessTokenMaxTTL),
        accessTokenNumUsesLimit: Number(identityAzureAuth.accessTokenNumUsesLimit),
        accessTokenPeriod: Number(identityAzureAuth.accessTokenPeriod) || 0,
        accessTokenTrustedIps: identityAzureAuth.accessTokenTrustedIps as TIp[]
      });

      if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
        authAttemptCounter.add(1, {
          "infisical.identity.id": identityAzureAuth.identityId,
          "infisical.identity.name": identity.name,
          "infisical.organization.id": org.id,
          "infisical.organization.name": org.name,
          "infisical.identity.auth_method": AuthAttemptAuthMethod.AZURE_AUTH,
          "infisical.identity.auth_result": AuthAttemptAuthResult.SUCCESS,
          "client.address": requestContext.get(RequestContextKey.Ip),
          "user_agent.original": requestContext.get(RequestContextKey.UserAgent)
        });
      }

      recordAuthAttemptMetric({
        startTime: authMetricStartTime,
        method: AuthAttemptAuthMethod.AZURE_AUTH,
        result: AuthAttemptAuthResult.SUCCESS,
        orgId: org.id
      });

      return { accessToken, identityAzureAuth, identityAccessToken, identity };
    } catch (error) {
      if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
        authAttemptCounter.add(1, {
          "infisical.identity.id": identityAzureAuth.identityId,
          "infisical.identity.name": identity.name,
          "infisical.organization.id": org.id,
          "infisical.organization.name": org.name,
          "infisical.identity.auth_method": AuthAttemptAuthMethod.AZURE_AUTH,
          "infisical.identity.auth_result": AuthAttemptAuthResult.FAILURE,
          "client.address": requestContext.get(RequestContextKey.Ip),
          "user_agent.original": requestContext.get(RequestContextKey.UserAgent)
        });
      }

      recordAuthAttemptMetric({
        startTime: authMetricStartTime,
        method: AuthAttemptAuthMethod.AZURE_AUTH,
        result: AuthAttemptAuthResult.FAILURE,
        orgId: org.id,
        error
      });
      throw error;
    }
  };

  const attachAzureAuth = async ({
    identityId,
    tenantId,
    resource,
    allowedServicePrincipalIds,
    accessTokenTTL,
    accessTokenMaxTTL,
    accessTokenNumUsesLimit,
    accessTokenTrustedIps,
    actorId,
    actorAuthMethod,
    actor,
    actorOrgId,
    isActorSuperAdmin
  }: TAttachAzureAuthDTO) => {
    const identityMembershipOrg = await membershipIdentityDAL.getIdentityById({
      scopeData: {
        scope: AccessScope.Organization,
        orgId: actorOrgId
      },
      identityId
    });
    if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
    if (identityMembershipOrg.identity.orgId !== actorOrgId) {
      throw new ForbiddenRequestError({ message: "Sub organization not authorized to access this identity" });
    }

    if (identityMembershipOrg.identity.authMethods.includes(IdentityAuthMethod.AZURE_AUTH)) {
      throw new BadRequestError({
        message: "Failed to add Azure Auth to already configured identity"
      });
    }
    if (accessTokenMaxTTL > 0 && accessTokenTTL > accessTokenMaxTTL) {
      throw new BadRequestError({ message: "Access token TTL cannot be greater than max TTL" });
    }

    await assertIdentityAuthAccessAllowed(
      { permissionService, orgDAL },
      {
        identityId,
        orgId: identityMembershipOrg.scopeOrgId,
        projectId: identityMembershipOrg.identity.projectId,
        action: OrgPermissionIdentityActions.EditAuth,
        baseMessage: "Failed to add azure auth to identity with more privileged role",
        actor,
        actorId,
        actorAuthMethod,
        actorOrgId
      }
    );

    await validateIdentityUpdateForSuperAdminPrivileges(identityId, isActorSuperAdmin);
    const plan = await licenseService.getPlan(identityMembershipOrg.scopeOrgId);
    const reformattedAccessTokenTrustedIps = accessTokenTrustedIps.map((accessTokenTrustedIp) => {
      if (
        !plan.ipAllowlisting &&
        accessTokenTrustedIp.ipAddress !== "0.0.0.0/0" &&
        accessTokenTrustedIp.ipAddress !== "::/0"
      )
        throw new BadRequestError({
          message:
            "Failed to add IP access range to access token due to plan restriction. Upgrade plan to add IP access range."
        });
      if (!isValidIpOrCidr(accessTokenTrustedIp.ipAddress))
        throw new BadRequestError({
          message: "The IP is not a valid IPv4, IPv6, or CIDR block"
        });
      return extractIPDetails(accessTokenTrustedIp.ipAddress);
    });

    const identityAzureAuth = await identityAzureAuthDAL.transaction(async (tx) => {
      const doc = await identityAzureAuthDAL.create(
        {
          identityId: identityMembershipOrg.identity.id,
          tenantId,
          resource,
          allowedServicePrincipalIds,
          accessTokenMaxTTL,
          accessTokenTTL,
          accessTokenNumUsesLimit,
          accessTokenTrustedIps: JSON.stringify(reformattedAccessTokenTrustedIps)
        },
        tx
      );

      await emitIdentityAuthMethodChanged(
        eventEmitter,
        {
          membership: identityMembershipOrg,
          authMethod: IdentityAuthMethod.AZURE_AUTH,
          change: IdentityAuthMethodChange.Added,
          actor,
          actorId
        },
        tx
      );
      return doc;
    });
    await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.AZURE_AUTH);
    return { ...identityAzureAuth, orgId: identityMembershipOrg.scopeOrgId };
  };

  const updateAzureAuth = async ({
    identityId,
    tenantId,
    resource,
    allowedServicePrincipalIds,
    accessTokenTTL,
    accessTokenMaxTTL,
    accessTokenNumUsesLimit,
    accessTokenTrustedIps,
    actorId,
    actorAuthMethod,
    actor,
    actorOrgId,
    isActorSuperAdmin
  }: TUpdateAzureAuthDTO) => {
    const identityMembershipOrg = await membershipIdentityDAL.getIdentityById({
      scopeData: {
        scope: AccessScope.Organization,
        orgId: actorOrgId
      },
      identityId
    });
    if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
    if (identityMembershipOrg.identity.orgId !== actorOrgId) {
      throw new ForbiddenRequestError({ message: "Sub organization not authorized to access this identity" });
    }

    if (!identityMembershipOrg.identity.authMethods.includes(IdentityAuthMethod.AZURE_AUTH)) {
      throw new BadRequestError({
        message: "Failed to update Azure Auth"
      });
    }

    const identityGcpAuth = await identityAzureAuthDAL.findOne({ identityId });

    if (
      (accessTokenMaxTTL || identityGcpAuth.accessTokenMaxTTL) > 0 &&
      (accessTokenTTL || identityGcpAuth.accessTokenMaxTTL) > (accessTokenMaxTTL || identityGcpAuth.accessTokenMaxTTL)
    ) {
      throw new BadRequestError({ message: "Access token TTL cannot be greater than max TTL" });
    }

    await assertIdentityAuthAccessAllowed(
      { permissionService, orgDAL },
      {
        identityId,
        orgId: identityMembershipOrg.scopeOrgId,
        projectId: identityMembershipOrg.identity.projectId,
        action: OrgPermissionIdentityActions.EditAuth,
        baseMessage: "Failed to update azure auth of identity with more privileged role",
        actor,
        actorId,
        actorAuthMethod,
        actorOrgId
      }
    );

    await validateIdentityUpdateForSuperAdminPrivileges(identityId, isActorSuperAdmin);
    const plan = await licenseService.getPlan(identityMembershipOrg.scopeOrgId);
    const reformattedAccessTokenTrustedIps = accessTokenTrustedIps?.map((accessTokenTrustedIp) => {
      if (
        !plan.ipAllowlisting &&
        accessTokenTrustedIp.ipAddress !== "0.0.0.0/0" &&
        accessTokenTrustedIp.ipAddress !== "::/0"
      )
        throw new BadRequestError({
          message:
            "Failed to add IP access range to access token due to plan restriction. Upgrade plan to add IP access range."
        });
      if (!isValidIpOrCidr(accessTokenTrustedIp.ipAddress))
        throw new BadRequestError({
          message: "The IP is not a valid IPv4, IPv6, or CIDR block"
        });
      return extractIPDetails(accessTokenTrustedIp.ipAddress);
    });

    const updatedAzureAuth = await identityAzureAuthDAL.transaction(async (tx) => {
      const doc = await identityAzureAuthDAL.updateById(
        identityGcpAuth.id,
        {
          tenantId,
          resource,
          allowedServicePrincipalIds,
          accessTokenMaxTTL,
          accessTokenTTL,
          accessTokenNumUsesLimit,
          accessTokenTrustedIps: reformattedAccessTokenTrustedIps
            ? JSON.stringify(reformattedAccessTokenTrustedIps)
            : undefined
        },
        tx
      );
      await emitIdentityAuthMethodChanged(
        eventEmitter,
        {
          membership: identityMembershipOrg,
          authMethod: IdentityAuthMethod.AZURE_AUTH,
          change: IdentityAuthMethodChange.Updated,
          actor,
          actorId
        },
        tx
      );
      return doc;
    });

    await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.AZURE_AUTH);
    return {
      ...updatedAzureAuth,
      orgId: identityMembershipOrg.scopeOrgId
    };
  };

  const getAzureAuth = async ({ identityId, actorId, actor, actorAuthMethod, actorOrgId }: TGetAzureAuthDTO) => {
    const identityMembershipOrg = await membershipIdentityDAL.getIdentityById({
      scopeData: {
        scope: AccessScope.Organization,
        orgId: actorOrgId
      },
      identityId
    });
    if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
    if (identityMembershipOrg.identity.orgId !== actorOrgId) {
      throw new ForbiddenRequestError({ message: "Sub organization not authorized to access this identity" });
    }
    if (!identityMembershipOrg.identity.authMethods.includes(IdentityAuthMethod.AZURE_AUTH)) {
      throw new BadRequestError({
        message: "The identity does not have Azure Auth attached"
      });
    }

    const identityAzureAuth = await identityAzureAuthDAL.findOne({ identityId });

    if (identityMembershipOrg.identity.projectId) {
      const { permission } = await permissionService.getProjectPermission({
        actionProjectType: ActionProjectType.Any,
        actor,
        actorId,
        projectId: identityMembershipOrg.identity.projectId,
        actorAuthMethod,
        actorOrgId
      });

      ForbiddenError.from(permission).throwUnlessCan(
        ProjectPermissionIdentityActions.Read,
        subject(ProjectPermissionSub.Identity, { identityId })
      );
    } else {
      const { permission } = await permissionService.getOrgPermission({
        scope: OrganizationActionScope.Any,
        actor,
        actorId,
        orgId: identityMembershipOrg.scopeOrgId,
        actorAuthMethod,
        actorOrgId
      });
      ForbiddenError.from(permission).throwUnlessCan(OrgPermissionIdentityActions.Read, OrgPermissionSubjects.Identity);
    }
    return { ...identityAzureAuth, orgId: identityMembershipOrg.scopeOrgId };
  };

  const revokeIdentityAzureAuth = async ({
    identityId,
    actorId,
    actor,
    actorAuthMethod,
    actorOrgId,
    isActorSuperAdmin
  }: TRevokeAzureAuthDTO) => {
    const identityMembershipOrg = await membershipIdentityDAL.getIdentityById({
      scopeData: {
        scope: AccessScope.Organization,
        orgId: actorOrgId
      },
      identityId
    });
    if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
    if (identityMembershipOrg.identity.orgId !== actorOrgId) {
      throw new ForbiddenRequestError({ message: "Sub organization not authorized to access this identity" });
    }

    if (!identityMembershipOrg.identity.authMethods.includes(IdentityAuthMethod.AZURE_AUTH)) {
      throw new BadRequestError({
        message: "The identity does not have azure auth"
      });
    }
    await assertIdentityAuthAccessAllowed(
      { permissionService, orgDAL },
      {
        identityId,
        orgId: identityMembershipOrg.scopeOrgId,
        projectId: identityMembershipOrg.identity.projectId,
        action: OrgPermissionIdentityActions.RevokeAuth,
        baseMessage: "Failed to revoke azure auth of identity with more privileged role",
        actor,
        actorId,
        actorAuthMethod,
        actorOrgId
      }
    );

    await validateIdentityUpdateForSuperAdminPrivileges(identityId, isActorSuperAdmin);

    const revokedIdentityAzureAuth = await identityAzureAuthDAL.transaction(async (tx) => {
      const deletedAzureAuth = await identityAzureAuthDAL.delete({ identityId }, tx);
      await identityAccessTokenDAL.delete({ identityId, authMethod: IdentityAuthMethod.AZURE_AUTH }, tx);

      await emitIdentityAuthMethodChanged(
        eventEmitter,
        {
          membership: identityMembershipOrg,
          authMethod: IdentityAuthMethod.AZURE_AUTH,
          change: IdentityAuthMethodChange.Removed,
          actor,
          actorId
        },
        tx
      );
      return { ...deletedAzureAuth?.[0], orgId: identityMembershipOrg.scopeOrgId };
    });

    // Detaching the auth method must invalidate any tokens already issued
    // through it; without this, leaked tokens authenticate up to MAX_AGE
    // even after the admin pulled the auth method.
    await identityAccessTokenService.revokeTokensForIdentityAuthMethod({
      identityId,
      authMethod: IdentityAuthMethod.AZURE_AUTH
    });
    await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.AZURE_AUTH);

    return revokedIdentityAzureAuth;
  };

  return {
    login,
    attachAzureAuth,
    updateAzureAuth,
    getAzureAuth,
    revokeIdentityAzureAuth
  };
};