Skip to content

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

9.6 KB
Raw Blame
import {
  TRotationFactory,
  TRotationFactoryCheckActiveCredentials,
  TRotationFactoryGetSecretsPayload,
  TRotationFactoryIssueCredentials,
  TRotationFactoryRevokeCredentials,
  TRotationFactoryRotateCredentials
} from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-types";
import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
import { assertStripeConnectionAuthorized } from "@app/services/app-connection/stripe/stripe-connection-fns";
import {
  getStripeAppRequestConfig,
  getStripeErrorMessage,
  getStripeErrorStatus,
  getStripeMerchantRequestConfig,
  STRIPE_API_KEYS_URL,
  throwStripeApiKeyManagementError,
  withIdempotencyKey
} from "@app/services/app-connection/stripe/stripe-connection-public-client";
import { IntegrationUrls } from "@app/services/integration-auth/integration-list";

import { generateStripeEncryptionKeyPair, readStripeSecret } from "./stripe-api-key-jwe";
import {
  TStripeApiKeyCreateResponse,
  TStripeApiKeyRotationGeneratedCredentials,
  TStripeApiKeyRotationWithConnection
} from "./stripe-api-key-rotation-types";

const STRIPE_KEY_NAME_MAX_LENGTH = 100;

export const stripeApiKeyRotationFactory: TRotationFactory<
  TStripeApiKeyRotationWithConnection,
  TStripeApiKeyRotationGeneratedCredentials
> = (secretRotation, appConnectionDAL, kmsService, _gatewayV2Service, _gatewayPoolService, keyStore) => {
  const {
    connection,
    parameters: { permissions, keyName },
    secretsMapping
  } = secretRotation;

  const { accountId } = connection.credentials;

  // The default name leaves out the mapped secret's name, which would otherwise show in the Stripe
  // dashboard. The timestamp keeps the old and new key apart while both are live, and is what makes
  // a key stranded by a timed-out create identifiable there.
  const $keyName = () => `${keyName ?? `infisical-managed`}-${Date.now()}`.slice(0, STRIPE_KEY_NAME_MAX_LENGTH);
  // Runs once at the start of each operation, not per request, so the cleanup a failed operation
  // does (expiring a key it just created) never fails on authorization half way through.
  const $assertAuthorized = () =>
    assertStripeConnectionAuthorized(connection.id, { appConnectionDAL, kmsService, keyStore });

  /** No 404 on a double expire has ever been observed, so a non-404 failure on retiring a key that
   *  was already expired can't be told apart from a real failure by status code alone. This is only
   *  ever consulted after the expire call itself has failed, to check whether the key was already
   *  gone; it must never run first, since a transient failure here (a 429, a 5xx, a socket error)
   *  would otherwise block an expire attempt that would very likely have succeeded.
   */
  const $keyExists = async (keyId: string): Promise<boolean> => {
    try {
      await request.get(`${STRIPE_API_KEYS_URL}/${keyId}`, getStripeAppRequestConfig(accountId));
      return true;
    } catch (error) {
      if (getStripeErrorStatus(error) === 404) return false;

      throw error;
    }
  };

  const $tryRetireKey = async (keyId: string): Promise<{ retired: true } | { retired: false; error: unknown }> => {
    try {
      await request.post(
        `${STRIPE_API_KEYS_URL}/${keyId}/expire`,
        {},
        withIdempotencyKey(getStripeAppRequestConfig(accountId))
      );
      return { retired: true };
    } catch (expireError) {
      if (getStripeErrorStatus(expireError) === 404) return { retired: true };

      // The expire failed for some other reason. It might still be that the key was already
      // retired and a repeat expire doesn't return 404 the way a first one would, so check
      // existence to excuse the failure. But the check is only ever an excuse, never a
      // replacement: if it also fails, or it finds the key still there, the original expire
      // error is what gets surfaced.
      try {
        if (!(await $keyExists(keyId))) return { retired: true };
      } catch {
        // Fall through and surface expireError below.
      }

      return { retired: false, error: expireError };
    }
  };

  /**
   * Expire is the whole retirement. Stripe decides when it takes effect, so nothing here claims the
   * key is dead the moment this returns. In practice the key stops working within several minutes,
   * which is well inside the weeks-to-months cadence rotations run on.
   */
  const $retireKey = async (keyId: string) => {
    const result = await $tryRetireKey(keyId);

    if (!result.retired) throwStripeApiKeyManagementError(accountId, result.error);
  };

  /**
   * A key exists in Stripe before the row does, so anything that fails after create, whether that is
   * decrypting the secret Stripe returned or committing the row, has to take the key with it.
   */
  const $retireOnFailure = async <T>(keyId: string, action: () => Promise<T>): Promise<T> => {
    try {
      return await action();
    } catch (actionError) {
      try {
        await $retireKey(keyId);
      } catch (cleanupError) {
        throw new BadRequestError({
          message: `${getStripeErrorMessage(actionError)} The newly created Stripe API key ${keyId} could not be expired and may need to be removed manually: ${getStripeErrorMessage(cleanupError)}`
        });
      }

      throw actionError;
    }
  };

  const $createApiKey = async () => {
    const { publicKey, privateKey } = await generateStripeEncryptionKeyPair();

    let data: TStripeApiKeyCreateResponse;

    try {
      ({ data } = await request.post<TStripeApiKeyCreateResponse>(
        STRIPE_API_KEYS_URL,
        {
          type: "secret_key",
          name: $keyName(),
          permissions,
          public_key: { pem_key: { data: publicKey, algorithm: "RSA" } }
        },
        withIdempotencyKey(getStripeAppRequestConfig(accountId))
      ));
    } catch (error) {
      return throwStripeApiKeyManagementError(accountId, error);
    }

    if (!data?.id) {
      throw new BadRequestError({ message: "Stripe did not return an ID for the created API key." });
    }

    const { id: keyId } = data;

    // readStripeSecret can throw (a malformed JWE, an unsupported algorithm, a decrypt failure). The
    // key already exists in Stripe by that point, so that throw needs the same cleanup as a failed
    // commit, not a bare rethrow.
    return $retireOnFailure(keyId, async () => ({ keyId, apiKey: readStripeSecret(data.secret_key, privateKey) }));
  };

  const issueCredentials: TRotationFactoryIssueCredentials<TStripeApiKeyRotationGeneratedCredentials> = async (
    callback
  ) => {
    await $assertAuthorized();

    const credentials = await $createApiKey();

    return $retireOnFailure(credentials.keyId, () => callback(credentials));
  };

  const revokeCredentials: TRotationFactoryRevokeCredentials<TStripeApiKeyRotationGeneratedCredentials> = async (
    credentials,
    callback
  ) => {
    if (!credentials?.length) return callback();

    await $assertAuthorized();

    // The published key is retired last. A failure part way through aborts the delete, so retiring
    // it first would leave the rotation row and its mapped secret in place pointing at a key that
    // is on its way out, which is an outage until the operator retries.
    const { activeIndex } = secretRotation;
    const retirementOrder = [
      ...credentials.filter((_, index) => index !== activeIndex),
      ...credentials.filter((_, index) => index === activeIndex)
    ];

    for await (const { keyId } of retirementOrder) {
      await $retireKey(keyId);
    }

    return callback();
  };

  const rotateCredentials: TRotationFactoryRotateCredentials<TStripeApiKeyRotationGeneratedCredentials> = async (
    credentialsToRevoke,
    callback
  ) => {
    await $assertAuthorized();

    const newCredentials = await $createApiKey();

    // Retire before committing, so a failure leaves Postgres and Stripe agreeing with each other and
    // the key we just minted gets cleaned up rather than orphaned across BullMQ's retries.
    if (credentialsToRevoke?.keyId) {
      const retireResult = await $tryRetireKey(credentialsToRevoke.keyId);

      if (!retireResult.retired) {
        const cleanupResult = await $tryRetireKey(newCredentials.keyId);

        if (!cleanupResult.retired) {
          throw new BadRequestError({
            message: `Stripe API key ${credentialsToRevoke.keyId} could not be retired (${getStripeErrorMessage(retireResult.error)}), and the newly created key ${newCredentials.keyId} could not be cleaned up either (${getStripeErrorMessage(cleanupResult.error)}). Both may need to be removed manually from the Stripe dashboard.`
          });
        }

        throwStripeApiKeyManagementError(accountId, retireResult.error);
      }
    }

    return $retireOnFailure(newCredentials.keyId, () => callback(newCredentials));
  };

  const getSecretsPayload: TRotationFactoryGetSecretsPayload<TStripeApiKeyRotationGeneratedCredentials> = ({
    apiKey
  }) => [{ key: secretsMapping.apiKey, value: apiKey }];

  const checkActiveCredentials: TRotationFactoryCheckActiveCredentials<
    TStripeApiKeyRotationGeneratedCredentials
  > = async ({ apiKey }) => {
    try {
      await request.get(
        `${IntegrationUrls.STRIPE_API_URL}/v1/customers?limit=1`,
        getStripeMerchantRequestConfig(apiKey)
      );
    } catch (error) {
      // 403 means the key authenticated and simply lacks customer_read, which is a healthy narrow
      // key. Only 401 means the key is gone.
      if (getStripeErrorStatus(error) === 403) return;

      throw new BadRequestError({
        message: `Stripe API key verification failed: ${getStripeErrorMessage(error)}`
      });
    }
  };

  return {
    issueCredentials,
    revokeCredentials,
    rotateCredentials,
    getSecretsPayload,
    checkActiveCredentials
  };
};