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 { AxiosError, AxiosRequestConfig, AxiosResponse } from "axios";
import https from "https";
import picomatch from "picomatch";
import RE2 from "re2";
import {
AccessScope,
ActionProjectType,
IdentityAuthMethod,
OrganizationActionScope,
TIdentityKubernetesAuthsUpdate
} from "@app/db/schemas";
import { TIdentityAuthTemplates } from "@app/db/schemas/identity-auth-templates";
import { TGatewayPoolDALFactory } from "@app/ee/services/gateway-pool/gateway-pool-dal";
import { assertIndividualGatewayAllowed } from "@app/ee/services/gateway-pool/gateway-pool-policy-fns";
import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
import { TGatewayV2DALFactory } from "@app/ee/services/gateway-v2/gateway-v2-dal";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { TGatewayV2ConnectionDetails } from "@app/ee/services/gateway-v2/gateway-v2-types";
import { TIdentityAuthTemplateDALFactory } from "@app/ee/services/identity-auth-template/identity-auth-template-dal";
import { IdentityAuthTemplateMethod } from "@app/ee/services/identity-auth-template/identity-auth-template-enums";
import { assertTemplateUnchangedForLink } from "@app/ee/services/identity-auth-template/identity-auth-template-fns";
import { TKubernetesTemplateFields } from "@app/ee/services/identity-auth-template/identity-auth-template-types";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import {
OrgPermissionGatewayActions,
OrgPermissionGatewayPoolActions,
OrgPermissionIdentityActions,
OrgPermissionMachineIdentityAuthTemplateActions,
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 { getMissingGatewayMessage, getRetiredGatewayMessage } from "@app/lib/gateway-v2/gateway-errors";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
import { GatewayHttpProxyActions, GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
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 { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { getSharedHttpsAgent, safeRequest } from "@app/lib/validator/safe-request";
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 { TKmsServiceFactory } from "../kms/kms-service";
import { KmsDataKey } from "../kms/kms-types";
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 { TIdentityKubernetesAuthDALFactory } from "./identity-kubernetes-auth-dal";
import { handleAxiosError, isKnownError, KubernetesAuthErrorContext } from "./identity-kubernetes-auth-error-handlers";
import {
extractK8sUsername,
getJwtFingerprintForLog,
getKubernetesHostname,
getKubernetesServerName,
getKubernetesStatusForLog,
withKubernetesHostScheme
} from "./identity-kubernetes-auth-fns";
import {
IdentityKubernetesAuthTokenReviewMode,
TAttachKubernetesAuthDTO,
TCreateTokenReviewResponse,
TGetKubernetesAuthDTO,
TLoginKubernetesAuthDTO,
TRevokeKubernetesAuthDTO,
TUpdateKubernetesAuthDTO
} from "./identity-kubernetes-auth-types";
import {
GatewayRequestExecutor,
TKubernetesConnectionFields,
validateKubernetesConnectionFields,
validateKubernetesHostConnectivity,
validateTokenReviewerPermissions
} from "./identity-kubernetes-auth-validators";
const TOKEN_REVIEW_TIMEOUT_MS = 10_000;
// A TokenReview response is a few KB; the largest part is the echoed token, itself capped at 8KB
// by the route schema. Bounded so an operator-supplied host cannot make us buffer an arbitrary body.
const TOKEN_REVIEW_MAX_RESPONSE_BYTES = 64 * 1024;
type TIdentityKubernetesAuthServiceFactoryDep = {
identityDAL: Pick<TIdentityDALFactory, "findById">;
identityKubernetesAuthDAL: Pick<
TIdentityKubernetesAuthDALFactory,
"create" | "findOne" | "transaction" | "updateById" | "delete"
>;
identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "delete">;
identityAuthTemplateDAL: Pick<TIdentityAuthTemplateDALFactory, "findByIdAndOrgId" | "findByIdForShare">;
membershipIdentityDAL: Pick<TMembershipIdentityDALFactory, "findOne" | "update" | "getIdentityById">;
keyStore: Pick<TKeyStoreFactory, "setItemWithExpiryNX">;
permissionService: Pick<
TPermissionServiceFactory,
"getOrgPermission" | "getProjectPermission" | "getActorGrantAbilities"
>;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
gatewayV2Service: TGatewayV2ServiceFactory;
gatewayV2DAL: Pick<TGatewayV2DALFactory, "find">;
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "pickHealthyGateway" | "runWithPoolFailover">;
gatewayPoolDAL: Pick<TGatewayPoolDALFactory, "findById">;
orgDAL: Pick<TOrgDALFactory, "findById" | "findOne" | "findEffectiveOrgMembership">;
identityAccessTokenService: Pick<
TIdentityAccessTokenServiceFactory,
"issueIdentityAccessToken" | "revokeTokensForIdentityAuthMethod" | "invalidateTrustedIpsCache"
>;
eventEmitter: TEventEmitter;
};
export type TIdentityKubernetesAuthServiceFactory = ReturnType<typeof identityKubernetesAuthServiceFactory>;
const GATEWAY_AUTH_DEFAULT_HOST = "https://kubernetes.default.svc.cluster.local";
// The retired gateway v1 `gatewayId` column is still populated on rows that were pinned to a v1
// gateway. Nothing can resolve it any more, but it still means "this must not be dialed directly",
// so every gateway-or-direct decision has to treat it as a configured gateway and fail closed.
// Reading only gatewayV2Id/gatewayPoolId would send the token reviewer JWT straight to the
// customer's Kubernetes API server from the platform.
const isPinnedToRetiredGateway = (row: {
gatewayId?: string | null;
gatewayV2Id?: string | null;
gatewayPoolId?: string | null;
}) => Boolean(row.gatewayId) && !row.gatewayV2Id && !row.gatewayPoolId;
export const identityKubernetesAuthServiceFactory = ({
identityDAL,
identityKubernetesAuthDAL,
identityAuthTemplateDAL,
membershipIdentityDAL,
keyStore,
identityAccessTokenDAL,
permissionService,
licenseService,
gatewayV2Service,
gatewayV2DAL,
kmsService,
gatewayPoolService,
gatewayPoolDAL,
orgDAL,
identityAccessTokenService,
eventEmitter
}: TIdentityKubernetesAuthServiceFactoryDep) => {
const $gatewayProxyWrapper = async <T>(
inputs: {
gatewayId?: string;
gatewayPoolId?: string;
targetHost?: string;
targetPort?: number;
caCert?: string;
verifyTlsCertificate?: boolean;
reviewTokenThroughGateway: boolean;
},
gatewayCallback: (host: string, port: number, httpsAgent?: https.Agent) => Promise<T>
): Promise<T> => {
let gatewayHttpsAgent: https.Agent | undefined;
if (!inputs.reviewTokenThroughGateway) {
gatewayHttpsAgent = getSharedHttpsAgent({
ca: inputs.caCert || undefined,
rejectUnauthorized: inputs.verifyTlsCertificate ?? true,
servername: inputs.targetHost
});
}
const $proxyThroughGatewayV2 = async (details: TGatewayV2ConnectionDetails) =>
withGatewayV2Proxy(
async (port) => {
const res = await gatewayCallback(
inputs.reviewTokenThroughGateway ? "http://localhost" : "https://localhost",
port,
gatewayHttpsAgent
);
return res;
},
{
protocol: inputs.reviewTokenThroughGateway ? GatewayProxyProtocol.Http : GatewayProxyProtocol.Tcp,
...details,
httpsAgent: gatewayHttpsAgent
}
);
if (inputs.gatewayPoolId) {
const { result } = await gatewayPoolService.runWithPoolFailover(
{ poolId: inputs.gatewayPoolId },
async (gatewayId) => {
const details = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({
gatewayId,
targetHost: inputs.targetHost ?? GATEWAY_AUTH_DEFAULT_HOST,
targetPort: inputs.targetPort ?? 443
});
if (!details) {
throw new NotFoundError({ message: `Connection details for gateway with ID '${gatewayId}' not found` });
}
return $proxyThroughGatewayV2(details);
}
);
return result;
}
const gatewayV2ConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({
gatewayId: inputs.gatewayId!,
targetHost: inputs.targetHost ?? GATEWAY_AUTH_DEFAULT_HOST,
targetPort: inputs.targetPort ?? 443
});
// Falling through here would silently bypass the gateway this auth method is pinned to.
if (!gatewayV2ConnectionDetails) {
throw new NotFoundError({ message: getMissingGatewayMessage(inputs.gatewayId!) });
}
return $proxyThroughGatewayV2(gatewayV2ConnectionDetails);
};
/**
* Supports two modes:
* - Gateway reviewer mode: Gateway uses its own service account (no kubernetesHost option)
* - API mode through gateway: Gateway proxies TCP connection to kubernetesHost (kubernetesHost option provided)
*/
const $createGatewayValidationRequest = (
gatewayId: string,
options?: { kubernetesHost?: string; caCert?: string; verifyTlsCertificate?: boolean }
): GatewayRequestExecutor => {
const useGatewayServiceAccount = !options?.kubernetesHost;
let targetHost: string | undefined;
let targetPort: number | undefined;
if (options?.kubernetesHost) {
const parsedUrl = new URL(options.kubernetesHost);
targetHost = parsedUrl.hostname;
targetPort = parsedUrl.port ? Number(parsedUrl.port) : 443;
}
return async <T>(method: "get" | "post", url: string, body?: object, headers?: Record<string, string>) => {
let response: AxiosResponse<T> | undefined;
await $gatewayProxyWrapper(
{
gatewayId,
reviewTokenThroughGateway: useGatewayServiceAccount,
targetHost,
targetPort,
caCert: options?.caCert,
verifyTlsCertificate: options?.verifyTlsCertificate
},
async (host: string, port: number, httpsAgent?: https.Agent) => {
const config: AxiosRequestConfig = {
headers: {
"Content-Type": "application/json",
...(useGatewayServiceAccount
? { "x-infisical-action": GatewayHttpProxyActions.UseGatewayK8sServiceAccount }
: headers)
},
timeout: 10000,
signal: AbortSignal.timeout(10000),
validateStatus: () => true,
...(httpsAgent ? { httpsAgent } : {})
};
if (method === "get") {
response = await request.get<T>(`${host}:${port}${url}`, config);
} else {
response = await request.post<T>(`${host}:${port}${url}`, body, config);
}
return response.data;
}
);
if (!response) {
throw new BadRequestError({
name: "GatewayConnectionError",
message: "Failed to get response from gateway"
});
}
return response;
};
};
const $validateTemplateSourcedConnection = async (templateName: string, fields: TKubernetesConnectionFields) => {
const issues = validateKubernetesConnectionFields(fields);
if (issues.length > 0) {
throw new BadRequestError({
message: `Cannot use auth template '${templateName}': ${issues[0].message}. The template's gateway or gateway pool may have been deleted; update the template's connection settings and try again.`
});
}
if (
(fields.tokenReviewMode ?? IdentityKubernetesAuthTokenReviewMode.Api) ===
IdentityKubernetesAuthTokenReviewMode.Api &&
fields.kubernetesHost &&
!fields.gatewayId &&
!fields.gatewayPoolId
) {
await blockLocalAndPrivateIpAddresses(withKubernetesHostScheme(fields.kubernetesHost));
}
};
const login = async ({ identityId, jwt: serviceAccountJwt, organizationSlug }: TLoginKubernetesAuthDTO) => {
const authMetricStartTime = performance.now();
const appCfg = getConfig();
const identityKubernetesAuth = await identityKubernetesAuthDAL.findOne({ identityId });
if (!identityKubernetesAuth) {
throw new NotFoundError({
message: "Kubernetes auth method not found for identity, did you configure Kubernetes auth?"
});
}
if (isPinnedToRetiredGateway(identityKubernetesAuth)) {
throw new BadRequestError({ message: getRetiredGatewayMessage("This Kubernetes auth method") });
}
const identity = await requestMemoize(requestMemoKeys.identityFindById(identityKubernetesAuth.identityId), () =>
identityDAL.findById(identityKubernetesAuth.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 { decryptor } = await kmsService.createCipherPairWithDataKey({
type: KmsDataKey.Organization,
orgId: identity.orgId
});
let caCert = "";
if (identityKubernetesAuth.encryptedKubernetesCaCertificate) {
caCert = decryptor({ cipherTextBlob: identityKubernetesAuth.encryptedKubernetesCaCertificate }).toString();
}
if (appCfg.isCloud) {
logger.info(`Processing k8s auth for the identity=${identity.id}`);
}
const tokenReviewCallbackRaw = async ({
host = identityKubernetesAuth.kubernetesHost,
port,
// The gateway tunnels to a local proxy port, so the hop safeRequest would validate is
// localhost rather than the Kubernetes host, and the host it does reach sits in the
// gateway's network rather than ours.
isThroughGateway = false
}: { host?: string | null; port?: number; isThroughGateway?: boolean } = {}) => {
logger.info({ host, port }, "tokenReviewCallbackRaw: Processing kubernetes token review using raw API");
if (!host || !identityKubernetesAuth.kubernetesHost) {
throw new BadRequestError({
message: "Kubernetes host is required when token review mode is set to API"
});
}
let tokenReviewerJwt = "";
if (identityKubernetesAuth.encryptedKubernetesTokenReviewerJwt) {
tokenReviewerJwt = decryptor({
cipherTextBlob: identityKubernetesAuth.encryptedKubernetesTokenReviewerJwt
}).toString();
} else {
// if no token reviewer is provided means the incoming token has to act as reviewer
tokenReviewerJwt = serviceAccountJwt;
}
const servername = getKubernetesServerName(identityKubernetesAuth.kubernetesHost);
const tunnelServername = getKubernetesHostname(identityKubernetesAuth.kubernetesHost);
const baseUrl = port ? `${host}:${port}` : withKubernetesHostScheme(host);
const url = `${baseUrl}/apis/authentication.k8s.io/v1/tokenreviews`;
const body = {
apiVersion: "authentication.k8s.io/v1",
kind: "TokenReview",
spec: {
token: serviceAccountJwt,
...(identityKubernetesAuth.allowedAudience ? { audiences: [identityKubernetesAuth.allowedAudience] } : {})
}
};
const config = {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${tokenReviewerJwt}`
},
signal: AbortSignal.timeout(TOKEN_REVIEW_TIMEOUT_MS),
timeout: TOKEN_REVIEW_TIMEOUT_MS,
maxContentLength: TOKEN_REVIEW_MAX_RESPONSE_BYTES
};
const res = await (
isThroughGateway
? request.post<TCreateTokenReviewResponse>(url, body, {
...config,
httpsAgent: getSharedHttpsAgent({
ca: caCert || undefined,
rejectUnauthorized: identityKubernetesAuth.verifyTlsCertificate,
servername: tunnelServername
})
})
: safeRequest.post<TCreateTokenReviewResponse>(url, body, {
...config,
ca: caCert || undefined,
rejectUnauthorized: identityKubernetesAuth.verifyTlsCertificate,
servername
})
).catch((err) => {
const tokenReviewerJwtFingerprint = getJwtFingerprintForLog(tokenReviewerJwt);
const serviceAccountJwtFingerprint = getJwtFingerprintForLog(serviceAccountJwt);
if (err instanceof AxiosError) {
const status = err.response?.status;
const level = status === 401 || status === 403 ? "warn" : "error";
logger[level](
{
host,
port,
status: err.response?.status,
code: err.code,
...getKubernetesStatusForLog(err.response?.data, [tokenReviewerJwt, serviceAccountJwt]),
tokenReviewerJwtFingerprint,
serviceAccountJwtFingerprint
},
`tokenReviewCallbackRaw: Kubernetes token review request error (request error) [identityId=${identityKubernetesAuth.identityId}] [status=${err.response?.status}] [code=${err.code}]`
);
throw handleAxiosError(
err,
{ host, port, credentials: [tokenReviewerJwt, serviceAccountJwt] },
KubernetesAuthErrorContext.KubernetesApiServer
);
}
logger[isKnownError(err) ? "warn" : "error"](
{ error: err as Error, host, port, tokenReviewerJwtFingerprint, serviceAccountJwtFingerprint },
`tokenReviewCallbackRaw: Kubernetes token review request error (non-request error) [identityId=${identityKubernetesAuth.identityId}]`
);
if (isKnownError(err)) {
throw err;
}
throw new BadRequestError({
name: "KubernetesTokenReviewError",
message: (err as Error).message || "Unexpected error during token review",
error: err
});
});
return res.data;
};
const tokenReviewCallbackThroughGateway = async (host: string, port?: number) => {
// localPort is the correlation key into the gatewayTunnel:* lines, which carry the tunnel id
// and outlive this request: the tunnel is torn down after the response is already logged.
const gatewayIdForLog = identityKubernetesAuth.gatewayV2Id ?? identityKubernetesAuth.gatewayPoolId;
logger.info(
{ host, port },
`tokenReviewCallbackThroughGateway: Processing kubernetes token review using gateway [identityId=${identityKubernetesAuth.identityId}] [gatewayId=${gatewayIdForLog}] [localPort=${port}]`
);
const startedAt = Date.now();
const res = await request
.post<TCreateTokenReviewResponse>(
`${host}:${port}/apis/authentication.k8s.io/v1/tokenreviews`,
{
apiVersion: "authentication.k8s.io/v1",
kind: "TokenReview",
spec: {
token: serviceAccountJwt,
...(identityKubernetesAuth.allowedAudience
? { audiences: [identityKubernetesAuth.allowedAudience] }
: {})
}
},
{
headers: {
"Content-Type": "application/json",
"x-infisical-action": GatewayHttpProxyActions.UseGatewayK8sServiceAccount
},
signal: AbortSignal.timeout(10000),
timeout: 10000
}
)
.catch((err) => {
logger.error(
{ error: err as Error, host, port },
`tokenReviewCallbackThroughGateway: Kubernetes token review request error [identityId=${identityKubernetesAuth.identityId}] [gatewayId=${gatewayIdForLog}] [localPort=${port}] [elapsedMs=${Date.now() - startedAt}]`
);
if (err instanceof AxiosError) {
throw handleAxiosError(
err,
{ host, port, credentials: [serviceAccountJwt] },
KubernetesAuthErrorContext.GatewayProxy
);
}
if (isKnownError(err)) {
throw err;
}
throw new BadRequestError({
name: "GatewayTokenReviewError",
message: (err as Error).message || "Unexpected error during gateway token review",
error: err
});
});
const reviewStatus = res.data?.status;
const authenticated = Boolean(reviewStatus && "authenticated" in reviewStatus && reviewStatus.authenticated);
logger.info(
`tokenReviewCallbackThroughGateway: Kubernetes token review completed [identityId=${identityKubernetesAuth.identityId}] [gatewayId=${gatewayIdForLog}] [localPort=${port}] [authenticated=${authenticated}] [elapsedMs=${Date.now() - startedAt}]`
);
return res.data;
};
let data: TCreateTokenReviewResponse | undefined;
if (identityKubernetesAuth.tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Gateway) {
if (!identityKubernetesAuth.gatewayV2Id && !identityKubernetesAuth.gatewayPoolId) {
throw new BadRequestError({
message: "Gateway or Gateway Pool is required when token review mode is set to Gateway"
});
}
data = await $gatewayProxyWrapper(
{
gatewayId: identityKubernetesAuth.gatewayPoolId
? undefined
: (identityKubernetesAuth.gatewayV2Id as string),
gatewayPoolId: identityKubernetesAuth.gatewayPoolId ?? undefined,
caCert: caCert || undefined,
verifyTlsCertificate: identityKubernetesAuth.verifyTlsCertificate,
reviewTokenThroughGateway: true
},
tokenReviewCallbackThroughGateway
);
} else if (identityKubernetesAuth.tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api) {
if (!identityKubernetesAuth.kubernetesHost) {
throw new BadRequestError({
message: "Kubernetes host is required when token review mode is set to API"
});
}
let { kubernetesHost } = identityKubernetesAuth;
if (kubernetesHost.startsWith("https://") || kubernetesHost.startsWith("http://")) {
kubernetesHost = new RE2("^https?:\\/\\/").replace(kubernetesHost, "");
}
const [k8sHost, k8sPort] = kubernetesHost.split(":");
const hasGateway = identityKubernetesAuth.gatewayV2Id || identityKubernetesAuth.gatewayPoolId;
data = hasGateway
? await $gatewayProxyWrapper(
{
gatewayId: identityKubernetesAuth.gatewayPoolId
? undefined
: (identityKubernetesAuth.gatewayV2Id as string),
gatewayPoolId: identityKubernetesAuth.gatewayPoolId ?? undefined,
targetHost: k8sHost,
targetPort: k8sPort ? Number(k8sPort) : 443,
caCert: caCert || undefined,
verifyTlsCertificate: identityKubernetesAuth.verifyTlsCertificate,
reviewTokenThroughGateway: false
},
(gatewayHost, gatewayPort) =>
tokenReviewCallbackRaw({ host: gatewayHost, port: gatewayPort, isThroughGateway: true })
)
: await tokenReviewCallbackRaw();
} else {
throw new BadRequestError({
message: `Invalid token review mode: ${identityKubernetesAuth.tokenReviewMode}`
});
}
if (!data) {
throw new BadRequestError({
message: "Failed to review token"
});
}
if ("error" in data.status)
throw new UnauthorizedError({
message: data.status.error,
name: "KubernetesTokenReviewError",
detail: {
reasonCode: "token_review_error",
identityId: identity.id,
orgId: identity.orgId,
identityName: identity.name
}
});
// check the response to determine if the token is valid
if (!(data.status && data.status.authenticated))
throw new UnauthorizedError({
message: "Kubernetes token not authenticated",
name: "KubernetesTokenReviewError",
detail: {
reasonCode: "token_not_authenticated",
identityId: identity.id,
orgId: identity.orgId,
identityName: identity.name
}
});
const { namespace: targetNamespace, name: targetName } = extractK8sUsername(data.status.user.username);
if (identityKubernetesAuth.allowedNamespaces) {
// validate if [targetNamespace] is in the list of allowed namespaces
const isNamespaceAllowed = identityKubernetesAuth.allowedNamespaces
.split(",")
.map((namespace) => namespace.trim())
.some((namespace) => namespace === targetNamespace || picomatch.isMatch(targetNamespace, namespace));
if (!isNamespaceAllowed)
throw new UnauthorizedError({
message: "Access denied: K8s namespace not allowed.",
detail: {
reasonCode: "namespace_not_allowed",
identityId: identity.id,
orgId: identity.orgId,
identityName: identity.name
}
});
}
if (identityKubernetesAuth.allowedNames) {
// validate if [targetName] is in the list of allowed names
const isNameAllowed = identityKubernetesAuth.allowedNames
.split(",")
.map((name) => name.trim())
.some((name) => name === targetName || picomatch.isMatch(targetName, name));
if (!isNameAllowed)
throw new UnauthorizedError({
message: "Access denied: K8s name not allowed.",
detail: {
reasonCode: "name_not_allowed",
identityId: identity.id,
orgId: identity.orgId,
identityName: identity.name
}
});
}
if (identityKubernetesAuth.allowedAudience) {
// validate if [audience] is in the list of allowed audiences
const isAudienceAllowed = data.status.audiences.some(
(audience) => audience === identityKubernetesAuth.allowedAudience
);
if (!isAudienceAllowed)
throw new UnauthorizedError({
message: "Access denied: K8s audience not allowed.",
detail: {
reasonCode: "audience_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.KUBERNETES_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: identityKubernetesAuth.identityId,
identityName: identity.name,
authMethod: IdentityAuthMethod.KUBERNETES_AUTH,
orgId: tokenScopeOrg.id,
rootOrgId: tokenRootOrgId,
parentOrgId: tokenParentOrgId,
subOrganizationId,
accessTokenTTL: Number(identityKubernetesAuth.accessTokenTTL),
accessTokenMaxTTL: Number(identityKubernetesAuth.accessTokenMaxTTL),
accessTokenNumUsesLimit: Number(identityKubernetesAuth.accessTokenNumUsesLimit),
accessTokenPeriod: Number(identityKubernetesAuth.accessTokenPeriod) || 0,
accessTokenTrustedIps: identityKubernetesAuth.accessTokenTrustedIps as TIp[],
identityAuth: {
kubernetes: {
namespace: targetNamespace,
name: targetName
}
}
});
if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
authAttemptCounter.add(1, {
"infisical.identity.id": identityKubernetesAuth.identityId,
"infisical.identity.name": identity.name,
"infisical.organization.id": org.id,
"infisical.organization.name": org.name,
"infisical.identity.auth_method": AuthAttemptAuthMethod.KUBERNETES_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.KUBERNETES_AUTH,
result: AuthAttemptAuthResult.SUCCESS,
orgId: org.id
});
return { accessToken, identityKubernetesAuth, identityAccessToken, identity };
} catch (error) {
if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
authAttemptCounter.add(1, {
"infisical.identity.id": identityKubernetesAuth.identityId,
"infisical.identity.name": identity.name,
"infisical.organization.id": org.id,
"infisical.organization.name": org.name,
"infisical.identity.auth_method": AuthAttemptAuthMethod.KUBERNETES_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.KUBERNETES_AUTH,
result: AuthAttemptAuthResult.FAILURE,
orgId: org.id,
error
});
if (isKnownError(error)) {
throw error;
}
logger.error({ error, identityId }, "Unexpected error during Kubernetes auth login");
throw new BadRequestError({
name: "KubernetesAuthLoginError",
message: (error as Error).message || "An unexpected error occurred during Kubernetes authentication",
error
});
}
};
const attachKubernetesAuth = async (dto: TAttachKubernetesAuthDTO) => {
const {
identityId,
templateId,
allowedNamespaces,
allowedNames,
accessTokenTTL,
accessTokenMaxTTL,
accessTokenNumUsesLimit,
accessTokenTrustedIps,
actorId,
actorAuthMethod,
actor,
actorOrgId,
isActorSuperAdmin
} = dto;
let { gatewayId, gatewayPoolId, kubernetesHost, caCert, verifyTlsCertificate, tokenReviewerJwt, allowedAudience } =
dto;
let { tokenReviewMode } = dto;
// the route leaves these two optional (no zod default) so template-managed values can
// be detected and rejected when a template is used; default them for the custom path
tokenReviewMode = tokenReviewMode ?? IdentityKubernetesAuthTokenReviewMode.Api;
allowedAudience = allowedAudience ?? "";
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.KUBERNETES_AUTH)) {
throw new BadRequestError({
message: "Failed to add Kubernetes 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 kubernetes auth to identity with more privileged role",
actor,
actorId,
actorAuthMethod,
actorOrgId
}
);
const plan = await licenseService.getPlan(identityMembershipOrg.scopeOrgId);
const { encryptor, decryptor } = await kmsService.createCipherPairWithDataKey({
type: KmsDataKey.Organization,
orgId: identityMembershipOrg.scopeOrgId
});
let template: TIdentityAuthTemplates | undefined;
if (templateId) {
if (!plan.machineIdentityAuthTemplates) {
throw new BadRequestError({
message:
"Failed to use identity auth template due to plan restriction. Upgrade plan to access machine identity auth templates."
});
}
const { permission: orgPermission } = await permissionService.getOrgPermission({
scope: OrganizationActionScope.Any,
actor,
actorId,
orgId: identityMembershipOrg.scopeOrgId,
actorAuthMethod,
actorOrgId
});
ForbiddenError.from(orgPermission).throwUnlessCan(
OrgPermissionMachineIdentityAuthTemplateActions.AttachTemplates,
OrgPermissionSubjects.MachineIdentityAuthTemplate
);
template = await identityAuthTemplateDAL.findByIdAndOrgId(templateId, identityMembershipOrg.scopeOrgId);
if (!template || template.authMethod !== IdentityAuthTemplateMethod.KUBERNETES) {
throw new NotFoundError({ message: `Kubernetes auth template with ID '${templateId}' not found` });
}
const templateFields = JSON.parse(
decryptor({ cipherTextBlob: template.templateFields }).toString()
) as TKubernetesTemplateFields;
kubernetesHost = templateFields.kubernetesHost ?? null;
caCert = templateFields.caCert || undefined;
tokenReviewerJwt = templateFields.tokenReviewerJwt || undefined;
tokenReviewMode = templateFields.tokenReviewMode;
if (isPinnedToRetiredGateway(template)) {
throw new BadRequestError({
message: getRetiredGatewayMessage(`Auth template '${template.name}'`)
});
}
gatewayId = template.gatewayV2Id ?? null;
gatewayPoolId = template.gatewayPoolId ?? null;
verifyTlsCertificate = templateFields.verifyTlsCertificate ?? Boolean(templateFields.caCert?.length);
allowedAudience = templateFields.allowedAudience ?? "";
await $validateTemplateSourcedConnection(template.name, {
tokenReviewMode,
kubernetesHost,
caCert,
verifyTlsCertificate,
gatewayId,
gatewayPoolId
});
} else if (tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api && !kubernetesHost) {
throw new BadRequestError({
message: "When token review mode is set to API, a Kubernetes host must be provided"
});
}
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);
});
if (
caCert &&
caCert.length > 0 &&
verifyTlsCertificate === false &&
tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api
) {
throw new BadRequestError({
message:
"TLS certificate verification cannot be disabled when a CA certificate is provided. Either remove the CA certificate or enable verification."
});
}
const resolvedVerifyTlsCertificate = verifyTlsCertificate ?? Boolean(caCert);
if (gatewayId) {
if (!plan.gateway) {
throw new BadRequestError({
message:
"Your current plan does not support gateway usage with identity k8s auth. Please upgrade your plan or contact Infisical Sales for assistance."
});
}
const [gatewayV2] = await gatewayV2DAL.find({ id: gatewayId, orgId: identityMembershipOrg.scopeOrgId });
if (!gatewayV2) {
throw new NotFoundError({ message: getMissingGatewayMessage(gatewayId) });
}
// when the gateway comes from a template, attaching the gateway was authorized at
// template authoring time, so the actor only needs the attach-template permission
if (!template) {
const { permission: orgPermission } = await permissionService.getOrgPermission({
scope: OrganizationActionScope.Any,
actor,
actorId,
orgId: identityMembershipOrg.scopeOrgId,
actorAuthMethod,
actorOrgId
});
ForbiddenError.from(orgPermission).throwUnlessCan(
OrgPermissionGatewayActions.AttachGateways,
OrgPermissionSubjects.Gateway
);
}
// A template's gateway can predate the org's pool requirement, so it is checked here as well.
await assertIndividualGatewayAllowed({
orgDAL,
orgId: identityMembershipOrg.scopeOrgId,
gatewayId,
inheritedFrom: template ? `Auth template '${template.name}'` : undefined
});
if (tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Gateway) {
const gatewayExecutor = $createGatewayValidationRequest(gatewayId);
logger.info({ gatewayId }, "Validating gateway connectivity to Kubernetes");
await validateKubernetesHostConnectivity({ gatewayExecutor });
await validateTokenReviewerPermissions({ gatewayExecutor });
} else if (tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api && kubernetesHost) {
// API mode through gateway: gateway proxies requests with user's JWT
const gatewayExecutor = $createGatewayValidationRequest(gatewayId, {
kubernetesHost,
caCert: caCert || undefined,
verifyTlsCertificate: resolvedVerifyTlsCertificate
});
logger.info({ gatewayId, kubernetesHost }, "Validating Kubernetes connectivity through gateway");
await validateKubernetesHostConnectivity({ gatewayExecutor });
if (tokenReviewerJwt) {
await validateTokenReviewerPermissions({ gatewayExecutor, tokenReviewerJwt });
}
}
} else if (gatewayPoolId) {
if (!plan.gatewayPool) {
throw new BadRequestError({
message: "Your current plan does not support gateway pools. Please upgrade to an Enterprise plan."
});
}
if (!template) {
const { permission: orgPermission } = await permissionService.getOrgPermission({
scope: OrganizationActionScope.Any,
actor,
actorId,
orgId: identityMembershipOrg.scopeOrgId,
actorAuthMethod,
actorOrgId
});
ForbiddenError.from(orgPermission).throwUnlessCan(
OrgPermissionGatewayPoolActions.AttachGatewayPools,
OrgPermissionSubjects.GatewayPool
);
}
const pool = await gatewayPoolDAL.findById(gatewayPoolId);
if (!pool || pool.orgId !== identityMembershipOrg.scopeOrgId) {
throw new NotFoundError({ message: `Gateway pool with ID ${gatewayPoolId} not found` });
}
// Validate connectivity through a random healthy pool member
const validationGateway = await gatewayPoolService.pickHealthyGateway(gatewayPoolId);
if (tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Gateway) {
const gatewayExecutor = $createGatewayValidationRequest(validationGateway.id);
await validateKubernetesHostConnectivity({ gatewayExecutor });
await validateTokenReviewerPermissions({ gatewayExecutor });
} else if (tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api && kubernetesHost) {
const gatewayExecutor = $createGatewayValidationRequest(validationGateway.id, {
kubernetesHost,
caCert: caCert || undefined,
verifyTlsCertificate: resolvedVerifyTlsCertificate
});
await validateKubernetesHostConnectivity({ gatewayExecutor });
if (tokenReviewerJwt) {
await validateTokenReviewerPermissions({ gatewayExecutor, tokenReviewerJwt });
}
}
} else if (tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api && kubernetesHost) {
logger.info({ kubernetesHost }, "Validating Kubernetes host connectivity for new auth method");
await validateKubernetesHostConnectivity({
kubernetesHost,
caCert: caCert || undefined,
verifyTlsCertificate: resolvedVerifyTlsCertificate
});
if (tokenReviewerJwt) {
logger.info({ kubernetesHost }, "Validating token reviewer JWT permissions for new auth method");
await validateTokenReviewerPermissions({
kubernetesHost,
tokenReviewerJwt,
caCert: caCert || undefined,
verifyTlsCertificate: resolvedVerifyTlsCertificate
});
}
}
await validateIdentityUpdateForSuperAdminPrivileges(identityId, isActorSuperAdmin);
let resolvedGatewayV2Id: string | null | undefined = null;
if (!gatewayPoolId && gatewayId) {
resolvedGatewayV2Id = gatewayId;
}
const identityKubernetesAuth = await identityKubernetesAuthDAL.transaction(async (tx) => {
if (template) {
await assertTemplateUnchangedForLink(identityAuthTemplateDAL, template, tx);
}
const doc = await identityKubernetesAuthDAL.create(
{
identityId: identityMembershipOrg.identity.id,
kubernetesHost,
tokenReviewMode,
allowedNamespaces,
allowedNames,
// narrowing from the early default does not survive into this closure
allowedAudience: allowedAudience ?? "",
accessTokenMaxTTL,
accessTokenTTL,
accessTokenNumUsesLimit,
gatewayV2Id: resolvedGatewayV2Id,
gatewayPoolId: gatewayPoolId ?? null,
templateId: template?.id ?? null,
isTokenReviewerJwtTemplateSourced: Boolean(template && tokenReviewerJwt),
verifyTlsCertificate: resolvedVerifyTlsCertificate,
accessTokenTrustedIps: JSON.stringify(reformattedAccessTokenTrustedIps),
encryptedKubernetesTokenReviewerJwt: tokenReviewerJwt
? encryptor({ plainText: Buffer.from(tokenReviewerJwt) }).cipherTextBlob
: null,
encryptedKubernetesCaCertificate: caCert ? encryptor({ plainText: Buffer.from(caCert) }).cipherTextBlob : null
},
tx
);
await emitIdentityAuthMethodChanged(
eventEmitter,
{
membership: identityMembershipOrg,
authMethod: IdentityAuthMethod.KUBERNETES_AUTH,
change: IdentityAuthMethodChange.Added,
actor,
actorId
},
tx
);
return doc;
});
await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.KUBERNETES_AUTH);
return {
...identityKubernetesAuth,
caCert: caCert ?? "",
// a template's reviewer JWT is an org-scoped write-only credential; identity-level
// readers must not be able to recover it through the identity endpoints
tokenReviewerJwt: template ? "" : tokenReviewerJwt,
orgId: identityMembershipOrg.scopeOrgId,
gatewayId: identityKubernetesAuth.gatewayV2Id
};
};
const updateKubernetesAuth = async (dto: TUpdateKubernetesAuthDTO) => {
const {
identityId,
templateId,
allowedNamespaces,
allowedNames,
accessTokenTTL,
accessTokenMaxTTL,
accessTokenNumUsesLimit,
accessTokenTrustedIps,
actorId,
actorAuthMethod,
actor,
actorOrgId,
isActorSuperAdmin
} = dto;
let { kubernetesHost, caCert, verifyTlsCertificate, tokenReviewerJwt, allowedAudience, gatewayId, gatewayPoolId } =
dto;
let { tokenReviewMode } = dto;
// "" (the schema trims) matches neither persistence branch below, so the stored JWT
// survives it; it must read as "no change" everywhere else too, or it would slip past
// the template-JWT host-change guard while the stored credential stays live
if (tokenReviewerJwt === "") tokenReviewerJwt = undefined;
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.KUBERNETES_AUTH)) {
throw new BadRequestError({
message: "Failed to update Kubernetes Auth"
});
}
const identityKubernetesAuth = await identityKubernetesAuthDAL.findOne({ identityId });
if (
(accessTokenMaxTTL || identityKubernetesAuth.accessTokenMaxTTL) > 0 &&
(accessTokenTTL || identityKubernetesAuth.accessTokenMaxTTL) >
(accessTokenMaxTTL || identityKubernetesAuth.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 kubernetes auth of identity with more privileged role",
actor,
actorId,
actorAuthMethod,
actorOrgId
}
);
const plan = await licenseService.getPlan(identityMembershipOrg.scopeOrgId);
const { encryptor, decryptor } = await kmsService.createCipherPairWithDataKey({
type: KmsDataKey.Organization,
orgId: identityMembershipOrg.scopeOrgId
});
let template: TIdentityAuthTemplates | undefined;
// the UI re-sends the current templateId on every save of a linked identity, so only a
// link CHANGE requires the attach-template permission; a re-assert must stay editable
// for actors that hold identity EditAuth alone
if (templateId && templateId !== identityKubernetesAuth.templateId) {
if (!plan.machineIdentityAuthTemplates) {
throw new BadRequestError({
message:
"Failed to use identity auth template due to plan restriction. Upgrade plan to access machine identity auth templates."
});
}
const { permission: orgPermission } = await permissionService.getOrgPermission({
scope: OrganizationActionScope.Any,
actor,
actorId,
orgId: identityMembershipOrg.scopeOrgId,
actorAuthMethod,
actorOrgId
});
ForbiddenError.from(orgPermission).throwUnlessCan(
OrgPermissionMachineIdentityAuthTemplateActions.AttachTemplates,
OrgPermissionSubjects.MachineIdentityAuthTemplate
);
template = await identityAuthTemplateDAL.findByIdAndOrgId(templateId, identityMembershipOrg.scopeOrgId);
if (!template || template.authMethod !== IdentityAuthTemplateMethod.KUBERNETES) {
throw new NotFoundError({ message: `Kubernetes auth template with ID '${templateId}' not found` });
}
const templateFields = JSON.parse(
decryptor({ cipherTextBlob: template.templateFields }).toString()
) as TKubernetesTemplateFields;
kubernetesHost = templateFields.kubernetesHost ?? null;
caCert = templateFields.caCert ?? "";
tokenReviewerJwt = templateFields.tokenReviewerJwt || null;
tokenReviewMode = templateFields.tokenReviewMode;
// the template's gateway lives in columns, not the encrypted fields, so it can carry a
// foreign key and clear itself in step with the columns copied onto this row
if (isPinnedToRetiredGateway(template)) {
throw new BadRequestError({
message: getRetiredGatewayMessage(`Auth template '${template.name}'`)
});
}
gatewayId = template.gatewayV2Id ?? null;
gatewayPoolId = template.gatewayPoolId ?? null;
verifyTlsCertificate = templateFields.verifyTlsCertificate ?? Boolean(templateFields.caCert?.length);
allowedAudience = templateFields.allowedAudience ?? "";
await $validateTemplateSourcedConnection(template.name, {
tokenReviewMode,
kubernetesHost,
caCert,
verifyTlsCertificate,
gatewayId,
gatewayPoolId
});
} else if (templateId === undefined && identityKubernetesAuth.templateId) {
const hasTemplateManagedFieldChanges =
kubernetesHost !== undefined ||
caCert !== undefined ||
verifyTlsCertificate !== undefined ||
tokenReviewerJwt !== undefined ||
tokenReviewMode !== undefined ||
allowedAudience !== undefined ||
gatewayId !== undefined ||
gatewayPoolId !== undefined;
if (hasTemplateManagedFieldChanges) {
throw new BadRequestError({
message:
"This identity's Kubernetes auth connection settings are managed by an auth template. Update the template to change them, or unlink the template by setting templateId to null."
});
}
}
// a template-sourced reviewer JWT stays write-only to the caller, so it must only ever
// travel to the destination, and over the trust, that the template chose. unlinking
// deliberately leaves the credential in place to keep login working, which would otherwise
// let an actor with identity EditAuth (plus AttachGateways, for the gateway fields) repoint
// the connection and have the unauthenticated login endpoint deliver the JWT to a server or
// gateway they control, or downgrade TLS trust to intercept it in transit. keyed on the
// provenance flag rather than on the unlink itself, so a repoint in a later request is caught
// too. every field below decides where or how the JWT is sent; the host alone is not enough
// (a gateway tunnels it in API mode, and CA/verify settings guard it on the wire)
if (!template && identityKubernetesAuth.isTokenReviewerJwtTemplateSourced && tokenReviewerJwt === undefined) {
// includes the retired v1 column: unlinking a v1-pinned gateway still repoints where
// the template-sourced reviewer JWT would be sent
const storedGatewayId = identityKubernetesAuth.gatewayV2Id ?? identityKubernetesAuth.gatewayId ?? null;
const repointsConnection =
(kubernetesHost !== undefined && kubernetesHost !== identityKubernetesAuth.kubernetesHost) ||
(gatewayId !== undefined && (gatewayId ?? null) !== storedGatewayId) ||
(gatewayPoolId !== undefined && (gatewayPoolId ?? null) !== (identityKubernetesAuth.gatewayPoolId ?? null)) ||
(verifyTlsCertificate !== undefined && verifyTlsCertificate !== identityKubernetesAuth.verifyTlsCertificate) ||
(caCert !== undefined &&
caCert !==
(identityKubernetesAuth.encryptedKubernetesCaCertificate
? decryptor({ cipherTextBlob: identityKubernetesAuth.encryptedKubernetesCaCertificate }).toString()
: ""));
if (repointsConnection) {
throw new BadRequestError({
message:
"This identity still uses the token reviewer JWT copied from its auth template, so its Kubernetes connection settings (host, gateway, gateway pool, CA certificate, or TLS verification) cannot be changed. Supply your own tokenReviewerJwt with this change, or set tokenReviewerJwt to null to remove the stored one."
});
}
}
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);
});
if (gatewayId) {
if (!plan.gateway) {
throw new BadRequestError({
message:
"Your current plan does not support gateway usage with identity k8s auth. Please upgrade your plan or contact Infisical Sales for assistance."
});
}
const [gatewayV2] = await gatewayV2DAL.find({ id: gatewayId, orgId: identityMembershipOrg.scopeOrgId });
if (!gatewayV2) {
throw new NotFoundError({ message: getMissingGatewayMessage(gatewayId) });
}
if (!template) {
const { permission: orgPermission } = await permissionService.getOrgPermission({
scope: OrganizationActionScope.Any,
actor,
actorId,
orgId: identityMembershipOrg.scopeOrgId,
actorAuthMethod,
actorOrgId
});
ForbiddenError.from(orgPermission).throwUnlessCan(
OrgPermissionGatewayActions.AttachGateways,
OrgPermissionSubjects.Gateway
);
}
// A template's gateway can predate the org's pool requirement, so it is checked here as well.
await assertIndividualGatewayAllowed({
orgDAL,
orgId: identityMembershipOrg.scopeOrgId,
gatewayId,
previousGatewayId: identityKubernetesAuth.gatewayV2Id,
inheritedFrom: template ? `Auth template '${template.name}'` : undefined
});
}
// Handle gateway pool permission check
if (gatewayPoolId) {
if (!plan.gatewayPool) {
throw new BadRequestError({
message: "Your current plan does not support gateway pools. Please upgrade to an Enterprise plan."
});
}
if (!template) {
const { permission: orgPermission } = await permissionService.getOrgPermission({
scope: OrganizationActionScope.Any,
actor,
actorId,
orgId: identityMembershipOrg.scopeOrgId,
actorAuthMethod,
actorOrgId
});
ForbiddenError.from(orgPermission).throwUnlessCan(
OrgPermissionGatewayPoolActions.AttachGatewayPools,
OrgPermissionSubjects.GatewayPool
);
}
const pool = await gatewayPoolDAL.findById(gatewayPoolId);
if (!pool || pool.orgId !== identityMembershipOrg.scopeOrgId) {
throw new NotFoundError({ message: `Gateway pool with ID ${gatewayPoolId} not found` });
}
}
await validateIdentityUpdateForSuperAdminPrivileges(identityId, isActorSuperAdmin);
// Strict check to see if gateway ID is undefined. It should update the gateway ID to null if its strictly set to null.
const shouldUpdateGatewayId = Boolean(gatewayId !== undefined || gatewayPoolId !== undefined);
if (isPinnedToRetiredGateway(identityKubernetesAuth) && !shouldUpdateGatewayId) {
throw new BadRequestError({ message: getRetiredGatewayMessage("This Kubernetes auth method") });
}
let gatewayV2IdValue: string | null | undefined = null;
if (!gatewayPoolId && gatewayId) {
gatewayV2IdValue = gatewayId;
}
let gatewayPoolIdValue: string | null | undefined;
if (gatewayPoolId !== undefined) {
gatewayPoolIdValue = gatewayPoolId;
} else if (gatewayId !== undefined) {
gatewayPoolIdValue = null;
} else {
gatewayPoolIdValue = undefined;
}
const effectiveTokenReviewMode = tokenReviewMode ?? identityKubernetesAuth.tokenReviewMode;
const effectiveKubernetesHost =
kubernetesHost !== undefined ? kubernetesHost : identityKubernetesAuth.kubernetesHost;
const effectiveGatewayPoolId = gatewayPoolId !== undefined ? gatewayPoolId : identityKubernetesAuth.gatewayPoolId;
let effectiveGatewayId: string | null | undefined = null;
if (effectiveGatewayPoolId) {
effectiveGatewayId = null;
} else if (gatewayId !== undefined) {
effectiveGatewayId = gatewayId;
} else {
effectiveGatewayId = identityKubernetesAuth.gatewayV2Id;
}
let effectiveCaCert: string | undefined;
if (caCert !== undefined) {
effectiveCaCert = caCert;
} else if (identityKubernetesAuth.encryptedKubernetesCaCertificate) {
effectiveCaCert = decryptor({
cipherTextBlob: identityKubernetesAuth.encryptedKubernetesCaCertificate
}).toString();
} else {
effectiveCaCert = undefined;
}
// Auto-promote verifyTlsCertificate when the caller is supplying a non-empty
// CA in this update without explicitly setting the toggle. Required for
// backwards compatibility.
let resolvedVerifyTlsCertificate: boolean | undefined;
if (verifyTlsCertificate !== undefined) {
resolvedVerifyTlsCertificate = verifyTlsCertificate;
} else if (caCert !== undefined && caCert.length > 0) {
resolvedVerifyTlsCertificate = true;
}
const effectiveVerifyTlsCertificate = resolvedVerifyTlsCertificate ?? identityKubernetesAuth.verifyTlsCertificate;
if (
effectiveVerifyTlsCertificate &&
effectiveTokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api &&
!effectiveCaCert
) {
throw new BadRequestError({
message:
"A CA certificate is required when TLS certificate verification is enabled. Either paste the Kubernetes API server's CA certificate or disable verification."
});
}
if (
effectiveVerifyTlsCertificate === false &&
effectiveTokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api &&
effectiveCaCert &&
effectiveCaCert.length > 0
) {
throw new BadRequestError({
message:
"TLS certificate verification cannot be disabled when a CA certificate is provided. Either remove the CA certificate or enable verification."
});
}
let validationGatewayId: string | null = effectiveGatewayId ?? null;
if (!validationGatewayId && effectiveGatewayPoolId) {
const picked = await gatewayPoolService.pickHealthyGateway(effectiveGatewayPoolId);
validationGatewayId = picked.id;
}
if (validationGatewayId) {
if (effectiveTokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Gateway) {
const gatewayExecutor = $createGatewayValidationRequest(validationGatewayId);
logger.info(
{ gatewayId: validationGatewayId, gatewayPoolId: effectiveGatewayPoolId },
"Validating gateway connectivity to Kubernetes for auth method update"
);
await validateKubernetesHostConnectivity({ gatewayExecutor });
await validateTokenReviewerPermissions({ gatewayExecutor });
} else if (effectiveTokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api && effectiveKubernetesHost) {
const gatewayExecutor = $createGatewayValidationRequest(validationGatewayId, {
kubernetesHost: effectiveKubernetesHost,
caCert: effectiveCaCert,
verifyTlsCertificate: effectiveVerifyTlsCertificate
});
logger.info(
{
gatewayId: validationGatewayId,
gatewayPoolId: effectiveGatewayPoolId,
kubernetesHost: effectiveKubernetesHost
},
"Validating Kubernetes connectivity through gateway for auth method update"
);
await validateKubernetesHostConnectivity({ gatewayExecutor });
if (tokenReviewerJwt) {
await validateTokenReviewerPermissions({ gatewayExecutor, tokenReviewerJwt });
}
}
} else if (effectiveTokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Api) {
if (kubernetesHost) {
logger.info({ kubernetesHost }, "Validating Kubernetes host connectivity for auth method update");
await validateKubernetesHostConnectivity({
kubernetesHost,
caCert: effectiveCaCert,
verifyTlsCertificate: effectiveVerifyTlsCertificate
});
}
if (tokenReviewerJwt && effectiveKubernetesHost) {
logger.info(
{ kubernetesHost: effectiveKubernetesHost },
"Validating token reviewer JWT permissions for auth method update"
);
await validateTokenReviewerPermissions({
kubernetesHost: effectiveKubernetesHost,
tokenReviewerJwt,
caCert: effectiveCaCert,
verifyTlsCertificate: effectiveVerifyTlsCertificate
});
}
}
const updateQuery: TIdentityKubernetesAuthsUpdate = {
kubernetesHost,
tokenReviewMode,
allowedNamespaces,
allowedNames,
allowedAudience,
// tri-state passthrough: undefined keeps the current link, null unlinks, a uuid links
// (a re-assert of the current id skips the template load above, so template is unset)
templateId,
gatewayV2Id: shouldUpdateGatewayId ? gatewayV2IdValue : undefined,
// A deliberate gateway change clears the retired v1 pin too, otherwise `isPinnedToRetiredGateway`
// would reject this row's logins forever with no way to detach: setting gatewayId to null only
// clears gatewayV2Id, leaving the retired column set. Rows nobody edits keep their v1 value, so
// the retirement stays revertible for everything that has not already been repointed.
gatewayId: shouldUpdateGatewayId ? null : undefined,
gatewayPoolId: gatewayPoolIdValue,
verifyTlsCertificate: resolvedVerifyTlsCertificate,
accessTokenMaxTTL,
accessTokenTTL,
accessTokenNumUsesLimit,
accessTokenTrustedIps: reformattedAccessTokenTrustedIps
? JSON.stringify(reformattedAccessTokenTrustedIps)
: undefined
};
if (caCert !== undefined) {
updateQuery.encryptedKubernetesCaCertificate = caCert
? encryptor({ plainText: Buffer.from(caCert) }).cipherTextBlob
: null;
}
if (tokenReviewerJwt) {
updateQuery.encryptedKubernetesTokenReviewerJwt = encryptor({
plainText: Buffer.from(tokenReviewerJwt)
}).cipherTextBlob;
updateQuery.isTokenReviewerJwtTemplateSourced = Boolean(template);
} else if (tokenReviewerJwt === null) {
updateQuery.encryptedKubernetesTokenReviewerJwt = null;
updateQuery.isTokenReviewerJwtTemplateSourced = false;
}
const updatedKubernetesAuth = await identityKubernetesAuthDAL.transaction(async (tx) => {
if (template) {
await assertTemplateUnchangedForLink(identityAuthTemplateDAL, template, tx);
}
const doc = await identityKubernetesAuthDAL.updateById(identityKubernetesAuth.id, updateQuery, tx);
await emitIdentityAuthMethodChanged(
eventEmitter,
{
membership: identityMembershipOrg,
authMethod: IdentityAuthMethod.KUBERNETES_AUTH,
change: IdentityAuthMethodChange.Updated,
actor,
actorId
},
tx
);
return doc;
});
const updatedCACert = updatedKubernetesAuth.encryptedKubernetesCaCertificate
? decryptor({
cipherTextBlob: updatedKubernetesAuth.encryptedKubernetesCaCertificate
}).toString()
: "";
const updatedTokenReviewerJwt =
!updatedKubernetesAuth.templateId &&
!updatedKubernetesAuth.isTokenReviewerJwtTemplateSourced &&
updatedKubernetesAuth.encryptedKubernetesTokenReviewerJwt
? decryptor({
cipherTextBlob: updatedKubernetesAuth.encryptedKubernetesTokenReviewerJwt
}).toString()
: "";
await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.KUBERNETES_AUTH);
return {
...updatedKubernetesAuth,
orgId: identityMembershipOrg.scopeOrgId,
caCert: updatedCACert,
tokenReviewerJwt: updatedTokenReviewerJwt,
gatewayId: updatedKubernetesAuth.gatewayV2Id
};
};
const getKubernetesAuth = async ({
identityId,
actorId,
actor,
actorAuthMethod,
actorOrgId
}: TGetKubernetesAuthDTO) => {
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" });
}
const identityKubernetesAuth = await identityKubernetesAuthDAL.findOne({ identityId });
if (!identityKubernetesAuth) {
throw new NotFoundError({ message: `Failed to find Kubernetes Auth for identity with ID ${identityId}` });
}
if (!identityMembershipOrg.identity.authMethods.includes(IdentityAuthMethod.KUBERNETES_AUTH)) {
throw new BadRequestError({
message: "The identity does not have Kubernetes Auth attached"
});
}
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);
}
const { decryptor } = await kmsService.createCipherPairWithDataKey({
type: KmsDataKey.Organization,
orgId: identityMembershipOrg.scopeOrgId
});
let caCert = "";
if (identityKubernetesAuth.encryptedKubernetesCaCertificate) {
caCert = decryptor({ cipherTextBlob: identityKubernetesAuth.encryptedKubernetesCaCertificate }).toString();
}
// a template's reviewer JWT is an org-scoped write-only credential copied onto the
// identity row; identity-level readers must not be able to recover it, including
// after an unlink (the copied credential keeps its template provenance). Manually
// configured identities keep read-back (the caller supplied that value themselves).
let tokenReviewerJwt = "";
if (
!identityKubernetesAuth.templateId &&
!identityKubernetesAuth.isTokenReviewerJwtTemplateSourced &&
identityKubernetesAuth.encryptedKubernetesTokenReviewerJwt
) {
tokenReviewerJwt = decryptor({
cipherTextBlob: identityKubernetesAuth.encryptedKubernetesTokenReviewerJwt
}).toString();
}
return {
...identityKubernetesAuth,
caCert,
tokenReviewerJwt,
orgId: identityMembershipOrg.scopeOrgId,
gatewayId: identityKubernetesAuth.gatewayV2Id
};
};
const revokeIdentityKubernetesAuth = async ({
identityId,
actorId,
actor,
actorAuthMethod,
actorOrgId,
isActorSuperAdmin
}: TRevokeKubernetesAuthDTO) => {
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.KUBERNETES_AUTH)) {
throw new BadRequestError({
message: "The identity does not have kubernetes auth"
});
}
await assertIdentityAuthAccessAllowed(
{ permissionService, orgDAL },
{
identityId,
orgId: identityMembershipOrg.scopeOrgId,
projectId: identityMembershipOrg.identity.projectId,
action: OrgPermissionIdentityActions.RevokeAuth,
baseMessage: "Failed to revoke kubernetes auth of identity with more privileged role",
actor,
actorId,
actorAuthMethod,
actorOrgId
}
);
await validateIdentityUpdateForSuperAdminPrivileges(identityId, isActorSuperAdmin);
const revokedIdentityKubernetesAuth = await identityKubernetesAuthDAL.transaction(async (tx) => {
const deletedKubernetesAuth = await identityKubernetesAuthDAL.delete({ identityId }, tx);
await identityAccessTokenDAL.delete({ identityId, authMethod: IdentityAuthMethod.KUBERNETES_AUTH }, tx);
await emitIdentityAuthMethodChanged(
eventEmitter,
{
membership: identityMembershipOrg,
authMethod: IdentityAuthMethod.KUBERNETES_AUTH,
change: IdentityAuthMethodChange.Removed,
actor,
actorId
},
tx
);
return {
...deletedKubernetesAuth?.[0],
orgId: identityMembershipOrg.scopeOrgId,
// the row's own gatewayId is the retired v1 column; the API field reports gatewayV2Id
gatewayId: deletedKubernetesAuth?.[0]?.gatewayV2Id
};
});
// 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.KUBERNETES_AUTH
});
await identityAccessTokenService.invalidateTrustedIpsCache(identityId, IdentityAuthMethod.KUBERNETES_AUTH);
return revokedIdentityKubernetesAuth;
};
return {
login,
attachKubernetesAuth,
updateKubernetesAuth,
getKubernetesAuth,
revokeIdentityKubernetesAuth
};
};