Skip to content

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

feat: agent friendly API

varonix655a55463791
diff --git a/backend/src/server/app.ts b/backend/src/server/app.ts
index 7e2b2a3aa8..32213a9794 100644
--- a/backend/src/server/app.ts
+++ b/backend/src/server/app.ts
@@ -95,6 +95,19 @@ export const main = async ({
// @ts-expect-error akhilmhdh: even on setting it fastify as Redis | Cluster it's throwing error
server.decorate("redis", redis);
+
+ // ensures that we return proper zod errors instead of a 500 "something went wrong" error when someone sends a request with empty json body
+ const defaultJsonParser = server.getDefaultJsonParser("error", "error");
+ server.removeContentTypeParser("application/json");
+ server.addContentTypeParser("application/json", { parseAs: "string" }, (req, body: string | Buffer, done) => {
+ const strBody = body instanceof Buffer ? body.toString() : body;
+ if (strBody?.length === 0) {
+ done(null, {});
+ return;
+ }
+ void defaultJsonParser(req, strBody, done);
+ });
+
server.addContentTypeParser("application/scim+json", { parseAs: "string" }, (_, body: string | Buffer, done) => {
try {
const strBody = body instanceof Buffer ? body.toString() : body;
@@ -135,12 +148,12 @@ export const main = async ({
await server.register(apiMetrics);
}
+ await server.register(fastifyErrHandler);
await server.register(fastifySwagger);
await server.register(fastifyFormBody);
await server.register(websocket, {
options: { maxPayload: 64 * 1024 } // 64 KB
});
- await server.register(fastifyErrHandler);
// Rate limiters and security headers
if (appCfg.isProductionMode && appCfg.isCloud) {
diff --git a/backend/src/server/plugins/error-handler.ts b/backend/src/server/plugins/error-handler.ts
index 388e54666b..360468c977 100644
--- a/backend/src/server/plugins/error-handler.ts
+++ b/backend/src/server/plugins/error-handler.ts
@@ -1,5 +1,6 @@
import { ForbiddenError, PureAbility } from "@casl/ability";
import { requestContext } from "@fastify/request-context";
+import { errorCodes, FastifyError } from "fastify";
import fastifyPlugin from "fastify-plugin";
import jwt from "jsonwebtoken";
import { ZodError } from "zod";
@@ -53,6 +54,18 @@ enum HttpStatusCodes {
TooManyRequests = 429
}
+const BODY_PARSER_ERRORS = [
+ errorCodes.FST_ERR_CTP_INVALID_JSON_BODY,
+ errorCodes.FST_ERR_CTP_INVALID_MEDIA_TYPE,
+ errorCodes.FST_ERR_CTP_BODY_TOO_LARGE,
+ errorCodes.FST_ERR_CTP_INVALID_CONTENT_LENGTH
+];
+
+const isBodyParserError = (error: Error): error is FastifyError =>
+ BODY_PARSER_ERRORS.some((BodyParserError) => error instanceof BodyParserError);
+
+const API_REFERENCE_DOCS_URL = "https://infisical.com/docs/api-reference";
+
export const fastifyErrHandler = fastifyPlugin(async (server: FastifyZodProvider) => {
const appCfg = getConfig();
@@ -68,6 +81,17 @@ export const fastifyErrHandler = fastifyPlugin(async (server: FastifyZodProvider
unit: "{error}"
});
+ // only undefined routes include documentationUrl in the response; a "NotFounDerror" thrown by a handler means the route exists = not included
+ server.setNotFoundHandler((req, res) => {
+ void res.status(HttpStatusCodes.NotFound).send({
+ reqId: req.id,
+ statusCode: HttpStatusCodes.NotFound,
+ message: `Route ${req.method}:${req.url} not found`,
+ error: "Not Found",
+ documentationUrl: API_REFERENCE_DOCS_URL
+ });
+ });
+
server.setErrorHandler((error: Error, req, res) => {
// Expected client errors don't need stack traces. Log them without the Error object to
// avoid stack serialization; keep full-stack logging for unexpected / server errors.
@@ -80,6 +104,7 @@ export const fastifyErrHandler = fastifyPlugin(async (server: FastifyZodProvider
error instanceof ForbiddenRequestError ||
error instanceof PermissionBoundaryError ||
error instanceof ZodError ||
+ isBodyParserError(error) ||
(error instanceof OauthTokenError && error.statusCode < HttpStatusCodes.InternalServerError) ||
error instanceof RateLimitError ||
error instanceof PolicyViolationError ||
@@ -380,6 +405,13 @@ export const fastifyErrHandler = fastifyPlugin(async (server: FastifyZodProvider
"Invalid JSON in request body. If you are sending a Certificate Signing Request (CSR), ensure newlines are escaped as \\n characters, not literal line breaks.",
error: "BadRequestError"
});
+ } else if (isBodyParserError(error)) {
+ void res.status(error.statusCode ?? HttpStatusCodes.BadRequest).send({
+ reqId: req.id,
+ statusCode: error.statusCode ?? HttpStatusCodes.BadRequest,
+ message: error.message,
+ error: "BodyParserError"
+ });
} else {
void res.status(HttpStatusCodes.InternalServerError).send({
reqId: req.id,
diff --git a/backend/src/server/plugins/swagger.ts b/backend/src/server/plugins/swagger.ts
index 8b6a8338d7..32aa05ce6e 100644
--- a/backend/src/server/plugins/swagger.ts
+++ b/backend/src/server/plugins/swagger.ts
@@ -6,6 +6,9 @@ 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 { jsonSchemaTransform } from "./fastify-zod";
@@ -31,6 +34,31 @@ const SPEC_FORMAT_BY_ROUTE: Record<string, SpecFormat> = {
[`${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): Promise<SpecPayload> => {
const isYaml = format === "yaml";
const body = isYaml ? fastify.swagger({ yaml: true }) : JSON.stringify(fastify.swagger());
@@ -151,6 +179,12 @@ export const fastifySwagger = fp(async (fastify) => {
};
const serveSpec = async (req: FastifyRequest, reply: FastifyReply, format: SpecFormat) => {
+ const { tag } = SpecQuerySchema.parse(req.query);
+ if (format === "json" && tag) {
+ await reply.send(filterSpecByTag(fastify.swagger() as unknown as OpenApiDocument, tag));
+ return;
+ }
+
const payload = await getSpecPayload(format);
const encoding = pickSpecEncoding(req.headers["accept-encoding"]);
diff --git a/backend/src/server/routes/v3/deprecated-secret-router.ts b/backend/src/server/routes/v3/deprecated-secret-router.ts
index d37199ac0c..b375c69185 100644
--- a/backend/src/server/routes/v3/deprecated-secret-router.ts
+++ b/backend/src/server/routes/v3/deprecated-secret-router.ts
@@ -60,9 +60,10 @@ export const registerDeprecatedSecretRouter = async (server: FastifyZodProvider)
rateLimit: writeLimit
},
schema: {
+ deprecated: true,
+ description: "Deprecated. Use POST /v4/secrets/tags/:secretName instead.",
hide: false,
tags: [ApiDocsTags.Secrets],
- description: "Attach tags to a secret",
security: [
{
bearerAuth: []
@@ -117,9 +118,10 @@ export const registerDeprecatedSecretRouter = async (server: FastifyZodProvider)
rateLimit: writeLimit
},
schema: {
+ deprecated: true,
+ description: "Deprecated. Use DELETE /v4/secrets/tags/:secretName instead.",
hide: false,
tags: [ApiDocsTags.Secrets],
- description: "Detach tags from a secret",
security: [
{
bearerAuth: []
@@ -174,9 +176,10 @@ export const registerDeprecatedSecretRouter = async (server: FastifyZodProvider)
rateLimit: secretsLimit
},
schema: {
+ deprecated: true,
+ description: "Deprecated. Use GET /v4/secrets/raw instead.",
hide: false,
tags: [ApiDocsTags.Secrets],
- description: "List secrets",
security: [
{
bearerAuth: []
@@ -393,6 +396,8 @@ export const registerDeprecatedSecretRouter = async (server: FastifyZodProvider)
schema: {
hide: false,
tags: [ApiDocsTags.Secrets],
+ deprecated: true,
+ description: "Deprecated. Use GET /v4/secrets/raw/id/:secretId instead.",
params: z.object({
secretId: z.string()
}),
@@ -430,7 +435,8 @@ export const registerDeprecatedSecretRouter = async (server: FastifyZodProvider)
schema: {
hide: false,
tags: [ApiDocsTags.Secrets],
- description: "Get a secret by name",
+ deprecated: true,
+ description: "Deprecated. Use GET /v4/secrets/raw/:secretName instead.",
security: [
{
bearerAuth: []
@@ -563,7 +569,8 @@ export const registerDeprecatedSecretRouter = async (server: FastifyZodProvider)
schema: {
hide: false,
tags: [ApiDocsTags.Secrets],
- description: "Create secret",
+ deprecated: true,
+ description: "Deprecated. Use POST /v4/secrets/raw/:secretName instead.",
security: [
{
bearerAuth: []
@@ -718,7 +725,8 @@ export const registerDeprecatedSecretRouter = async (server: FastifyZodProvider)
schema: {
hide: false,
tags: [ApiDocsTags.Secrets],
- description: "Update secret",
+ deprecated: true,
+ description: "Deprecated. Use PATCH /v4/secrets/raw/:secretName instead.",
security: [
{
bearerAuth: []
@@ -882,7 +890,8 @@ export const registerDeprecatedSecretRouter = async (server: FastifyZodProvider)
schema: {
hide: false,
tags: [ApiDocsTags.Secrets],
- description: "Delete secret",
+ deprecated: true,
+ description: "Deprecated. Use DELETE /v4/secrets/raw/:secretName instead.",
security: [
{
bearerAuth: []
@@ -1006,6 +1015,8 @@ export const registerDeprecatedSecretRouter = async (server: FastifyZodProvider)
rateLimit: secretsLimit
},
schema: {
+ deprecated: true,
+ description: "Deprecated. Use GET /v4/secrets instead.",
querystring: z.object({
workspaceId: z.string().trim(),
environment: z.string().trim(),
@@ -1123,6 +1134,8 @@ export const registerDeprecatedSecretRouter = async (server: FastifyZodProvider)
rateLimit: secretsLimit
},
schema: {
+ deprecated: true,
+ description: "Deprecated. Use GET /v4/secrets/:secretName instead.",
params: z.object({
secretName: z.string().trim()
}),
@@ -1209,6 +1222,8 @@ export const registerDeprecatedSecretRouter = async (server: FastifyZodProvider)
rateLimit: secretsLimit
},
schema: {
+ deprecated: true,
+ description: "Deprecated. Use POST /v4/secrets/:secretName instead.",
body: z.object({
workspaceId: z.string().trim(),
environment: z.string().trim(),
@@ -1391,6 +1406,8 @@ export const registerDeprecatedSecretRouter = async (server: FastifyZodProvider)
rateLimit: secretsLimit
},
schema: {
+ deprecated: true,
+ description: "Deprecated. Use PATCH /v4/secrets/:secretName instead.",
params: z.object({
secretName: z.string()
}),
@@ -1591,6 +1608,8 @@ export const registerDeprecatedSecretRouter = async (server: FastifyZodProvider)
rateLimit: secretsLimit
},
schema: {
+ deprecated: true,
+ description: "Deprecated. Use DELETE /v4/secrets/:secretName instead.",
params: z.object({
secretName: z.string()
}),
@@ -1726,6 +1745,8 @@ export const registerDeprecatedSecretRouter = async (server: FastifyZodProvider)
rateLimit: secretsLimit
},
schema: {
+ deprecated: true,
+ description: "Deprecated. Use POST /v4/secrets/move instead.",
hide: false,
tags: [ApiDocsTags.Secrets],
body: z.object({
@@ -1783,6 +1804,8 @@ export const registerDeprecatedSecretRouter = async (server: FastifyZodProvider)
rateLimit: secretsLimit
},
schema: {
+ deprecated: true,
+ description: "Deprecated. Use POST /v4/secrets/batch instead.",
body: z.object({
workspaceId: z.string().trim(),
environment: z.string().trim(),
@@ -1920,6 +1943,8 @@ export const registerDeprecatedSecretRouter = async (server: FastifyZodProvider)
rateLimit: secretsLimit
},
schema: {
+ deprecated: true,
+ description: "Deprecated. Use PATCH /v4/secrets/batch instead.",
body: z.object({
workspaceId: z.string().trim(),
environment: z.string().trim(),
@@ -2060,6 +2085,8 @@ export const registerDeprecatedSecretRouter = async (server: FastifyZodProvider)
rateLimit: secretsLimit
},
schema: {
+ deprecated: true,
+ description: "Deprecated. Use DELETE /v4/secrets/batch instead.",
body: z.object({
workspaceId: z.string().trim(),
environment: z.string().trim(),
@@ -2194,7 +2221,8 @@ export const registerDeprecatedSecretRouter = async (server: FastifyZodProvider)
schema: {
hide: false,
tags: [ApiDocsTags.Secrets],
- description: "Create many secrets",
+ deprecated: true,
+ description: "Deprecated. Use POST /v4/secrets/batch/raw instead.",
security: [
{
bearerAuth: []
@@ -2333,7 +2361,8 @@ export const registerDeprecatedSecretRouter = async (server: FastifyZodProvider)
schema: {
hide: false,
tags: [ApiDocsTags.Secrets],
- description: "Update many secrets",
+ deprecated: true,
+ description: "Deprecated. Use PATCH /v4/secrets/batch/raw instead.",
security: [
{
bearerAuth: []
@@ -2545,7 +2574,8 @@ export const registerDeprecatedSecretRouter = async (server: FastifyZodProvider)
schema: {
hide: false,
tags: [ApiDocsTags.Secrets],
- description: "Delete many secrets",
+ deprecated: true,
+ description: "Deprecated. Use DELETE /v4/secrets/batch/raw instead.",
security: [
{
bearerAuth: []
diff --git a/docs/api-reference/overview/introduction.mdx b/docs/api-reference/overview/introduction.mdx
index acb85d4e5d..f3570b5d61 100644
--- a/docs/api-reference/overview/introduction.mdx
+++ b/docs/api-reference/overview/introduction.mdx
@@ -11,6 +11,15 @@ rotating credentials, or for integrating secret management into a larger system.
With the Public API, you can create, read, update, and delete secrets, as well as manage access control, query audit logs, and more.
+<Visibility for="agents">
+ <Info>
+ **Are you an AI agent reading this page?** Welcome. Skip the scrolling: the complete OpenAPI specification is at `/api/docs/json` on any Infisical instance, for example [app.infisical.com/api/docs/json](https://app.infisical.com/api/docs/json).
+
+ The full specification is large, so spare your context window and add the `tag` query parameter to get only the endpoints you need. For example `/api/docs/json?tag=secrets`.
+ </Info>
+</Visibility>
+
+
## API versioning
The API is versioned on a per-resource basis. A resource's version is only incremented for breaking changes, so different endpoints may have different version numbers (e.g., `/api/v4/secrets` vs. `/api/v1/secret-syncs`).