Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
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 { 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 { TIdentityGcpAuthDALFactory } from "./identity-gcp-auth-dal";
import {
GCP_TRUST_BINDING_REQUIRED_MESSAGE,
hasGcpTrustBinding,
validateIamIdentity,
validateIdTokenIdentity
} from "./identity-gcp-auth-fns";
import {
TAttachGcpAuthDTO,
TGcpIdentityDetails,
TGetGcpAuthDTO,
TLoginGcpAuthDTO,
TRevokeGcpAuthDTO,
TUpdateGcpAuthDTO
} from "./identity-gcp-auth-types";
type TIdentityGcpAuthServiceFactoryDep = {
identityDAL: Pick<TIdentityDALFactory, "findById">;
identityGcpAuthDAL: Pick<TIdentityGcpAuthDALFactory, "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 TIdentityGcpAuthServiceFactory = ReturnType<typeof identityGcpAuthServiceFactory>;
export const identityGcpAuthServiceFactory = ({
identityDAL,
identityGcpAuthDAL,
membershipIdentityDAL,
keyStore,
identityAccessTokenDAL,
permissionService,
licenseService,
orgDAL,
identityAccessTokenService,
eventEmitter
}: TIdentityGcpAuthServiceFactoryDep) => {
const login = async ({ identityId, jwt: gcpJwt, organizationSlug }: TLoginGcpAuthDTO) => {
const authMetricStartTime = performance.now();
const appCfg = getConfig();
const identityGcpAuth = await identityGcpAuthDAL.findOne({ identityId });
if (!identityGcpAuth) {
throw new NotFoundError({ message: "GCP auth method not found for identity, did you configure GCP auth?" });
}
const identity = await requestMemoize(requestMemoKeys.identityFindById(identityGcpAuth.identityId), () =>
identityDAL.findById(identityGcpAuth.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 (!hasGcpTrustBinding(identityGcpAuth)) {
logger.warn(`GCP Auth Login: identity has no trust binding, allowing [identity-id=${identity.id}]`);
}
let gcpIdentityDetails: TGcpIdentityDetails;
switch (identityGcpAuth.type) {
case "gce": {
gcpIdentityDetails = await validateIdTokenIdentity({
audience: identityId,
jwt: gcpJwt
});
break;
}
case "iam": {
gcpIdentityDetails = await validateIamIdentity({
audience: identityId,
jwt: gcpJwt
});
break;
}
default: {
throw new BadRequestError({ message: "Invalid GCP Auth type" });
}
}
if (
identityGcpAuth.type === "gce" &&
(identityGcpAuth.allowedProjects || identityGcpAuth.allowedZones) &&
!gcpIdentityDetails.computeEngineDetails
) {
throw new UnauthorizedError({
message: "Access denied: GCP identity token is missing the Compute Engine details required to verify it.",
detail: {
reasonCode: "compute_engine_details_missing",
identityId: identity.id,
orgId: identity.orgId,
identityName: identity.name
}
});
}
if (identityGcpAuth.allowedServiceAccounts) {
// validate if the service account is in the list of allowed service accounts
const isServiceAccountAllowed = identityGcpAuth.allowedServiceAccounts
.split(",")
.map((serviceAccount) => serviceAccount.trim())
.some((serviceAccount) => serviceAccount === gcpIdentityDetails.email);
if (!isServiceAccountAllowed)
throw new UnauthorizedError({
message: "Access denied: GCP service account not allowed.",
detail: {
reasonCode: "service_account_not_allowed",
identityId: identity.id,
orgId: identity.orgId,
identityName: identity.name
}
});
}
if (identityGcpAuth.type === "gce" && identityGcpAuth.allowedProjects) {
// validate if the project that the service account belongs to is in the list of allowed projects
const isProjectAllowed = identityGcpAuth.allowedProjects
.split(",")
.map((project) => project.trim())
.some((project) => project === gcpIdentityDetails.computeEngineDetails?.project_id);
if (!isProjectAllowed)
throw new UnauthorizedError({
message: "Access denied: GCP project not allowed.",
detail: {
reasonCode: "project_not_allowed",
identityId: identity.id,
orgId: identity.orgId,
identityName: identity.name
}
});
}
if (identityGcpAuth.type === "gce" && identityGcpAuth.allowedZones) {
const isZoneAllowed = identityGcpAuth.allowedZones
.split(",")
.map((zone) => zone.trim())
.some((zone) => zone === gcpIdentityDetails.computeEngineDetails?.zone);
if (!isZoneAllowed)
throw new UnauthorizedError({
message: "Access denied: GCP zone not allowed.",
detail: {
reasonCode: "zone_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.GCP_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: identityGcpAuth.identityId,
identityName: identity.name,
authMethod: IdentityAuthMethod.GCP_AUTH,
orgId: tokenScopeOrg.id,
rootOrgId: tokenRootOrgId,
parentOrgId: tokenParentOrgId,
subOrganizationId,
accessTokenTTL: Number(identityGcpAuth.accessTokenTTL),
accessTokenMaxTTL: Number(identityGcpAuth.accessTokenMaxTTL),
accessTokenNumUsesLimit: Number(identityGcpAuth.accessTokenNumUsesLimit),
accessTokenPeriod: Number(identityGcpAuth.accessTokenPeriod) || 0,
accessTokenTrustedIps: identityGcpAuth.accessTokenTrustedIps as TIp[]
});
if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
authAttemptCounter.add(1, {
"infisical.identity.id": identityGcpAuth.identityId,
"infisical.identity.name": identity.name,
"infisical.organization.id": org.id,
"infisical.organization.name": org.name,
"infisical.identity.auth_method": AuthAttemptAuthMethod.GCP_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.GCP_AUTH,
result: AuthAttemptAuthResult.SUCCESS,
orgId: org.id
});
return { accessToken, identityGcpAuth, identityAccessToken, identity };
} catch (error) {
if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
authAttemptCounter.add(1, {
"infisical.identity.id": identityGcpAuth.identityId,
"infisical.identity.name": identity.name,
"infisical.organization.id": org.id,
"infisical.organization.name": org.name,
"infisical.identity.auth_method": AuthAttemptAuthMethod.GCP_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.GCP_AUTH,
result: AuthAttemptAuthResult.FAILURE,
orgId: org.id,
error
});
throw error;
}
};
const attachGcpAuth = async ({
identityId,
type,
allowedServiceAccounts,
allowedProjects,
allowedZones,
accessTokenTTL,
accessTokenMaxTTL,
accessTokenNumUsesLimit,
accessTokenTrustedIps,
actorId,
actorAuthMethod,
actor,
actorOrgId,
isActorSuperAdmin
}: TAttachGcpAuthDTO) => {
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.GCP_AUTH)) {
throw new BadRequestError({
message: "Failed to add GCP Auth to already configured identity"
});
}
if (accessTokenMaxTTL > 0 && accessTokenTTL > accessTokenMaxTTL) {
throw new BadRequestError({ message: "Access token TTL cannot be greater than max TTL" });
}
if (!hasGcpTrustBinding({ type, allowedServiceAccounts, allowedProjects })) {
throw new BadRequestError({ message: GCP_TRUST_BINDING_REQUIRED_MESSAGE });
}
await assertIdentityAuthAccessAllowed(
{ permissionService, orgDAL },
{
identityId,
orgId: identityMembershipOrg.scopeOrgId,
projectId: identityMembershipOrg.identity.projectId,
action: OrgPermissionIdentityActions.EditAuth,
baseMessage: "Failed to add gcp 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 identityGcpAuth = await identityGcpAuthDAL.transaction(async (tx) => {
const doc = await identityGcpAuthDAL.create(
{
identityId: identityMembershipOrg.identity.id,
type,
allowedServiceAccounts,
allowedProjects,
allowedZones,
accessTokenMaxTTL,
accessTokenTTL,
accessTokenNumUsesLimit,
accessTokenTrustedIps: JSON.stringify(reformattedAccessTokenTrustedIps)
},
tx
);
await emitIdentityAuthMethodChanged(
eventEmitter,
{
membership: identityMembershipOrg,
authMethod: IdentityAuthMethod.GCP_AUTH,
change: IdentityAuthMethodChange.Added,
actor,
actorId
},
tx
);
return doc;
});
await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.GCP_AUTH);
return { ...identityGcpAuth, orgId: identityMembershipOrg.scopeOrgId };
};
const updateGcpAuth = async ({
identityId,
type,
allowedServiceAccounts,
allowedProjects,
allowedZones,
accessTokenTTL,
accessTokenMaxTTL,
accessTokenNumUsesLimit,
accessTokenTrustedIps,
actorId,
actorAuthMethod,
actor,
actorOrgId,
isActorSuperAdmin
}: TUpdateGcpAuthDTO) => {
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.GCP_AUTH)) {
throw new BadRequestError({
message: "Failed to update GCP Auth"
});
}
const identityGcpAuth = await identityGcpAuthDAL.findOne({ identityId });
if (
!hasGcpTrustBinding({
type: type ?? identityGcpAuth.type,
allowedServiceAccounts: allowedServiceAccounts ?? identityGcpAuth.allowedServiceAccounts,
allowedProjects: allowedProjects ?? identityGcpAuth.allowedProjects
})
) {
throw new BadRequestError({ message: GCP_TRUST_BINDING_REQUIRED_MESSAGE });
}
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 gcp 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 updatedGcpAuth = await identityGcpAuthDAL.transaction(async (tx) => {
const doc = await identityGcpAuthDAL.updateById(
identityGcpAuth.id,
{
type,
allowedServiceAccounts,
allowedProjects,
allowedZones,
accessTokenMaxTTL,
accessTokenTTL,
accessTokenNumUsesLimit,
accessTokenTrustedIps: reformattedAccessTokenTrustedIps
? JSON.stringify(reformattedAccessTokenTrustedIps)
: undefined
},
tx
);
await emitIdentityAuthMethodChanged(
eventEmitter,
{
membership: identityMembershipOrg,
authMethod: IdentityAuthMethod.GCP_AUTH,
change: IdentityAuthMethodChange.Updated,
actor,
actorId
},
tx
);
return doc;
});
await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.GCP_AUTH);
return {
...updatedGcpAuth,
orgId: identityMembershipOrg.scopeOrgId
};
};
const getGcpAuth = async ({ identityId, actorId, actor, actorAuthMethod, actorOrgId }: TGetGcpAuthDTO) => {
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.GCP_AUTH)) {
throw new BadRequestError({
message: "The identity does not have GCP Auth attached"
});
}
const identityGcpAuth = await identityGcpAuthDAL.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 { ...identityGcpAuth, orgId: identityMembershipOrg.scopeOrgId };
};
const revokeIdentityGcpAuth = async ({
identityId,
actorId,
actor,
actorAuthMethod,
actorOrgId,
isActorSuperAdmin
}: TRevokeGcpAuthDTO) => {
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.GCP_AUTH)) {
throw new BadRequestError({
message: "The identity does not have gcp auth"
});
}
await assertIdentityAuthAccessAllowed(
{ permissionService, orgDAL },
{
identityId,
orgId: identityMembershipOrg.scopeOrgId,
projectId: identityMembershipOrg.identity.projectId,
action: OrgPermissionIdentityActions.RevokeAuth,
baseMessage: "Failed to revoke gcp auth of identity with more privileged role",
actor,
actorId,
actorAuthMethod,
actorOrgId
}
);
await validateIdentityUpdateForSuperAdminPrivileges(identityId, isActorSuperAdmin);
const revokedIdentityGcpAuth = await identityGcpAuthDAL.transaction(async (tx) => {
const deletedGcpAuth = await identityGcpAuthDAL.delete({ identityId }, tx);
await identityAccessTokenDAL.delete({ identityId, authMethod: IdentityAuthMethod.GCP_AUTH }, tx);
await emitIdentityAuthMethodChanged(
eventEmitter,
{
membership: identityMembershipOrg,
authMethod: IdentityAuthMethod.GCP_AUTH,
change: IdentityAuthMethodChange.Removed,
actor,
actorId
},
tx
);
return { ...deletedGcpAuth?.[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.GCP_AUTH
});
await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.GCP_AUTH);
return revokedIdentityGcpAuth;
};
return {
login,
attachGcpAuth,
updateGcpAuth,
getGcpAuth,
revokeIdentityGcpAuth
};
};