Skip to content

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

23.1 KB
Raw Blame
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import { ForbiddenError, subject } from "@casl/ability";
import { requestContext } from "@fastify/request-context";
import { AxiosError } from "axios";
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 { TIdentityOciAuthDALFactory } from "./identity-oci-auth-dal";
import { getOciErrorForLog, getOciSignerUserOcid } from "./identity-oci-auth-fns";
import {
  TAttachOciAuthDTO,
  TGetOciAuthDTO,
  TLoginOciAuthDTO,
  TOciGetUserResponse,
  TRevokeOciAuthDTO,
  TUpdateOciAuthDTO
} from "./identity-oci-auth-types";

type TIdentityOciAuthServiceFactoryDep = {
  identityDAL: Pick<TIdentityDALFactory, "findById">;
  identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "delete">;
  identityOciAuthDAL: Pick<TIdentityOciAuthDALFactory, "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 TIdentityOciAuthServiceFactory = ReturnType<typeof identityOciAuthServiceFactory>;

export const identityOciAuthServiceFactory = ({
  identityDAL,
  identityAccessTokenDAL,
  identityOciAuthDAL,
  membershipIdentityDAL,
  keyStore,
  licenseService,
  permissionService,
  orgDAL,
  identityAccessTokenService,
  eventEmitter
}: TIdentityOciAuthServiceFactoryDep) => {
  const login = async ({ identityId, headers, userOcid, organizationSlug }: TLoginOciAuthDTO) => {
    const authMetricStartTime = performance.now();
    const appCfg = getConfig();
    const identityOciAuth = await identityOciAuthDAL.findOne({ identityId });
    if (!identityOciAuth) {
      throw new NotFoundError({ message: "OCI auth method not found for identity, did you configure OCI auth?" });
    }

    const identity = await requestMemoize(requestMemoKeys.identityFindById(identityOciAuth.identityId), () =>
      identityDAL.findById(identityOciAuth.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 {
      // Validate OCI host format. Ensures that the host is in "identity.<region>.oraclecloud.com" format.
      if (!headers.host || !new RE2("^identity\\.([a-z]{2}-[a-z]+-[1-9])\\.oraclecloud\\.com$").test(headers.host)) {
        throw new BadRequestError({
          message: "Invalid OCI host format. Expected format: identity.<region>.oraclecloud.com"
        });
      }

      const signerUserOcid = getOciSignerUserOcid(headers.authorization);
      if (!signerUserOcid) {
        throw new BadRequestError({
          message:
            "Invalid OCI signature: the authorization header must be signed by an OCI user API key (keyId in the form <tenancy-ocid>/<user-ocid>/<fingerprint>)."
        });
      }

      if (signerUserOcid !== userOcid) {
        throw new UnauthorizedError({
          message: "Access denied: the OCI user that signed the request does not match the provided user OCID.",
          detail: {
            reasonCode: "signer_mismatch",
            identityId: identity.id,
            orgId: identity.orgId,
            identityName: identity.name
          }
        });
      }

      const { data } = await request
        .get<TOciGetUserResponse>(`https://${headers.host}/20160918/users/${userOcid}`, {
          headers
        })
        .catch((err: AxiosError) => {
          logger.error(
            getOciErrorForLog(err),
            `OciIdentityLogin: Failed to authenticate with Oracle Cloud [identityId=${identity.id}] [status=${err.response?.status}]`
          );
          throw err;
        });

      if (data.compartmentId !== identityOciAuth.tenancyOcid) {
        throw new UnauthorizedError({
          message: "Access denied: OCI account isn't part of tenancy.",
          detail: {
            reasonCode: "tenancy_not_allowed",
            identityId: identity.id,
            orgId: identity.orgId,
            identityName: identity.name
          }
        });
      }

      if (identityOciAuth.allowedUsernames) {
        const isAccountAllowed = identityOciAuth.allowedUsernames.split(",").some((name) => name.trim() === data.name);

        if (!isAccountAllowed)
          throw new UnauthorizedError({
            message: "Access denied: OCI account username not allowed.",
            detail: {
              reasonCode: "username_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;
        }
      }

      // Generate the token
      await recordIdentityLastLoginDebounced({
        keyStore,
        membershipIdentityDAL,
        identity,
        lastLoginAuthMethod: IdentityAuthMethod.OCI_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: identityOciAuth.identityId,
        identityName: identity.name,
        authMethod: IdentityAuthMethod.OCI_AUTH,
        orgId: tokenScopeOrg.id,
        rootOrgId: tokenRootOrgId,
        parentOrgId: tokenParentOrgId,
        subOrganizationId,
        accessTokenTTL: Number(identityOciAuth.accessTokenTTL),
        accessTokenMaxTTL: Number(identityOciAuth.accessTokenMaxTTL),
        accessTokenNumUsesLimit: Number(identityOciAuth.accessTokenNumUsesLimit),
        accessTokenPeriod: Number(identityOciAuth.accessTokenPeriod) || 0,
        accessTokenTrustedIps: identityOciAuth.accessTokenTrustedIps as TIp[]
      });

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

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

  const attachOciAuth = async ({
    identityId,
    tenancyOcid,
    allowedUsernames,
    accessTokenTTL,
    accessTokenMaxTTL,
    accessTokenNumUsesLimit,
    accessTokenTrustedIps,
    actorId,
    actorAuthMethod,
    actor,
    actorOrgId,
    isActorSuperAdmin
  }: TAttachOciAuthDTO) => {
    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.OCI_AUTH)) {
      throw new BadRequestError({
        message: "Failed to add OCI 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 OCI 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 identityOciAuth = await identityOciAuthDAL.transaction(async (tx) => {
      const doc = await identityOciAuthDAL.create(
        {
          identityId: identityMembershipOrg.identity.id,
          type: "iam",
          tenancyOcid,
          allowedUsernames,
          accessTokenMaxTTL,
          accessTokenTTL,
          accessTokenNumUsesLimit,
          accessTokenTrustedIps: JSON.stringify(reformattedAccessTokenTrustedIps)
        },
        tx
      );
      await emitIdentityAuthMethodChanged(
        eventEmitter,
        {
          membership: identityMembershipOrg,
          authMethod: IdentityAuthMethod.OCI_AUTH,
          change: IdentityAuthMethodChange.Added,
          actor,
          actorId
        },
        tx
      );
      return doc;
    });
    await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.OCI_AUTH);
    return { ...identityOciAuth, orgId: identityMembershipOrg.scopeOrgId };
  };

  const updateOciAuth = async ({
    identityId,
    tenancyOcid,
    allowedUsernames,
    accessTokenTTL,
    accessTokenMaxTTL,
    accessTokenNumUsesLimit,
    accessTokenTrustedIps,
    actorId,
    actorAuthMethod,
    actor,
    actorOrgId,
    isActorSuperAdmin
  }: TUpdateOciAuthDTO) => {
    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.OCI_AUTH)) {
      throw new NotFoundError({
        message: "The identity does not have OCI Auth attached"
      });
    }

    const identityOciAuth = await identityOciAuthDAL.findOne({ identityId });

    if (
      (accessTokenMaxTTL || identityOciAuth.accessTokenMaxTTL) > 0 &&
      (accessTokenTTL || identityOciAuth.accessTokenTTL) > (accessTokenMaxTTL || identityOciAuth.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 OCI 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 updatedOciAuth = await identityOciAuthDAL.transaction(async (tx) => {
      const doc = await identityOciAuthDAL.updateById(
        identityOciAuth.id,
        {
          tenancyOcid,
          allowedUsernames,
          accessTokenMaxTTL,
          accessTokenTTL,
          accessTokenNumUsesLimit,
          accessTokenTrustedIps: reformattedAccessTokenTrustedIps
            ? JSON.stringify(reformattedAccessTokenTrustedIps)
            : undefined
        },
        tx
      );
      await emitIdentityAuthMethodChanged(
        eventEmitter,
        {
          membership: identityMembershipOrg,
          authMethod: IdentityAuthMethod.OCI_AUTH,
          change: IdentityAuthMethodChange.Updated,
          actor,
          actorId
        },
        tx
      );
      return doc;
    });

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

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

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

  const revokeIdentityOciAuth = async ({
    identityId,
    actorId,
    actor,
    actorAuthMethod,
    actorOrgId,
    isActorSuperAdmin
  }: TRevokeOciAuthDTO) => {
    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.OCI_AUTH)) {
      throw new BadRequestError({
        message: "The identity does not have OCI auth"
      });
    }

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

    await validateIdentityUpdateForSuperAdminPrivileges(identityId, isActorSuperAdmin);

    const revokedIdentityOciAuth = await identityOciAuthDAL.transaction(async (tx) => {
      const deletedOciAuth = await identityOciAuthDAL.delete({ identityId }, tx);
      await identityAccessTokenDAL.delete({ identityId, authMethod: IdentityAuthMethod.OCI_AUTH }, tx);

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

    return revokedIdentityOciAuth;
  };

  return {
    login,
    attachOciAuth,
    updateOciAuth,
    getOciAuth,
    revokeIdentityOciAuth
  };
};