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
distinguish between oauth and jwt token
Thiago Araujo da Silvad72b668cd668
diff --git a/backend/src/server/plugins/auth/inject-identity.test.ts b/backend/src/server/plugins/auth/inject-identity.test.tsnew file mode 100644index 0000000000..26f5fd8fe6--- /dev/null+++ b/backend/src/server/plugins/auth/inject-identity.test.ts@@ -0,0 +1,84 @@+import type { FastifyRequest } from "fastify";+import { afterAll, beforeAll, describe, expect, test, vi } from "vitest";++import { crypto } from "@app/lib/crypto";+import { AuthMethod, AuthMode, AuthTokenType } from "@app/services/auth/auth-type";++import { extractAuth } from "./inject-identity";++vi.mock("@app/lib/logger", () => ({+ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() }+}));++const AUTH_SECRET = "test-secret-for-extract-auth-unit-tests";++const baseAccessClaims = {+ authTokenType: AuthTokenType.ACCESS_TOKEN as const,+ authMethod: AuthMethod.EMAIL,+ userId: "user-1",+ tokenVersionId: "session-1",+ accessVersion: 1,+ organizationId: "org-1"+};++const sign = (claims: Record<string, unknown>) => crypto.jwt().sign(claims, AUTH_SECRET, { expiresIn: "1h" });++const makeReq = (authorization?: string, apiKey?: string) =>+ ({+ headers: {+ authorization,+ ...(apiKey ? { "x-api-key": apiKey } : {})+ }+ }) as unknown as FastifyRequest;++describe("extractAuth — OAuth access token classification", () => {+ beforeAll(async () => {+ process.env.FIPS_ENABLED = "false";+ await crypto.initialize({} as never, {} as never, {} as never);+ });++ afterAll(() => {+ delete process.env.FIPS_ENABLED;+ });++ test("an access token carrying oauthClientId is classified as AuthMode.OAUTH", async () => {+ const token = sign({ ...baseAccessClaims, oauthClientId: "oauth_client_abc" });+ const result = await extractAuth(makeReq(`Bearer ${token}`), AUTH_SECRET);++ expect(result.authMode).toBe(AuthMode.OAUTH);+ expect((result.token as { oauthClientId?: string }).oauthClientId).toBe("oauth_client_abc");+ });++ test("a plain access token (no marker) remains a first-party AuthMode.JWT", async () => {+ const token = sign(baseAccessClaims);+ const result = await extractAuth(makeReq(`Bearer ${token}`), AUTH_SECRET);++ expect(result.authMode).toBe(AuthMode.JWT);+ });++ test("the MCP marker takes precedence over the OAuth marker", async () => {+ const token = sign({ ...baseAccessClaims, mcp: { endpointId: "ep-1" }, oauthClientId: "oauth_client_abc" });+ const result = await extractAuth(makeReq(`Bearer ${token}`), AUTH_SECRET);++ expect(result.authMode).toBe(AuthMode.MCP_JWT);+ });++ test("a service token is still detected by its st. prefix, never as OAuth", async () => {+ const result = await extractAuth(makeReq("Bearer st.some-service-token"), AUTH_SECRET);++ expect(result.authMode).toBe(AuthMode.SERVICE_TOKEN);+ });++ test("an x-api-key header short-circuits before token parsing", async () => {+ const token = sign({ ...baseAccessClaims, oauthClientId: "oauth_client_abc" });+ const result = await extractAuth(makeReq(`Bearer ${token}`, "my-api-key"), AUTH_SECRET);++ expect(result.authMode).toBe(AuthMode.API_KEY);+ });++ test("a missing authorization header yields no auth mode", async () => {+ const result = await extractAuth(makeReq(undefined), AUTH_SECRET);++ expect(result.authMode).toBeNull();+ });+});diff --git a/backend/src/server/plugins/auth/inject-identity.ts b/backend/src/server/plugins/auth/inject-identity.tsindex 4b983491a1..6b0ae79408 100644--- a/backend/src/server/plugins/auth/inject-identity.ts+++ b/backend/src/server/plugins/auth/inject-identity.ts@@ -24,7 +24,7 @@ import { getServerCfg } from "@app/services/super-admin/super-admin-service";export type TAuthMode =| {- authMode: AuthMode.JWT | AuthMode.MCP_JWT;+ authMode: AuthMode.JWT | AuthMode.MCP_JWT | AuthMode.OAUTH;actor: ActorType.USER;userId: string;tokenVersionId: string; // the session id of token used@@ -35,6 +35,7 @@ export type TAuthMode =authMethod: AuthMethod;isMfaVerified?: boolean;mfaMethod?: MfaMethod;+ oauthClientId?: string;token: AuthModeJwtTokenPayload;}| {@@ -130,6 +131,14 @@ export const extractAuth = async (req: FastifyRequest, jwtSecret: string) => {} as const;}+ if (decodedToken?.oauthClientId) {+ return {+ authMode: AuthMode.OAUTH,+ token: decodedToken as AuthModeJwtTokenPayload,+ actor: ActorType.USER+ } as const;+ }+return {authMode: AuthMode.JWT,token: decodedToken as AuthModeJwtTokenPayload,@@ -291,6 +300,29 @@ export const injectIdentity = fp(fireIdentifyForUser(user);break;}+ case AuthMode.OAUTH: {+ const { user, tokenVersionId, orgId, orgName, rootOrgId, parentOrgId } =+ await server.services.authToken.fnValidateJwtIdentity(token);+ requestContext.set(RequestContextKey.OrgId, orgId);+ requestContext.set(RequestContextKey.OrgName, orgName);+ requestContext.set(RequestContextKey.UserAuthInfo, { userId: user.id, email: user.email || "" });+ req.auth = {+ authMode: AuthMode.OAUTH,+ user,+ userId: user.id,+ tokenVersionId,+ actor,+ orgId,+ rootOrgId,+ parentOrgId,+ authMethod: token.authMethod,+ isMfaVerified: token.isMfaVerified,+ oauthClientId: token.oauthClientId,+ token+ };+ fireIdentifyForUser(user);+ break;+ }case AuthMode.IDENTITY_ACCESS_TOKEN: {const identity = await server.services.identityAccessToken.fnValidateIdentityAccessTokenFast(token,diff --git a/backend/src/server/plugins/auth/verify-auth.test.ts b/backend/src/server/plugins/auth/verify-auth.test.tsnew file mode 100644index 0000000000..9b4045d943--- /dev/null+++ b/backend/src/server/plugins/auth/verify-auth.test.ts@@ -0,0 +1,113 @@+import type { FastifyReply, FastifyRequest, HookHandlerDoneFunction } from "fastify";+import { describe, expect, test, vi } from "vitest";++import { ForbiddenRequestError, UnauthorizedError } from "@app/lib/errors";+import { AuthMode } from "@app/services/auth/auth-type";++import { verifyAuth } from "./verify-auth";++type FakeAuth = {+ authMode: AuthMode;+};++const makeReq = (auth: FakeAuth | undefined, opts?: { orgId?: string; method?: string }) =>+ ({+ auth,+ method: opts?.method ?? "GET",+ url: "/api/v1/secrets",+ permission: { orgId: opts?.orgId },+ shouldForwardWritesToPrimaryInstance: false+ }) as unknown as FastifyRequest;++const run = (+ strategies: AuthMode[],+ req: FastifyRequest,+ options?: { requireOrg: boolean }+): { done: HookHandlerDoneFunction; call: () => void } => {+ const done = vi.fn() as unknown as HookHandlerDoneFunction;+ const middleware = options ? verifyAuth(strategies, options) : verifyAuth(strategies);+ return { done, call: () => middleware(req, {} as FastifyReply, done) };+};++describe("verifyAuth — delegated OAuth access", () => {+ test("a JWT route accepts a first-party session JWT", () => {+ const { call, done } = run([AuthMode.JWT], makeReq({ authMode: AuthMode.JWT }, { orgId: "org-1" }));+ expect(call).not.toThrow();+ expect(done).toHaveBeenCalledOnce();+ });++ test("a JWT route also accepts a delegated OAuth token (acts on behalf of the user)", () => {+ const { call, done } = run([AuthMode.JWT], makeReq({ authMode: AuthMode.OAUTH }, { orgId: "org-1" }));+ expect(call).not.toThrow();+ expect(done).toHaveBeenCalledOnce();+ });++ test("the JWT→OAUTH allowance is one-directional: an OAUTH-only route rejects a session JWT", () => {+ const { call, done } = run([AuthMode.OAUTH], makeReq({ authMode: AuthMode.JWT }, { orgId: "org-1" }));+ expect(call).toThrow(ForbiddenRequestError);+ expect(done).not.toHaveBeenCalled();+ });++ test("an OAUTH-only route accepts a delegated OAuth token", () => {+ const { call, done } = run([AuthMode.OAUTH], makeReq({ authMode: AuthMode.OAUTH }, { orgId: "org-1" }));+ expect(call).not.toThrow();+ expect(done).toHaveBeenCalledOnce();+ });++ test("a route that does not allow JWT (e.g. identity-only) rejects a delegated OAuth token", () => {+ const { call, done } = run(+ [AuthMode.IDENTITY_ACCESS_TOKEN],+ makeReq({ authMode: AuthMode.OAUTH }, { orgId: "org-1" })+ );+ expect(call).toThrow(ForbiddenRequestError);+ expect(done).not.toHaveBeenCalled();+ });++ test("OAuth tokens are excluded from a service-token route", () => {+ const { call } = run([AuthMode.SERVICE_TOKEN], makeReq({ authMode: AuthMode.OAUTH }, { orgId: "org-1" }));+ expect(call).toThrow(ForbiddenRequestError);+ });+});++describe("verifyAuth — requireOrg", () => {+ test("a delegated OAuth token without an org is rejected when requireOrg is set", () => {+ const { call } = run([AuthMode.JWT], makeReq({ authMode: AuthMode.OAUTH }), { requireOrg: true });+ expect(call).toThrow(UnauthorizedError);+ });++ test("a session JWT without an org is rejected when requireOrg is set", () => {+ const { call } = run([AuthMode.JWT], makeReq({ authMode: AuthMode.JWT }), { requireOrg: true });+ expect(call).toThrow(UnauthorizedError);+ });++ test("a delegated OAuth token with an org passes when requireOrg is set", () => {+ const { call, done } = run([AuthMode.JWT], makeReq({ authMode: AuthMode.OAUTH }, { orgId: "org-1" }), {+ requireOrg: true+ });+ expect(call).not.toThrow();+ expect(done).toHaveBeenCalledOnce();+ });++ test("requireOrg=false lets an org-less delegated OAuth token through", () => {+ const { call, done } = run([AuthMode.JWT], makeReq({ authMode: AuthMode.OAUTH }), { requireOrg: false });+ expect(call).not.toThrow();+ expect(done).toHaveBeenCalledOnce();+ });+});++describe("verifyAuth — guards", () => {+ test("throws when no auth is present on the request", () => {+ const { call } = run([AuthMode.JWT], makeReq(undefined));+ expect(call).toThrow(UnauthorizedError);+ });++ test("non-GET write requests forwarded to the primary instance short-circuit to done", () => {+ const done = vi.fn() as unknown as HookHandlerDoneFunction;+ const req = {+ method: "POST",+ shouldForwardWritesToPrimaryInstance: true+ } as unknown as FastifyRequest;+ verifyAuth([AuthMode.JWT])(req, {} as FastifyReply, done);+ expect(done).toHaveBeenCalledOnce();+ });+});diff --git a/backend/src/server/plugins/auth/verify-auth.ts b/backend/src/server/plugins/auth/verify-auth.tsindex fac5f02c92..c96191e0fc 100644--- a/backend/src/server/plugins/auth/verify-auth.ts+++ b/backend/src/server/plugins/auth/verify-auth.ts@@ -17,14 +17,27 @@ export const verifyAuth =if (!Array.isArray(authStrategies)) throw new Error("Auth strategy must be array");if (!req.auth) throw new UnauthorizedError({ message: "Token missing" });- const isAccessAllowed = authStrategies.some((strategy) => strategy === req.auth.authMode);+ const isAccessAllowed = authStrategies.some((strategy) => {+ if (strategy === req.auth.authMode) return true;+ // Delegated OAuth access tokens act on behalf of the user, so they satisfy any route that+ // accepts a first-party user JWT. They remain a distinct auth mode (carrying oauthClientId)+ // for audit and per-client revocation; this is intentionally one-directional — a route that+ // lists only AuthMode.OAUTH is NOT satisfied by a session JWT. To fence a sensitive route off+ // from delegated access, omit AuthMode.JWT or check req.auth.oauthClientId in the handler.+ if (strategy === AuthMode.JWT && req.auth.authMode === AuthMode.OAUTH) return true;+ return false;+ });if (!isAccessAllowed) {throw new ForbiddenRequestError({ name: `Forbidden access to ${req.url}` });}// New optional option. There are some routes which do not require an organization ID to be present on the request.// An example of this is the /v1 auth routes.- if (req.auth.authMode === AuthMode.JWT && options.requireOrg === true && !req.permission.orgId) {+ if (+ (req.auth.authMode === AuthMode.JWT || req.auth.authMode === AuthMode.OAUTH) &&+ options.requireOrg === true &&+ !req.permission.orgId+ ) {throw new UnauthorizedError({ name: `${req.url} Unauthorized Access, no organization found in request` });}diff --git a/backend/src/server/routes/v1/oauth-router.ts b/backend/src/server/routes/v1/oauth-router.tsindex 329bca51cf..d1d6eb0463 100644--- a/backend/src/server/routes/v1/oauth-router.ts+++ b/backend/src/server/routes/v1/oauth-router.ts@@ -430,7 +430,9 @@ export const registerOAuthRouter = async (server: FastifyZodProvider) => {})}},- onRequest: verifyAuth([AuthMode.JWT]),+ // Token introspection for OAuth clients: accepts the delegated OAuth access token. Reaching the+ // handler means injectIdentity already verified the signature and the underlying session.+ onRequest: verifyAuth([AuthMode.OAUTH]),handler: () => ({ active: true as const })});};diff --git a/backend/src/services/auth/auth-type.ts b/backend/src/services/auth/auth-type.tsindex 92e4b84eba..ade645d30f 100644--- a/backend/src/services/auth/auth-type.ts+++ b/backend/src/services/auth/auth-type.ts@@ -42,6 +42,9 @@ export enum AuthMode {IDENTITY_ACCESS_TOKEN = "identityAccessToken",SCIM_TOKEN = "scimToken",MCP_JWT = "mcpJwt",+ // Delegated OAuth 2.0 access tokens issued via the authorization code flow. These are NOT+ // first-party dashboard sessions: a route must explicitly opt into AuthMode.OAUTH to accept them.+ OAUTH = "oauth",GATEWAY_ACCESS_TOKEN = "gatewayAccessToken",RELAY_ACCESS_TOKEN = "relayAccessToken"}@@ -92,6 +95,9 @@ export type AuthModeJwtTokenPayload = {mcp?: {endpointId: string;};+ // Present only on delegated OAuth 2.0 access tokens. Its presence marks the token as+ // AuthMode.OAUTH so the default JWT middleware will not accept it as a first-party session.+ oauthClientId?: string;};export type AuthModeMfaJwtTokenPayload = {diff --git a/backend/src/services/oauth-client/oauth-client-service.ts b/backend/src/services/oauth-client/oauth-client-service.tsindex e5a9461821..3249e39c47 100644--- a/backend/src/services/oauth-client/oauth-client-service.ts+++ b/backend/src/services/oauth-client/oauth-client-service.ts@@ -56,7 +56,10 @@ type TOauthTokenClaims = {mfaMethod?: MfaMethod;};-const signOauthAccessToken = (claims: TOauthTokenClaims & { accessVersion: number }, expiresIn: string | number) => {+const signOauthAccessToken = (+ claims: TOauthTokenClaims & { accessVersion: number; oauthClientId: string },+ expiresIn: string | number+) => {const appCfg = getConfig();return crypto.jwt().sign({@@ -67,7 +70,10 @@ const signOauthAccessToken = (claims: TOauthTokenClaims & { accessVersion: numbeaccessVersion: claims.accessVersion,organizationId: claims.organizationId,isMfaVerified: claims.isMfaVerified,- mfaMethod: claims.mfaMethod+ mfaMethod: claims.mfaMethod,+ // Marks this as a delegated OAuth access token. extractAuth maps tokens carrying this+ // claim to AuthMode.OAUTH so they are rejected by the default first-party JWT middleware.+ oauthClientId: claims.oauthClientId},appCfg.AUTH_SECRET,{ expiresIn }@@ -348,7 +354,7 @@ export const oauthClientServiceFactory = ({};const accessToken = signOauthAccessToken(- { ...sharedClaims, accessVersion: tokenSession.accessVersion },+ { ...sharedClaims, accessVersion: tokenSession.accessVersion, oauthClientId: client.clientId },accessTokenExpiresIn);@@ -404,7 +410,7 @@ export const oauthClientServiceFactory = ({}const accessToken = signOauthAccessToken(- { ...sharedClaims, accessVersion: tokenVersion.accessVersion },+ { ...sharedClaims, accessVersion: tokenVersion.accessVersion, oauthClientId: client.clientId },accessTokenExpiresIn);