Skip to content

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

24.5 KB
Raw Blame
/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access */
import { ForbiddenError, subject } from "@casl/ability";
import { requestContext } from "@fastify/request-context";
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import RE2 from "re2";

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 { request } from "@app/lib/config/request";
import { BadRequestError, ForbiddenRequestError, NotFoundError, UnauthorizedError } from "@app/lib/errors";
import { extractIPDetails, isValidIpOrCidr, TIp } from "@app/lib/ip";
import { logger } from "@app/lib/logger";
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 { TIdentityAwsAuthDALFactory } from "./identity-aws-auth-dal";
import {
  AWS_TRUST_BINDING_REQUIRED_MESSAGE,
  extractPrincipalArn,
  extractPrincipalArnEntity,
  hasAwsTrustBinding,
  parseSignedGetCallerIdentityRequest
} from "./identity-aws-auth-fns";
import {
  TAttachAwsAuthDTO,
  TGetAwsAuthDTO,
  TGetCallerIdentityResponse,
  TLoginAwsAuthDTO,
  TRevokeAwsAuthDTO,
  TUpdateAwsAuthDTO
} from "./identity-aws-auth-types";

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

export type TIdentityAwsAuthServiceFactory = ReturnType<typeof identityAwsAuthServiceFactory>;

export const identityAwsAuthServiceFactory = ({
  identityDAL,
  identityAccessTokenDAL,
  identityAwsAuthDAL,
  membershipIdentityDAL,
  keyStore,
  licenseService,
  permissionService,
  orgDAL,
  identityAccessTokenService,
  eventEmitter
}: TIdentityAwsAuthServiceFactoryDep) => {
  const login = async ({
    identityId,
    iamHttpRequestMethod,
    iamRequestBody,
    iamRequestHeaders,
    organizationSlug
  }: TLoginAwsAuthDTO) => {
    const authMetricStartTime = performance.now();
    const appCfg = getConfig();
    const identityAwsAuth = await identityAwsAuthDAL.findOne({ identityId });
    if (!identityAwsAuth) {
      throw new NotFoundError({ message: "AWS auth method not found for identity, did you configure AWS auth?" });
    }

    const identity = await requestMemoize(requestMemoKeys.identityFindById(identityAwsAuth.identityId), () =>
      identityDAL.findById(identityAwsAuth.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 {
      if (!hasAwsTrustBinding(identityAwsAuth)) {
        logger.warn(`AWS Auth Login: identity has no trust binding, allowing [identity-id=${identity.id}]`);
      }

      const { url, headers, body } = parseSignedGetCallerIdentityRequest({
        iamHttpRequestMethod,
        iamRequestBody,
        iamRequestHeaders
      });

      const {
        data: {
          GetCallerIdentityResponse: {
            GetCallerIdentityResult: { Account, Arn, UserId }
          }
        }
      }: { data: TGetCallerIdentityResponse } = await request({
        method: "POST",
        url,
        headers,
        data: body
      });

      if (identityAwsAuth.allowedAccountIds) {
        // validate if Account is in the list of allowed Account IDs

        const isAccountAllowed = identityAwsAuth.allowedAccountIds
          .split(",")
          .map((accountId) => accountId.trim())
          .some((accountId) => accountId === Account);

        if (!isAccountAllowed)
          throw new UnauthorizedError({
            message: "Access denied: AWS account ID not allowed.",
            detail: {
              reasonCode: "account_id_not_allowed",
              identityId: identity.id,
              orgId: identity.orgId,
              identityName: identity.name
            }
          });
      }

      if (identityAwsAuth.allowedPrincipalArns) {
        // validate if Arn is in the list of allowed Principal ARNs

        const formattedArn = extractPrincipalArn(Arn);

        const isArnAllowed = identityAwsAuth.allowedPrincipalArns
          .split(",")
          .map((principalArn) => principalArn.trim())
          .some((principalArn) => {
            // convert wildcard ARN to a regular expression: "arn:aws:iam::123456789012:*" -> "^arn:aws:iam::123456789012:.*$"
            // considers exact matches + wildcard matches
            // heavily validated in router
            const regex = new RE2(`^${principalArn.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replaceAll("*", ".*")}$`);
            return regex.test(formattedArn) || regex.test(extractPrincipalArn(Arn, true));
          });

        if (!isArnAllowed) {
          logger.warn(
            `AWS Auth Login: AWS principal ARN not allowed [principal-arn=${formattedArn}] [raw-arn=${Arn}] [identity-id=${identity.id}]`
          );

          throw new UnauthorizedError({
            message: `Access denied: AWS principal ARN not allowed. [principal-arn=${formattedArn}]`,
            detail: {
              reasonCode: "principal_arn_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.AWS_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 splitArn = extractPrincipalArnEntity(Arn);
      const { accessToken, identityAccessToken } = await identityAccessTokenService.issueIdentityAccessToken({
        identityId: identityAwsAuth.identityId,
        identityName: identity.name,
        authMethod: IdentityAuthMethod.AWS_AUTH,
        orgId: tokenScopeOrg.id,
        rootOrgId: tokenRootOrgId,
        parentOrgId: tokenParentOrgId,
        subOrganizationId,
        accessTokenTTL: Number(identityAwsAuth.accessTokenTTL),
        accessTokenMaxTTL: Number(identityAwsAuth.accessTokenMaxTTL),
        accessTokenNumUsesLimit: Number(identityAwsAuth.accessTokenNumUsesLimit),
        accessTokenPeriod: Number(identityAwsAuth.accessTokenPeriod) || 0,
        accessTokenTrustedIps: identityAwsAuth.accessTokenTrustedIps as TIp[],
        identityAuth: {
          aws: {
            accountId: Account,
            arn: Arn,
            userId: UserId,

            // Derived from ARN
            partition: splitArn.Partition,
            service: splitArn.Service,
            resourceType: splitArn.Type,
            resourceName: splitArn.FriendlyName
          }
        }
      });

      if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
        authAttemptCounter.add(1, {
          "infisical.identity.id": identityAwsAuth.identityId,
          "infisical.identity.name": identity.name,
          "infisical.organization.id": org.id,
          "infisical.organization.name": org.name,
          "infisical.identity.auth_method": AuthAttemptAuthMethod.AWS_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.AWS_AUTH,
        result: AuthAttemptAuthResult.SUCCESS,
        orgId: org.id
      });

      return { accessToken, identityAwsAuth, identityAccessToken, identity };
    } catch (error) {
      if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
        authAttemptCounter.add(1, {
          "infisical.identity.id": identityAwsAuth.identityId,
          "infisical.identity.name": identity.name,
          "infisical.organization.id": org.id,
          "infisical.organization.name": org.name,
          "infisical.identity.auth_method": AuthAttemptAuthMethod.AWS_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.AWS_AUTH,
        result: AuthAttemptAuthResult.FAILURE,
        orgId: org.id,
        error
      });
      throw error;
    }
  };

  const attachAwsAuth = async ({
    identityId,
    stsEndpoint,
    allowedPrincipalArns,
    allowedAccountIds,
    accessTokenTTL,
    accessTokenMaxTTL,
    accessTokenNumUsesLimit,
    accessTokenTrustedIps,
    actorId,
    actorAuthMethod,
    actor,
    actorOrgId,
    isActorSuperAdmin
  }: TAttachAwsAuthDTO) => {
    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.AWS_AUTH)) {
      throw new BadRequestError({
        message: "Failed to add AWS Auth to already configured identity"
      });
    }

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

    if (!hasAwsTrustBinding({ allowedAccountIds, allowedPrincipalArns })) {
      throw new BadRequestError({ message: AWS_TRUST_BINDING_REQUIRED_MESSAGE });
    }

    await assertIdentityAuthAccessAllowed(
      { permissionService, orgDAL },
      {
        identityId,
        orgId: identityMembershipOrg.scopeOrgId,
        projectId: identityMembershipOrg.identity.projectId,
        action: OrgPermissionIdentityActions.EditAuth,
        baseMessage: "Failed to add aws 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 identityAwsAuth = await identityAwsAuthDAL.transaction(async (tx) => {
      const doc = await identityAwsAuthDAL.create(
        {
          identityId: identityMembershipOrg.identity.id,
          type: "iam",
          stsEndpoint,
          allowedPrincipalArns,
          allowedAccountIds,
          accessTokenMaxTTL,
          accessTokenTTL,
          accessTokenNumUsesLimit,
          accessTokenTrustedIps: JSON.stringify(reformattedAccessTokenTrustedIps)
        },
        tx
      );
      await emitIdentityAuthMethodChanged(
        eventEmitter,
        {
          membership: identityMembershipOrg,
          authMethod: IdentityAuthMethod.AWS_AUTH,
          change: IdentityAuthMethodChange.Added,
          actor,
          actorId
        },
        tx
      );
      return doc;
    });
    await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.AWS_AUTH);
    return { ...identityAwsAuth, orgId: identityMembershipOrg.scopeOrgId };
  };

  const updateAwsAuth = async ({
    identityId,
    stsEndpoint,
    allowedPrincipalArns,
    allowedAccountIds,
    accessTokenTTL,
    accessTokenMaxTTL,
    accessTokenNumUsesLimit,
    accessTokenTrustedIps,
    actorId,
    actorAuthMethod,
    actor,
    actorOrgId,
    isActorSuperAdmin
  }: TUpdateAwsAuthDTO) => {
    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.AWS_AUTH)) {
      throw new NotFoundError({
        message: "The identity does not have AWS Auth attached"
      });
    }

    const identityAwsAuth = await identityAwsAuthDAL.findOne({ identityId });

    if (
      !hasAwsTrustBinding({
        allowedAccountIds: allowedAccountIds ?? identityAwsAuth.allowedAccountIds,
        allowedPrincipalArns: allowedPrincipalArns ?? identityAwsAuth.allowedPrincipalArns
      })
    ) {
      throw new BadRequestError({ message: AWS_TRUST_BINDING_REQUIRED_MESSAGE });
    }

    if (
      (accessTokenMaxTTL || identityAwsAuth.accessTokenMaxTTL) > 0 &&
      (accessTokenTTL || identityAwsAuth.accessTokenMaxTTL) > (accessTokenMaxTTL || identityAwsAuth.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 aws 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 updatedAwsAuth = await identityAwsAuthDAL.transaction(async (tx) => {
      const doc = await identityAwsAuthDAL.updateById(
        identityAwsAuth.id,
        {
          stsEndpoint,
          allowedPrincipalArns,
          allowedAccountIds,
          accessTokenMaxTTL,
          accessTokenTTL,
          accessTokenNumUsesLimit,
          accessTokenTrustedIps: reformattedAccessTokenTrustedIps
            ? JSON.stringify(reformattedAccessTokenTrustedIps)
            : undefined
        },
        tx
      );
      await emitIdentityAuthMethodChanged(
        eventEmitter,
        {
          membership: identityMembershipOrg,
          authMethod: IdentityAuthMethod.AWS_AUTH,
          change: IdentityAuthMethodChange.Updated,
          actor,
          actorId
        },
        tx
      );
      return doc;
    });

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

  const getAwsAuth = async ({ identityId, actorId, actor, actorAuthMethod, actorOrgId }: TGetAwsAuthDTO) => {
    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.AWS_AUTH)) {
      throw new BadRequestError({
        message: "The identity does not have AWS Auth attached"
      });
    }

    const awsIdentityAuth = await identityAwsAuthDAL.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 { ...awsIdentityAuth, orgId: identityMembershipOrg.scopeOrgId };
  };

  const revokeIdentityAwsAuth = async ({
    identityId,
    actorId,
    actor,
    actorAuthMethod,
    actorOrgId,
    isActorSuperAdmin
  }: TRevokeAwsAuthDTO) => {
    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.AWS_AUTH)) {
      throw new BadRequestError({
        message: "The identity does not have aws auth"
      });
    }
    await assertIdentityAuthAccessAllowed(
      { permissionService, orgDAL },
      {
        identityId,
        orgId: identityMembershipOrg.scopeOrgId,
        projectId: identityMembershipOrg.identity.projectId,
        action: OrgPermissionIdentityActions.RevokeAuth,
        baseMessage: "Failed to revoke aws auth of identity with more privileged role",
        actor,
        actorId,
        actorAuthMethod,
        actorOrgId
      }
    );

    await validateIdentityUpdateForSuperAdminPrivileges(identityId, isActorSuperAdmin);
    const revokedIdentityAwsAuth = await identityAwsAuthDAL.transaction(async (tx) => {
      const deletedAwsAuth = await identityAwsAuthDAL.delete({ identityId }, tx);
      await identityAccessTokenDAL.delete({ identityId, authMethod: IdentityAuthMethod.AWS_AUTH }, tx);

      await emitIdentityAuthMethodChanged(
        eventEmitter,
        {
          membership: identityMembershipOrg,
          authMethod: IdentityAuthMethod.AWS_AUTH,
          change: IdentityAuthMethodChange.Removed,
          actor,
          actorId
        },
        tx
      );
      return { ...deletedAwsAuth?.[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.AWS_AUTH
    });
    await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.AWS_AUTH);

    return revokedIdentityAwsAuth;
  };

  return {
    login,
    attachAwsAuth,
    updateAwsAuth,
    getAwsAuth,
    revokeIdentityAwsAuth
  };
};