Skip to content

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

only set scopes for the required task

Thiago Araujo da Silvae88c35578d0d
diff --git a/backend/e2e-test/routes/v1/oauth-scope.spec.ts b/backend/e2e-test/routes/v1/oauth-scope.spec.ts
index dd41ac010b..10e4c9b5fe 100644
--- a/backend/e2e-test/routes/v1/oauth-scope.spec.ts
+++ b/backend/e2e-test/routes/v1/oauth-scope.spec.ts
@@ -22,6 +22,21 @@ const signOauthToken = (scopes: string[]) =>
{ expiresIn: "1h" }
);
+// GET /api/v3/secrets/raw — the secret-read endpoint `infisical run` calls at runtime. This is one
+// of the few routes that explicitly opts into AuthMode.OAUTH, so a delegated token can reach it; the
+// secrets:read scope then narrows the (admin) ability down to read-only.
+const readSecrets = async (token: string) =>
+ testServer.inject({
+ method: "GET",
+ url: `/api/v3/secrets/raw`,
+ headers: { authorization: `Bearer ${token}` },
+ query: {
+ workspaceId: seedData1.project.id,
+ environment: seedData1.environment.slug,
+ secretPath: "/"
+ }
+ });
+
const createFolder = async (token: string, name: string) =>
testServer.inject({
method: "POST",
@@ -37,49 +52,61 @@ const createFolder = async (token: string, name: string) =>
describe("OAuth delegated token scope enforcement", async () => {
// Control: a first-party session JWT (no oauthClientId) is never scope-narrowed, so the org admin
- // can create folders. This is the baseline the scoped cases are compared against.
- test("first-party session JWT can create a folder", async () => {
- const res = await createFolder(jwtAuthToken, "oauth-scope-control");
+ // can read secrets. This is the baseline the scoped cases are compared against.
+ test("first-party session JWT can read secrets", async () => {
+ const res = await readSecrets(jwtAuthToken);
expect(res.statusCode).toBe(200);
-
- await testServer.inject({
- method: "DELETE",
- url: `/api/v1/folders/${res.json().folder.id}`,
- headers: { authorization: `Bearer ${jwtAuthToken}` },
- body: { workspaceId: seedData1.project.id, environment: seedData1.environment.slug, path: "/" }
- });
- });
-
- test("a token scoped to secrets:write can create a folder", async () => {
- const token = signOauthToken(["secrets:write"]);
- const res = await createFolder(token, "oauth-scope-write");
- expect(res.statusCode).toBe(200);
-
- await testServer.inject({
- method: "DELETE",
- url: `/api/v1/folders/${res.json().folder.id}`,
- headers: { authorization: `Bearer ${jwtAuthToken}` },
- body: { workspaceId: seedData1.project.id, environment: seedData1.environment.slug, path: "/" }
- });
});
- test("a token scoped to secrets:read only cannot create a folder", async () => {
+ test("a token scoped to secrets:read can read secrets", async () => {
const token = signOauthToken(["secrets:read"]);
- const res = await createFolder(token, "oauth-scope-readonly");
- // read scope does not grant the Create action on SecretFolders → CASL forbids
- expect(res.statusCode).toBe(403);
+ const res = await readSecrets(token);
+ expect(res.statusCode).toBe(200);
});
test("a token with no scopes is denied (deny-by-default)", async () => {
const token = signOauthToken([]);
- const res = await createFolder(token, "oauth-scope-empty");
+ const res = await readSecrets(token);
+ // empty scopes → empty ability → CASL forbids the read
expect(res.statusCode).toBe(403);
});
test("unknown scopes are dropped, leaving an empty (denied) ability", async () => {
// Even if a token somehow carries an unrecognized scope, it must not grant anything.
- const token = signOauthToken(["secrets:write:everything", "not-a-real-scope"]);
- const res = await createFolder(token, "oauth-scope-unknown");
+ const token = signOauthToken(["secrets:read:everything", "not-a-real-scope"]);
+ const res = await readSecrets(token);
+ expect(res.statusCode).toBe(403);
+ });
+
+ // Surface boundary: only secret-read routes opt into AuthMode.OAUTH. A write route like folder
+ // creation is JWT-only, so a delegated token is rejected at the auth layer (403) regardless of the
+ // scope it carries — it never reaches the scope-narrowing in permission-building.
+ test("a delegated token cannot reach a non-opted-in write route", async () => {
+ const token = signOauthToken(["secrets:read"]);
+ const res = await createFolder(token, "oauth-scope-write-denied");
+ expect(res.statusCode).toBe(403);
+ });
+
+ // Security regression: account-management routes (TOTP, MFA, sessions, password) authenticate on
+ // userId alone and never build a scope-narrowed permission. They must NOT opt into AuthMode.OAUTH,
+ // so a delegated token — even minted from a valid admin session — is rejected at the auth layer.
+ test("a delegated token is rejected on a JWT-only account route (GET /me/totp)", async () => {
+ const token = signOauthToken(["secrets:read"]);
+ const res = await testServer.inject({
+ method: "GET",
+ url: `/api/v1/user/me/totp`,
+ headers: { authorization: `Bearer ${token}` }
+ });
expect(res.statusCode).toBe(403);
});
+
+ test("the same account route is reachable by the first-party session JWT", async () => {
+ const res = await testServer.inject({
+ method: "GET",
+ url: `/api/v1/user/me/totp`,
+ headers: { authorization: `Bearer ${jwtAuthToken}` }
+ });
+ // 200 (configured) or 404 (no TOTP set up) — the point is it is NOT 403/forbidden by auth mode.
+ expect(res.statusCode).not.toBe(403);
+ });
});
diff --git a/backend/src/server/plugins/auth/verify-auth.test.ts b/backend/src/server/plugins/auth/verify-auth.test.ts
index 9b4045d943..b7307b1c8c 100644
--- a/backend/src/server/plugins/auth/verify-auth.test.ts
+++ b/backend/src/server/plugins/auth/verify-auth.test.ts
@@ -36,25 +36,37 @@ describe("verifyAuth — delegated OAuth access", () => {
expect(done).toHaveBeenCalledOnce();
});
- test("a JWT route also accepts a delegated OAuth token (acts on behalf of the user)", () => {
+ test("a JWT route does NOT accept a delegated OAuth token (must opt in explicitly)", () => {
+ // This is the core of the explicit opt-in contract: a route guarded only by AuthMode.JWT — e.g.
+ // account routes like /me/totp that authenticate on userId without building a scope-narrowed
+ // permission — must reject delegated OAuth tokens so their scopes cannot be bypassed.
const { call, done } = run([AuthMode.JWT], makeReq({ authMode: AuthMode.OAUTH }, { orgId: "org-1" }));
- expect(call).not.toThrow();
- expect(done).toHaveBeenCalledOnce();
+ expect(call).toThrow(ForbiddenRequestError);
+ expect(done).not.toHaveBeenCalled();
});
- test("the JWT→OAUTH allowance is one-directional: an OAUTH-only route rejects a session JWT", () => {
+ test("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("a route opts into delegated access by listing AuthMode.OAUTH alongside AuthMode.JWT", () => {
+ const { call, done } = run(
+ [AuthMode.JWT, AuthMode.OAUTH],
+ makeReq({ authMode: AuthMode.OAUTH }, { orgId: "org-1" })
+ );
+ expect(call).not.toThrow();
+ expect(done).toHaveBeenCalledOnce();
+ });
+
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", () => {
+ test("a route that does not allow OAUTH (e.g. identity-only) rejects a delegated OAuth token", () => {
const { call, done } = run(
[AuthMode.IDENTITY_ACCESS_TOKEN],
makeReq({ authMode: AuthMode.OAUTH }, { orgId: "org-1" })
@@ -71,7 +83,7 @@ describe("verifyAuth — delegated OAuth access", () => {
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 });
+ const { call } = run([AuthMode.JWT, AuthMode.OAUTH], makeReq({ authMode: AuthMode.OAUTH }), { requireOrg: true });
expect(call).toThrow(UnauthorizedError);
});
@@ -81,15 +93,21 @@ describe("verifyAuth — requireOrg", () => {
});
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
- });
+ const { call, done } = run(
+ [AuthMode.JWT, AuthMode.OAUTH],
+ 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 });
+ const { call, done } = run([AuthMode.JWT, AuthMode.OAUTH], makeReq({ authMode: AuthMode.OAUTH }), {
+ requireOrg: false
+ });
expect(call).not.toThrow();
expect(done).toHaveBeenCalledOnce();
});
diff --git a/backend/src/server/plugins/auth/verify-auth.ts b/backend/src/server/plugins/auth/verify-auth.ts
index c96191e0fc..4d61e98b63 100644
--- a/backend/src/server/plugins/auth/verify-auth.ts
+++ b/backend/src/server/plugins/auth/verify-auth.ts
@@ -17,16 +17,15 @@ 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) => {
- 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;
- });
+ // Delegated OAuth access tokens are a distinct auth mode and must be opted into explicitly: a
+ // route only accepts them when it lists AuthMode.OAUTH. They are deliberately NOT accepted on
+ // the strength of AuthMode.JWT alone. OAuth scopes are enforced later, when a handler builds an
+ // org/project permission (the ability is intersected with the granted scopes). A JWT-only route
+ // that authenticates on userId without building a permission — e.g. account routes like
+ // GET/DELETE /me/totp, session revocation, MFA — never runs that scope narrowing, so letting a
+ // delegated token through on JWT alone would bypass scopes entirely. Adding AuthMode.OAUTH to a
+ // route is therefore only safe when its handler performs a scope-narrowed permission check.
+ const isAccessAllowed = authStrategies.some((strategy) => strategy === req.auth.authMode);
if (!isAccessAllowed) {
throw new ForbiddenRequestError({ name: `Forbidden access to ${req.url}` });
}
diff --git a/backend/src/server/routes/v3/deprecated-secret-router.ts b/backend/src/server/routes/v3/deprecated-secret-router.ts
index 0606eeb75e..3aebc5bee0 100644
--- a/backend/src/server/routes/v3/deprecated-secret-router.ts
+++ b/backend/src/server/routes/v3/deprecated-secret-router.ts
@@ -280,7 +280,13 @@ export const registerDeprecatedSecretRouter = async (server: FastifyZodProvider)
304: z.void()
}
},
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ onRequest: verifyAuth([
+ AuthMode.JWT,
+ AuthMode.API_KEY,
+ AuthMode.SERVICE_TOKEN,
+ AuthMode.IDENTITY_ACCESS_TOKEN,
+ AuthMode.OAUTH
+ ]),
handler: async (req, reply) => {
// just for delivery hero usecase
let { secretPath, environment, workspaceId } = req.query;
@@ -393,7 +399,7 @@ export const registerDeprecatedSecretRouter = async (server: FastifyZodProvider)
})
}
},
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
handler: async (req) => {
const { secretId } = req.params;
const secret = await server.services.secret.getSecretByIdRaw({
@@ -448,7 +454,13 @@ export const registerDeprecatedSecretRouter = async (server: FastifyZodProvider)
})
}
},
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ onRequest: verifyAuth([
+ AuthMode.JWT,
+ AuthMode.API_KEY,
+ AuthMode.SERVICE_TOKEN,
+ AuthMode.IDENTITY_ACCESS_TOKEN,
+ AuthMode.OAUTH
+ ]),
handler: async (req) => {
const { workspaceSlug } = req.query;
let { secretPath, environment, workspaceId } = req.query;
diff --git a/backend/src/server/routes/v4/secret-router.ts b/backend/src/server/routes/v4/secret-router.ts
index 05fd1f4747..d7552a86e2 100644
--- a/backend/src/server/routes/v4/secret-router.ts
+++ b/backend/src/server/routes/v4/secret-router.ts
@@ -176,7 +176,7 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
304: z.void()
}
},
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
handler: async (req, reply) => {
// just for delivery hero usecase
let { secretPath, environment, projectId } = req.query;
@@ -282,7 +282,7 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
})
}
},
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
handler: async (req) => {
const { secretId } = req.params;
const secret = await server.services.secret.getSecretByIdRaw({
@@ -337,7 +337,7 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
})
}
},
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
handler: async (req) => {
let { secretPath, environment, projectId } = req.query;
if (req.auth.actor === ActorType.SERVICE) {
diff --git a/backend/src/services/oauth-client/oauth-scope.test.ts b/backend/src/services/oauth-client/oauth-scope.test.ts
index dc42e50af1..9f297ec276 100644
--- a/backend/src/services/oauth-client/oauth-scope.test.ts
+++ b/backend/src/services/oauth-client/oauth-scope.test.ts
@@ -4,8 +4,8 @@ import { applyOauthScopeToProjectRules, isValidOauthScope, OauthScope, parseOaut
describe("parseOauthScopeString", () => {
test("splits, trims, and de-duplicates recognized scopes", () => {
- const { granted, invalid } = parseOauthScopeString(" secrets:read secrets:read projects:read ");
- expect(granted).toEqual([OauthScope.SecretsRead, OauthScope.ProjectsRead]);
+ const { granted, invalid } = parseOauthScopeString(" secrets:read secrets:read ");
+ expect(granted).toEqual([OauthScope.SecretsRead]);
expect(invalid).toEqual([]);
});
diff --git a/backend/src/services/oauth-client/oauth-scope.ts b/backend/src/services/oauth-client/oauth-scope.ts
index 02220186d2..9da212bb75 100644
--- a/backend/src/services/oauth-client/oauth-scope.ts
+++ b/backend/src/services/oauth-client/oauth-scope.ts
@@ -1,13 +1,5 @@
-import {
- OrgPermissionActions,
- OrgPermissionIdentityActions,
- OrgPermissionSubjects
-} from "@app/ee/services/permission/org-permission";
import {
ProjectPermissionActions,
- ProjectPermissionDynamicSecretActions,
- ProjectPermissionIdentityActions,
- ProjectPermissionMemberActions,
ProjectPermissionSecretActions,
ProjectPermissionSub
} from "@app/ee/services/permission/project-permission";
@@ -16,14 +8,12 @@ import {
// underlying user; scopes only *narrow* that ability (effective = userPermissions ∩ grantedScopes).
// Each scope maps to a set of (level, subject, actions) rules that are intersected against the user's
// CASL rules in permission-service. Keep this list curated — it is a public contract.
+//
+// Only secrets:read is exposed for now: the sole delegated use case is `infisical run` fetching
+// secrets at runtime (e.g. via Coder External Auth). Add further scopes only when a route is opted
+// into AuthMode.OAUTH to serve them.
export enum OauthScope {
- SecretsRead = "secrets:read",
- SecretsWrite = "secrets:write",
- ProjectsRead = "projects:read",
- DynamicSecretsRead = "dynamic-secrets:read",
- DynamicSecretsLease = "dynamic-secrets:lease",
- IdentitiesRead = "identities:read",
- IdentitiesManage = "identities:manage"
+ SecretsRead = "secrets:read"
}
// Which permission ability a rule applies to. getOrgPermission builds org-level abilities,
@@ -57,90 +47,6 @@ export const OAUTH_SCOPE_DEFINITIONS: Record<OauthScope, TOauthScopeDefinition>
{ level: "project", subject: ProjectPermissionSub.SecretFolders, actions: [ProjectPermissionActions.Read] },
{ level: "project", subject: ProjectPermissionSub.SecretImports, actions: [ProjectPermissionActions.Read] }
]
- },
- [OauthScope.SecretsWrite]: {
- description: "Create, edit, and delete secrets, folders, and imports",
- rules: [
- {
- level: "project",
- subject: ProjectPermissionSub.Secrets,
- actions: [
- ProjectPermissionSecretActions.Create,
- ProjectPermissionSecretActions.Edit,
- ProjectPermissionSecretActions.Delete
- ]
- },
- {
- level: "project",
- subject: ProjectPermissionSub.SecretFolders,
- actions: [ProjectPermissionActions.Create, ProjectPermissionActions.Edit, ProjectPermissionActions.Delete]
- },
- {
- level: "project",
- subject: ProjectPermissionSub.SecretImports,
- actions: [ProjectPermissionActions.Create, ProjectPermissionActions.Edit, ProjectPermissionActions.Delete]
- }
- ]
- },
- [OauthScope.ProjectsRead]: {
- description: "Read project metadata, environments, tags, and members",
- rules: [
- { level: "org", subject: OrgPermissionSubjects.Workspace, actions: [OrgPermissionActions.Read] },
- { level: "project", subject: ProjectPermissionSub.Project, actions: [ProjectPermissionActions.Read] },
- { level: "project", subject: ProjectPermissionSub.Environments, actions: [ProjectPermissionActions.Read] },
- { level: "project", subject: ProjectPermissionSub.Tags, actions: [ProjectPermissionActions.Read] },
- { level: "project", subject: ProjectPermissionSub.Member, actions: [ProjectPermissionMemberActions.Read] }
- ]
- },
- [OauthScope.DynamicSecretsRead]: {
- description: "Read dynamic secret configurations",
- rules: [
- {
- level: "project",
- subject: ProjectPermissionSub.DynamicSecrets,
- actions: [ProjectPermissionDynamicSecretActions.ReadRootCredential]
- }
- ]
- },
- [OauthScope.DynamicSecretsLease]: {
- description: "Generate and manage dynamic secret leases",
- rules: [
- {
- level: "project",
- subject: ProjectPermissionSub.DynamicSecrets,
- actions: [ProjectPermissionDynamicSecretActions.Lease]
- }
- ]
- },
- [OauthScope.IdentitiesRead]: {
- description: "Read machine identities",
- rules: [
- {
- level: "org",
- subject: OrgPermissionSubjects.Identity,
- actions: [OrgPermissionIdentityActions.Read, OrgPermissionIdentityActions.GetToken]
- },
- {
- level: "project",
- subject: ProjectPermissionSub.Identity,
- actions: [ProjectPermissionIdentityActions.Read]
- }
- ]
- },
- [OauthScope.IdentitiesManage]: {
- description: "Create, edit, delete, and issue tokens for machine identities",
- rules: [
- {
- level: "org",
- subject: OrgPermissionSubjects.Identity,
- actions: Object.values(OrgPermissionIdentityActions)
- },
- {
- level: "project",
- subject: ProjectPermissionSub.Identity,
- actions: Object.values(ProjectPermissionIdentityActions)
- }
- ]
}
};