Skip to content

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

7.0 KB
Raw Blame
import { createHash } from "node:crypto";
import { promisify } from "node:util";
import { brotliCompress, constants as zlibConstants, gzip } from "node:zlib";

import swagger from "@fastify/swagger";
import swaggerUI from "@fastify/swagger-ui";
import { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import fp from "fastify-plugin";
import { z } from "zod";

import { ApiDocsTags } from "@app/lib/api-docs";

import { fullJsonSchemaTransform, jsonSchemaTransform } from "./fastify-zod";

const DOCS_ROUTE_PREFIX = "/api/docs";
const SPEC_CACHE_MAX_AGE_SECONDS = 600;
const MAX_TAGGED_SPEC_PAYLOADS = 20;

const gzipAsync = promisify(gzip);
const brotliCompressAsync = promisify(brotliCompress);

type SpecFormat = "json" | "yaml";
type SpecEncoding = "br" | "gzip";

type SpecPayload = {
  contentType: string;
  etagBase: string;
  identity: Buffer;
  br: Buffer;
  gzip: Buffer;
};

const SPEC_FORMAT_BY_ROUTE: Record<string, SpecFormat> = {
  [`${DOCS_ROUTE_PREFIX}/json`]: "json",
  [`${DOCS_ROUTE_PREFIX}/yaml`]: "yaml"
};

// the tags are matched by slug ("secret-tags" for "Secret Tags") so agents can pass them without encoding
const TAG_BY_SLUG: Record<string, ApiDocsTags> = Object.fromEntries(
  Object.values(ApiDocsTags).map((tag) => [tag.toLowerCase().replace(/[^a-z0-9]+/g, "-"), tag])
);

const SpecQuerySchema = z.object({
  tag: z
    .enum(Object.keys(TAG_BY_SLUG) as [string, ...string[]])
    .transform((slug) => TAG_BY_SLUG[slug])
    .optional()
});

type OpenApiDocument = {
  paths?: Record<string, Record<string, { tags?: string[] }>>;
};

const filterSpecByTag = (spec: OpenApiDocument, tag: ApiDocsTags): OpenApiDocument => {
  const paths: NonNullable<OpenApiDocument["paths"]> = {};
  for (const [url, operations] of Object.entries(spec.paths ?? {})) {
    const kept = Object.entries(operations).filter(([, operation]) => operation.tags?.includes(tag));
    if (kept.length) paths[url] = Object.fromEntries(kept);
  }
  return { ...spec, paths };
};

const buildSpecPayload = async (
  fastify: FastifyInstance,
  format: SpecFormat,
  tag?: ApiDocsTags
): Promise<SpecPayload> => {
  const isYaml = format === "yaml";
  let body: string;
  if (isYaml) {
    body = fastify.swagger({ yaml: true });
  } else {
    const spec = fastify.swagger() as unknown as OpenApiDocument;
    body = JSON.stringify(tag ? filterSpecByTag(spec, tag) : spec);
  }
  const contentType = isYaml ? "application/x-yaml" : "application/json; charset=utf-8";

  const identity = Buffer.from(body, "utf8");

  const [brotlied, gzipped] = await Promise.all([
    brotliCompressAsync(identity, {
      params: {
        [zlibConstants.BROTLI_PARAM_QUALITY]: 5,
        [zlibConstants.BROTLI_PARAM_SIZE_HINT]: identity.byteLength
      }
    }),
    gzipAsync(identity)
  ]);

  fastify.log.info(
    {
      format,
      tag,
      identityBytes: identity.byteLength,
      brotliBytes: brotlied.byteLength,
      gzipBytes: gzipped.byteLength
    },
    "Cached OpenAPI spec payload"
  );

  return {
    contentType,
    etagBase: createHash("sha256").update(identity).digest("base64"),
    identity,
    br: brotlied,
    gzip: gzipped
  };
};

const appendVary = (reply: FastifyReply, field: string) => {
  const current = reply.getHeader("vary");
  const joined = Array.isArray(current) ? current.join(",") : current;
  const existing = (typeof joined === "string" ? joined : "")
    .split(",")
    .map((entry) => entry.trim())
    .filter(Boolean);

  if (existing.some((entry) => entry === "*" || entry.toLowerCase() === field)) return;

  void reply.header("vary", [...existing, field].join(", "));
};

const pickSpecEncoding = (header: FastifyRequest["headers"]["accept-encoding"]): SpecEncoding | null => {
  if (!header) return null;

  const weights = new Map<string, number>();
  for (const directive of (Array.isArray(header) ? header.join(",") : header).split(",")) {
    const [token, ...params] = directive.trim().split(";");

    if (token) {
      const quality = params.map((param) => param.trim()).find((param) => param.startsWith("q="));
      const parsed = quality ? Number(quality.slice(2)) : 1;
      weights.set(token.toLowerCase(), Number.isNaN(parsed) ? 1 : parsed);
    }
  }

  if ((weights.get("br") ?? 0) > 0) return "br";
  if ((weights.get("gzip") ?? weights.get("*") ?? 0) > 0) return "gzip";
  return null;
};

export const fastifySwagger = fp(async (fastify, { fullSpec = false }: { fullSpec?: boolean }) => {
  await fastify.register(swagger, {
    transform: fullSpec ? fullJsonSchemaTransform : jsonSchemaTransform,
    openapi: {
      info: {
        title: "Infisical API",
        description: "List of all available APIs that can be consumed",
        version: "0.0.1"
      },
      servers: [
        {
          url: "https://us.infisical.com",
          description: "Production server (US)"
        },
        {
          url: "https://eu.infisical.com",
          description: "Production server (EU)"
        },
        {
          url: "http://localhost:8080",
          description: "Local server"
        }
      ],
      components: {
        securitySchemes: {
          bearerAuth: {
            type: "http",
            scheme: "bearer",
            bearerFormat: "JWT",
            description: "An access token in Infisical"
          }
        }
      }
    }
  });

  const specPayloads = new Map<string, Promise<SpecPayload>>();
  const taggedSpecPayloads = new Map<string, Promise<SpecPayload>>();

  const getSpecPayload = (format: SpecFormat, tag?: ApiDocsTags) => {
    const cache = tag ? taggedSpecPayloads : specPayloads;
    const key = tag ?? format;

    const cached = cache.get(key);
    if (cached) return cached;

    const pending = buildSpecPayload(fastify, format, tag).catch((err) => {
      cache.delete(key);
      throw err;
    });

    if (tag && cache.size >= MAX_TAGGED_SPEC_PAYLOADS) cache.delete(cache.keys().next().value as string);
    cache.set(key, pending);
    return pending;
  };

  const serveSpec = async (req: FastifyRequest, reply: FastifyReply, format: SpecFormat) => {
    const { tag } = SpecQuerySchema.parse(req.query);
    // Only the JSON spec is filtered by tag.
    const payload = await getSpecPayload(format, format === "json" ? tag : undefined);
    const encoding = pickSpecEncoding(req.headers["accept-encoding"]);

    void reply
      .header("content-type", payload.contentType)
      .header("etag", `"${payload.etagBase}${encoding ? `-${encoding}` : ""}"`)
      .header("cache-control", `public, max-age=${SPEC_CACHE_MAX_AGE_SECONDS}`);

    appendVary(reply, "accept-encoding");

    if (encoding) void reply.header("content-encoding", encoding);

    await reply.send(encoding ? payload[encoding] : payload.identity);
  };

  await fastify.register(swaggerUI, {
    routePrefix: DOCS_ROUTE_PREFIX,
    uiHooks: {
      preHandler: (req, reply, done) => {
        const format = SPEC_FORMAT_BY_ROUTE[req.routeOptions.url ?? ""];

        if (!format) {
          done();
          return;
        }

        void serveSpec(req, reply, format).catch((err) => done(err as Error));
      }
    }
  });
});