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
have scopes as least privilege principle
Thiago Araujo da Silvaeebd5c923c06
diff --git a/backend/e2e-test/routes/v1/oauth-scope.spec.ts b/backend/e2e-test/routes/v1/oauth-scope.spec.tsnew file mode 100644index 0000000000..dd41ac010b--- /dev/null+++ b/backend/e2e-test/routes/v1/oauth-scope.spec.ts@@ -0,0 +1,85 @@+import jwt from "jsonwebtoken";++import { seedData1 } from "@app/db/seed-data";+import { AuthMethod, AuthTokenType } from "@app/services/auth/auth-type";++// Mints a delegated OAuth access token for the seed user (an org admin) with the given scopes. It+// reuses the same session (tokenVersionId/accessVersion) as the working jwtAuthToken, so it passes+// signature + session validation and only differs by the oauthClientId/scopes claims.+const signOauthToken = (scopes: string[]) =>+ jwt.sign(+ {+ authTokenType: AuthTokenType.ACCESS_TOKEN,+ userId: seedData1.id,+ tokenVersionId: seedData1.token.id,+ authMethod: AuthMethod.EMAIL,+ organizationId: seedData1.organization.id,+ accessVersion: 1,+ oauthClientId: "oauth_client_e2e_test",+ scopes+ },+ process.env.AUTH_SECRET ?? "something-random",+ { expiresIn: "1h" }+ );++const createFolder = async (token: string, name: string) =>+ testServer.inject({+ method: "POST",+ url: `/api/v1/folders`,+ headers: { authorization: `Bearer ${token}` },+ body: {+ workspaceId: seedData1.project.id,+ environment: seedData1.environment.slug,+ name,+ path: "/"+ }+ });++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");+ 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 () => {+ 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);+ });++ test("a token with no scopes is denied (deny-by-default)", async () => {+ const token = signOauthToken([]);+ const res = await createFolder(token, "oauth-scope-empty");+ 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");+ expect(res.statusCode).toBe(403);+ });+});diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.tsindex 9048cc2462..aa1696f443 100644--- a/backend/src/@types/fastify.d.ts+++ b/backend/src/@types/fastify.d.ts@@ -184,6 +184,10 @@ declare module "@fastify/request-context" {reqId: string;ip?: string;userAgent?: string;+ // Set only on delegated OAuth requests. Presence (even as an empty array) signals that+ // permission abilities must be intersected with these scopes; absence means a first-party+ // session with no scope narrowing.+ oauthScopes?: string[];orgId?: string;orgName?: string;userAuthInfo?: {diff --git a/backend/src/ee/services/permission/permission-service.ts b/backend/src/ee/services/permission/permission-service.tsindex 1648523aff..ec03fd9121 100644--- a/backend/src/ee/services/permission/permission-service.ts+++ b/backend/src/ee/services/permission/permission-service.ts@@ -43,6 +43,12 @@ import { requestMemoize } from "@app/lib/request-context/request-memoizer";import { TAdditionalPrivilegeDALFactory } from "@app/services/additional-privilege/additional-privilege-dal";import { ActorType } from "@app/services/auth/auth-type";import { TIdentityDALFactory } from "@app/services/identity/identity-dal";+import {+ applyOauthScopeToOrgRules,+ applyOauthScopeToProjectRules,+ isValidOauthScope,+ OauthScope+} from "@app/services/oauth-client/oauth-scope";import { TProjectDALFactory } from "@app/services/project/project-dal";import { TRoleDALFactory } from "@app/services/role/role-dal";import { TServiceTokenDALFactory } from "@app/services/service-token/service-token-dal";@@ -72,6 +78,16 @@ import {ProjectPermissionSub} from "./project-permission";+// Returns the delegated OAuth scopes for the current request, or undefined when this is not an+// OAuth-delegated request. The distinction matters: a returned array (even empty) means scope+// narrowing applies, while undefined means a first-party session / background job is untouched.+const getDelegatedOauthScopes = (): OauthScope[] | undefined => {+ const raw = requestContext.get(RequestContextKey.OauthScopes);+ if (!raw) return undefined;+ // The scopes were validated at consent time, but re-coerce defensively against the catalog.+ return raw.filter(isValidOauthScope);+};+const buildOrgPermissionRules = (orgUserRoles: TBuildOrgPermissionDTO) => {const rules = orgUserRoles.map(({ role, permissions }) => {@@ -301,13 +317,14 @@ export const permissionServiceFactory = ({const hasRole = (role: string) => membershipsHaveActiveRole(permissionData, role);- const permission = createMongoAbility<OrgPermissionSet>(buildOrgPermissionRules(permissionFromRoles), {+ const fullPermission = createMongoAbility<OrgPermissionSet>(buildOrgPermissionRules(permissionFromRoles), {conditionsMatcher});- const canBypassSso = permission.can(OrgPermissionSsoActions.BypassSsoEnforcement, OrgPermissionSubjects.Sso);+ const canBypassSso = fullPermission.can(OrgPermissionSsoActions.BypassSsoEnforcement, OrgPermissionSubjects.Sso);- // SSO enforcement applies only to users+ // SSO enforcement applies only to users. Evaluate it against the full ability — SSO bypass is a+ // property of the user's roles, not of what an OAuth client was delegated.if (actor === ActorType.USER) {validateOrgSSO(actorAuthMethod,@@ -318,6 +335,14 @@ export const permissionServiceFactory = ({);}+ // Delegated OAuth tokens get a scope-narrowed ability; first-party sessions get the full one.+ const oauthScopes = getDelegatedOauthScopes();+ const permission = oauthScopes+ ? createMongoAbility<OrgPermissionSet>(applyOauthScopeToOrgRules(fullPermission.rules, oauthScopes), {+ conditionsMatcher+ })+ : fullPermission;+return {permission,memberships: permissionData,@@ -649,7 +674,19 @@ export const permissionServiceFactory = ({requestContext.set(RequestContextKey.ProjectDetails, payload.projectDetailsCtx);requestContext.set(RequestContextKey.IdentityPermissionMetadata, payload.identityPermissionMetadataCtx);- return payload.result;++ // Narrow the ability for delegated OAuth tokens. Applied here, outside the (cross-request) cache+ // boundary, so the cached payload always holds the full ability and only this request is scoped.+ const oauthScopes = getDelegatedOauthScopes();+ if (!oauthScopes) return payload.result;++ return {+ ...payload.result,+ permission: createMongoAbility<ProjectPermissionSet>(+ applyOauthScopeToProjectRules(payload.result.permission.rules, oauthScopes),+ { conditionsMatcher }+ )+ };};const getResourcePermission: TPermissionServiceFactory["getResourcePermission"] = async ({@@ -683,6 +720,19 @@ export const permissionServiceFactory = ({});return requestMemoize(memoKey, async () => {+ // The v1 OAuth scope catalog does not cover resource-level (e.g. cert-manager) memberships, so+ // a delegated token receives an empty resource ability — any ForbiddenError.from(...) check on+ // it fails. This keeps the strict deny-by-default contract for anything outside granted scopes.+ const oauthScopes = getDelegatedOauthScopes();+ if (oauthScopes) {+ return {+ permission: createMongoAbility<ResourcePermissionSet>([], { conditionsMatcher }),+ memberships: [],+ hasRole: () => false,+ isImplicitAdmin: false+ };+ }+let isProjectAdmin = false;let isProjectMember = false;try {diff --git a/backend/src/lib/request-context/request-context-keys.ts b/backend/src/lib/request-context/request-context-keys.tsindex 4ccff7923d..b1454abf90 100644--- a/backend/src/lib/request-context/request-context-keys.ts+++ b/backend/src/lib/request-context/request-context-keys.ts@@ -8,6 +8,7 @@ export enum RequestContextKey {IdentityPermissionMetadata = "identityPermissionMetadata",Ip = "ip",Memoizer = "memoizer",+ OauthScopes = "oauthScopes",OrgId = "orgId",OrgName = "orgName",ProjectDetails = "projectDetails",diff --git a/backend/src/server/plugins/auth/inject-identity.ts b/backend/src/server/plugins/auth/inject-identity.tsindex 6b0ae79408..d2ff5af88e 100644--- a/backend/src/server/plugins/auth/inject-identity.ts+++ b/backend/src/server/plugins/auth/inject-identity.ts@@ -305,6 +305,9 @@ export const injectIdentity = fp(await server.services.authToken.fnValidateJwtIdentity(token);requestContext.set(RequestContextKey.OrgId, orgId);requestContext.set(RequestContextKey.OrgName, orgName);+ // Always set (even as []) so permission-service can distinguish a delegated OAuth request+ // that must be scope-narrowed from a first-party session that must not be.+ requestContext.set(RequestContextKey.OauthScopes, token.scopes ?? []);requestContext.set(RequestContextKey.UserAuthInfo, { userId: user.id, email: user.email || "" });req.auth = {authMode: AuthMode.OAUTH,diff --git a/backend/src/server/routes/v1/oauth-router.ts b/backend/src/server/routes/v1/oauth-router.tsindex d1d6eb0463..60b41d5439 100644--- a/backend/src/server/routes/v1/oauth-router.ts+++ b/backend/src/server/routes/v1/oauth-router.ts@@ -280,26 +280,30 @@ export const registerOAuthRouter = async (server: FastifyZodProvider) => {schema: {querystring: z.object({client_id: z.string(),- redirect_uri: z.string().url()+ redirect_uri: z.string().url(),+ scope: z.string().optional()}),response: {200: z.object({clientName: z.string(),clientDescription: z.string().nullable().optional(),- requirePkce: z.boolean()+ requirePkce: z.boolean(),+ requestedScopes: z.object({ scope: z.string(), description: z.string() }).array()})}},handler: async (req) => {const info = await server.services.oauthClient.getAuthorizeInfo({clientId: req.query.client_id,- redirectUri: req.query.redirect_uri+ redirectUri: req.query.redirect_uri,+ scope: req.query.scope});return {clientName: info.clientName,clientDescription: info.clientDescription,- requirePkce: info.requirePkce+ requirePkce: info.requirePkce,+ requestedScopes: info.requestedScopes};}});diff --git a/backend/src/services/auth/auth-type.ts b/backend/src/services/auth/auth-type.tsindex ade645d30f..a183e82edc 100644--- a/backend/src/services/auth/auth-type.ts+++ b/backend/src/services/auth/auth-type.ts@@ -98,6 +98,9 @@ export type AuthModeJwtTokenPayload = {// 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;+ // Granted OAuth delegation scopes (see OauthScope). The delegated ability is intersected with+ // these in permission-service; an empty/absent list denies all scope-guarded resource access.+ scopes?: string[];};export type AuthModeMfaJwtTokenPayload = {@@ -120,6 +123,7 @@ export type AuthModeRefreshJwtTokenPayload = {isMfaVerified?: boolean;mfaMethod?: MfaMethod;oauthClientId?: string;+ scopes?: string[];};export type AuthModeSignUpTokenPayload = {diff --git a/backend/src/services/oauth-client/oauth-client-service.ts b/backend/src/services/oauth-client/oauth-client-service.tsindex 04fae9e29a..66123f1a25 100644--- a/backend/src/services/oauth-client/oauth-client-service.ts+++ b/backend/src/services/oauth-client/oauth-client-service.ts@@ -30,6 +30,7 @@ import {TOauthTokenExchangeDTO,TUpdateOauthClientDTO} from "./oauth-client-types";+import { getOauthScopeDescriptions, parseOauthScopeString } from "./oauth-scope";type TOauthClientServiceFactoryDep = {oauthClientDAL: TOauthClientDALFactory;@@ -63,6 +64,7 @@ type TOauthTokenClaims = {organizationId: string;isMfaVerified?: boolean;mfaMethod?: MfaMethod;+ scopes: string[];};const signOauthAccessToken = (@@ -82,7 +84,10 @@ const signOauthAccessToken = (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+ oauthClientId: claims.oauthClientId,+ // Granted delegation scopes. permission-service intersects the user's ability with these,+ // so the token can never exceed what the user consented to.+ scopes: claims.scopes},appCfg.AUTH_SECRET,{ expiresIn }@@ -104,7 +109,8 @@ const signOauthRefreshToken = (organizationId: claims.organizationId,isMfaVerified: claims.isMfaVerified,mfaMethod: claims.mfaMethod,- oauthClientId: claims.oauthClientId+ oauthClientId: claims.oauthClientId,+ scopes: claims.scopes},appCfg.AUTH_SECRET,{ expiresIn }@@ -219,7 +225,7 @@ export const oauthClientServiceFactory = ({return { client: sanitizeOauthClient(updatedClient), clientSecret };};- const getAuthorizeInfo = async ({ clientId, redirectUri }: TOauthAuthorizeInfoDTO) => {+ const getAuthorizeInfo = async ({ clientId, redirectUri, scope }: TOauthAuthorizeInfoDTO) => {const client = await oauthClientDAL.findOne({ clientId });if (!client) throw new UnauthorizedError({ message: "OAuth client not found" });@@ -227,11 +233,19 @@ export const oauthClientServiceFactory = ({throw new BadRequestError({ message: "Redirect URI is not registered for this OAuth client" });}+ // Surface unknown scopes up front so the consent screen can refuse rather than letting the+ // user approve a request that authorizeConsent will reject anyway.+ const { granted, invalid } = parseOauthScopeString(scope);+ if (invalid.length) {+ throw new BadRequestError({ message: `Unsupported OAuth scope(s): ${invalid.join(", ")}` });+ }+return {clientName: client.name,clientDescription: client.description,orgId: client.orgId,- requirePkce: client.requirePkce+ requirePkce: client.requirePkce,+ requestedScopes: getOauthScopeDescriptions(granted)};};@@ -247,6 +261,13 @@ export const oauthClientServiceFactory = ({throw new BadRequestError({ message: "This OAuth client requires PKCE (code_challenge is missing)" });}+ // Reject the request if it asks for any scope we don't recognize (RFC 6749 invalid_scope),+ // rather than silently dropping it and issuing a token narrower than the client expects.+ const { granted: grantedScopes, invalid: invalidScopes } = parseOauthScopeString(dto.scope);+ if (invalidScopes.length) {+ throw new BadRequestError({ message: `Unsupported OAuth scope(s): ${invalidScopes.join(", ")}` });+ }+await permissionService.getOrgPermission({actor: ActorType.USER,actorId: dto.userId,@@ -278,7 +299,7 @@ export const oauthClientServiceFactory = ({redirectUri: dto.redirectUri,codeChallenge: dto.codeChallenge,codeChallengeMethod: dto.codeChallengeMethod,- scope: dto.scope+ scopes: grantedScopes}));@@ -359,13 +380,16 @@ export const oauthClientServiceFactory = ({const { accessTokenExpiresIn, refreshTokenExpiresIn } = await getTokenLifetimes(codePayload.orgId);+ const grantedScopes = codePayload.scopes ?? [];+const sharedClaims = {authMethod: codePayload.authMethod,userId: codePayload.userId,tokenVersionId: tokenSession.id,organizationId: codePayload.orgId,isMfaVerified: codePayload.isMfaVerified,- mfaMethod: codePayload.mfaMethod+ mfaMethod: codePayload.mfaMethod,+ scopes: grantedScopes};const accessToken = signOauthAccessToken(@@ -383,7 +407,7 @@ export const oauthClientServiceFactory = ({token_type: "Bearer" as const,expires_in: expiresInToSeconds(accessTokenExpiresIn),refresh_token: refreshToken,- scope: codePayload.scope ?? ""+ scope: grantedScopes.join(" ")};}@@ -405,13 +429,17 @@ export const oauthClientServiceFactory = ({let { refreshToken } = dto;let { refreshVersion } = tokenVersion;+ // Carry the originally-granted scopes forward; a refresh must never broaden delegation.+ const grantedScopes = oauthDecodedToken.scopes ?? [];+const sharedClaims = {authMethod: decodedToken.authMethod,userId: decodedToken.userId,tokenVersionId: tokenVersion.id,organizationId: decodedToken.organizationId,isMfaVerified: decodedToken.isMfaVerified,- mfaMethod: decodedToken.mfaMethod+ mfaMethod: decodedToken.mfaMethod,+ scopes: grantedScopes};if (!isGraceHit) {@@ -434,7 +462,7 @@ export const oauthClientServiceFactory = ({token_type: "Bearer" as const,expires_in: expiresInToSeconds(accessTokenExpiresIn),refresh_token: refreshToken,- scope: ""+ scope: grantedScopes.join(" ")};};diff --git a/backend/src/services/oauth-client/oauth-client-types.ts b/backend/src/services/oauth-client/oauth-client-types.tsindex c81934abe6..d99d850a30 100644--- a/backend/src/services/oauth-client/oauth-client-types.ts+++ b/backend/src/services/oauth-client/oauth-client-types.ts@@ -20,6 +20,7 @@ export type TUpdateOauthClientDTO = {export type TOauthAuthorizeInfoDTO = {clientId: string;redirectUri: string;+ scope?: string;};export type TOauthConsentDTO = {@@ -63,7 +64,9 @@ export const OauthAuthorizationCodePayloadSchema = z.object({redirectUri: z.string(),codeChallenge: z.string().optional(),codeChallengeMethod: z.literal("S256").optional(),- scope: z.string().optional()+ // Granted, validated delegation scopes (recognized OauthScope values only). Resolved at consent+ // time so the token exchange does not have to re-parse the original space-delimited request.+ scopes: z.array(z.string()).optional()});export type TOauthAuthorizationCodePayload = z.infer<typeof OauthAuthorizationCodePayloadSchema>;diff --git a/backend/src/services/oauth-client/oauth-scope.test.ts b/backend/src/services/oauth-client/oauth-scope.test.tsnew file mode 100644index 0000000000..dc42e50af1--- /dev/null+++ b/backend/src/services/oauth-client/oauth-scope.test.ts@@ -0,0 +1,113 @@+import { ProjectPermissionSecretActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";++import { applyOauthScopeToProjectRules, isValidOauthScope, OauthScope, parseOauthScopeString } from "./oauth-scope";++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]);+ expect(invalid).toEqual([]);+ });++ test("separates unknown scopes as invalid", () => {+ const { granted, invalid } = parseOauthScopeString("secrets:read admin:everything");+ expect(granted).toEqual([OauthScope.SecretsRead]);+ expect(invalid).toEqual(["admin:everything"]);+ });++ test("empty / undefined input yields no scopes", () => {+ expect(parseOauthScopeString(undefined)).toEqual({ granted: [], invalid: [] });+ expect(parseOauthScopeString("")).toEqual({ granted: [], invalid: [] });+ });+});++describe("isValidOauthScope", () => {+ test("recognizes catalog scopes and rejects others", () => {+ expect(isValidOauthScope("secrets:read")).toBe(true);+ expect(isValidOauthScope("toString")).toBe(false);+ expect(isValidOauthScope("nope")).toBe(false);+ });+});++describe("applyOauthScopeToProjectRules", () => {+ test("drops rules whose subject is out of scope", () => {+ const rules = [+ { action: ["read"], subject: ProjectPermissionSub.Secrets },+ { action: ["read"], subject: ProjectPermissionSub.Member }+ ];+ const scoped = applyOauthScopeToProjectRules(rules, [OauthScope.SecretsRead]);+ expect(scoped).toHaveLength(1);+ expect(scoped[0].subject).toBe(ProjectPermissionSub.Secrets);+ });++ test("narrows actions to the scope-permitted subset (intersection, never expansion)", () => {+ // User can read+write secrets, but the token was only granted secrets:read.+ const rules = [+ {+ action: [+ ProjectPermissionSecretActions.DescribeAndReadValue,+ ProjectPermissionSecretActions.Create,+ ProjectPermissionSecretActions.Edit+ ],+ subject: ProjectPermissionSub.Secrets+ }+ ];+ const scoped = applyOauthScopeToProjectRules(rules, [OauthScope.SecretsRead]);+ expect(scoped).toHaveLength(1);+ expect(scoped[0].action).toEqual([ProjectPermissionSecretActions.DescribeAndReadValue]);+ });++ test("expands a CASL manage rule to exactly the scope-permitted actions", () => {+ const rules = [{ action: "manage", subject: ProjectPermissionSub.Secrets }];+ const scoped = applyOauthScopeToProjectRules(rules, [OauthScope.SecretsRead]);+ expect(scoped).toHaveLength(1);+ expect(scoped[0].action).toEqual(+ expect.arrayContaining([+ ProjectPermissionSecretActions.DescribeAndReadValue,+ ProjectPermissionSecretActions.DescribeSecret,+ ProjectPermissionSecretActions.ReadValue+ ])+ );+ // manage must NOT leak write actions the scope does not grant+ expect(scoped[0].action).not.toContain(ProjectPermissionSecretActions.Create);+ });++ test("fans out an 'all' subject admin rule across in-scope subjects only", () => {+ const rules = [{ action: "manage", subject: "all" }];+ const scoped = applyOauthScopeToProjectRules(rules, [OauthScope.SecretsRead]);+ const subjects = scoped.map((r) => r.subject);+ expect(subjects).toEqual(+ expect.arrayContaining([+ ProjectPermissionSub.Secrets,+ ProjectPermissionSub.SecretFolders,+ ProjectPermissionSub.SecretImports+ ])+ );+ // nothing outside the granted scope+ expect(subjects).not.toContain(ProjectPermissionSub.Member);+ });++ test("preserves rule conditions while narrowing actions", () => {+ const conditions = { environment: { $eq: "prod" } };+ const rules = [{ action: "manage", subject: ProjectPermissionSub.Secrets, conditions }];+ const scoped = applyOauthScopeToProjectRules(rules, [OauthScope.SecretsRead]);+ expect(scoped[0]).toMatchObject({ conditions });+ });++ test("keeps inverted (cannot) rules untouched", () => {+ const rules = [+ { action: ["read"], subject: ProjectPermissionSub.Secrets },+ { action: ["read"], subject: ProjectPermissionSub.Secrets, inverted: true, conditions: { secretPath: "/x" } }+ ];+ const scoped = applyOauthScopeToProjectRules(rules, [OauthScope.SecretsRead]);+ const inverted = scoped.find((r) => r.inverted);+ expect(inverted).toBeDefined();+ expect(inverted).toMatchObject({ inverted: true, conditions: { secretPath: "/x" } });+ });++ test("empty scopes deny all (no allow-rules survive)", () => {+ const rules = [{ action: "manage", subject: "all" }];+ const scoped = applyOauthScopeToProjectRules(rules, []);+ expect(scoped).toEqual([]);+ });+});diff --git a/backend/src/services/oauth-client/oauth-scope.ts b/backend/src/services/oauth-client/oauth-scope.tsnew file mode 100644index 0000000000..02220186d2--- /dev/null+++ b/backend/src/services/oauth-client/oauth-scope.ts@@ -0,0 +1,234 @@+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";++// Coarse, named OAuth delegation scopes. A delegated OAuth access token can never do more than the+// 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.+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"+}++// Which permission ability a rule applies to. getOrgPermission builds org-level abilities,+// getProjectPermission builds project-level abilities; a scope can contribute to either or both.+export type OauthScopeLevel = "org" | "project";++export type TOauthScopeRule = {+ level: OauthScopeLevel;+ subject: string;+ actions: string[];+};++type TOauthScopeDefinition = {+ description: string;+ rules: TOauthScopeRule[];+};++export const OAUTH_SCOPE_DEFINITIONS: Record<OauthScope, TOauthScopeDefinition> = {+ [OauthScope.SecretsRead]: {+ description: "Read secrets, folders, and imports",+ rules: [+ {+ level: "project",+ subject: ProjectPermissionSub.Secrets,+ actions: [+ ProjectPermissionSecretActions.DescribeAndReadValue,+ ProjectPermissionSecretActions.DescribeSecret,+ ProjectPermissionSecretActions.ReadValue+ ]+ },+ { 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)+ }+ ]+ }+};++export const isValidOauthScope = (value: string): value is OauthScope =>+ Object.prototype.hasOwnProperty.call(OAUTH_SCOPE_DEFINITIONS, value);++// OAuth scope requests are a space-delimited string (RFC 6749 §3.3). Splits, de-duplicates, and+// partitions into recognized scopes vs. unknown ones so the caller can reject `invalid_scope`.+export const parseOauthScopeString = (raw?: string): { granted: OauthScope[]; invalid: string[] } => {+ const seen = new Set<string>();+ const granted: OauthScope[] = [];+ const invalid: string[] = [];++ (raw ?? "")+ .split(/\s+/)+ .map((token) => token.trim())+ .filter((value) => {+ const keep = Boolean(value) && !seen.has(value);+ seen.add(value);+ return keep;+ })+ .forEach((value) => {+ if (isValidOauthScope(value)) granted.push(value);+ else invalid.push(value);+ });++ return { granted, invalid };+};++export const getOauthScopeDescriptions = (scopes: OauthScope[]) =>+ scopes.map((scope) => ({ scope, description: OAUTH_SCOPE_DEFINITIONS[scope].description }));++// CASL wildcards: "manage" matches every action on a subject, "all" matches every subject.+const CASL_MANAGE_ACTION = "manage";+const CASL_ALL_SUBJECT = "all";++type TCaslRuleLike = {+ action: string | string[];+ subject?: string | string[];+ inverted?: boolean;+};++const buildAllowedActionMap = (scopes: OauthScope[], level: OauthScopeLevel) => {+ const allowed = new Map<string, Set<string>>();+ scopes+ .flatMap((scope) => OAUTH_SCOPE_DEFINITIONS[scope].rules)+ .filter((rule) => rule.level === level)+ .forEach((rule) => {+ const existing = allowed.get(rule.subject) ?? new Set<string>();+ rule.actions.forEach((action) => existing.add(action));+ allowed.set(rule.subject, existing);+ });+ return allowed;+};++// A rule on the CASL "all" subject (e.g. org/project admin) fans out to every in-scope subject;+// any other subject maps to itself only when it is in scope, otherwise to nothing.+const resolveTargetSubjects = (ruleSubject: string | undefined, allowed: Map<string, Set<string>>): string[] => {+ if (ruleSubject === CASL_ALL_SUBJECT) return [...allowed.keys()];+ if (ruleSubject && allowed.has(ruleSubject)) return [ruleSubject];+ return [];+};++// Intersects a CASL rule set with the actions permitted by the granted scopes. This is purely+// subtractive: allow-rules are dropped if their subject is out of scope, and otherwise narrowed to+// the scope-permitted actions (conditions are preserved, so resource constraints still apply).+// Inverted ("cannot") rules are kept untouched because they only further restrict access.+const intersectRulesWithScopes = <T extends TCaslRuleLike>(rules: T[], allowed: Map<string, Set<string>>): T[] =>+ rules.flatMap((rule) => {+ if (rule.inverted) return [rule];++ const ruleSubjects = Array.isArray(rule.subject) ? rule.subject : [rule.subject];+ const ruleActions = Array.isArray(rule.action) ? rule.action : [rule.action];+ const grantsManage = ruleActions.includes(CASL_MANAGE_ACTION);++ return ruleSubjects.flatMap((ruleSubject) =>+ resolveTargetSubjects(ruleSubject, allowed).flatMap((subject) => {+ const allowedActions = allowed.get(subject) ?? new Set<string>();+ const newActions = grantsManage+ ? [...allowedActions]+ : ruleActions.filter((action) => allowedActions.has(action));+ return newActions.length ? [{ ...rule, subject, action: newActions }] : [];+ })+ );+ });++export const applyOauthScopeToOrgRules = <T extends TCaslRuleLike>(rules: T[], scopes: OauthScope[]): T[] =>+ intersectRulesWithScopes(rules, buildAllowedActionMap(scopes, "org"));++export const applyOauthScopeToProjectRules = <T extends TCaslRuleLike>(rules: T[], scopes: OauthScope[]): T[] =>+ intersectRulesWithScopes(rules, buildAllowedActionMap(scopes, "project"));diff --git a/frontend/src/hooks/api/oauthClients/queries.tsx b/frontend/src/hooks/api/oauthClients/queries.tsxindex ca8697e358..f5da1c4381 100644--- a/frontend/src/hooks/api/oauthClients/queries.tsx+++ b/frontend/src/hooks/api/oauthClients/queries.tsx@@ -6,8 +6,8 @@ import { TOauthAuthorizeInfo, TOauthClient } from "./types";export const oauthClientKeys = {list: (orgId: string) => [{ orgId }, "oauth-clients"] as const,- authorizeInfo: (clientId: string, redirectUri: string) =>- ["oauth-authorize-info", clientId, redirectUri] as const,+ authorizeInfo: (clientId: string, redirectUri: string, scope?: string) =>+ ["oauth-authorize-info", clientId, redirectUri, scope ?? ""] as const,all: ["oauth-clients"] as const};@@ -22,14 +22,15 @@ export const useGetOauthClients = (orgId: string) => {});};-export const useGetOauthAuthorizeInfo = (clientId: string, redirectUri: string) => {+export const useGetOauthAuthorizeInfo = (clientId: string, redirectUri: string, scope?: string) => {return useQuery({- queryKey: oauthClientKeys.authorizeInfo(clientId, redirectUri),+ queryKey: oauthClientKeys.authorizeInfo(clientId, redirectUri, scope),queryFn: async () => {const { data } = await apiRequest.get<TOauthAuthorizeInfo>("/api/v1/oauth/authorize/info", {params: {client_id: clientId,- redirect_uri: redirectUri+ redirect_uri: redirectUri,+ ...(scope ? { scope } : {})}});return data;diff --git a/frontend/src/hooks/api/oauthClients/types.ts b/frontend/src/hooks/api/oauthClients/types.tsindex a29fe1775c..abdb5d9d46 100644--- a/frontend/src/hooks/api/oauthClients/types.ts+++ b/frontend/src/hooks/api/oauthClients/types.ts@@ -34,10 +34,16 @@ export type TRotateOauthClientSecretDTO = {clientDbId: string;};+export type TOauthRequestedScope = {+ scope: string;+ description: string;+};+export type TOauthAuthorizeInfo = {clientName: string;clientDescription?: string | null;requirePkce: boolean;+ requestedScopes: TOauthRequestedScope[];};export type TOauthConsentDTO = {diff --git a/frontend/src/pages/organization/OauthConsentPage/OauthConsentPage.tsx b/frontend/src/pages/organization/OauthConsentPage/OauthConsentPage.tsxindex 55bc61bbf0..85e1e31609 100644--- a/frontend/src/pages/organization/OauthConsentPage/OauthConsentPage.tsx+++ b/frontend/src/pages/organization/OauthConsentPage/OauthConsentPage.tsx@@ -28,7 +28,7 @@ export const OauthConsentPage = () => {data: authorizeInfo,isPending: isInfoPending,error: authorizeInfoError- } = useGetOauthAuthorizeInfo(search.client_id, search.redirect_uri);+ } = useGetOauthAuthorizeInfo(search.client_id, search.redirect_uri, search.scope);const { mutateAsync: consentOauth, isPending: isConsenting } = useOauthConsent();@@ -123,9 +123,23 @@ export const OauthConsentPage = () => {<p className="mt-1 text-sm text-accent">{authorizeInfo.clientDescription}</p>)}<p className="mt-3 text-xs text-muted">- This application will be able to act on your behalf with your existing Infisical- permissions until you revoke its session.+ {authorizeInfo.requestedScopes.length+ ? "This application is requesting the following access on your behalf, limited to your existing Infisical permissions, until you revoke its session."+ : "This application will be able to act on your behalf with your existing Infisical permissions until you revoke its session."}</p>+ {authorizeInfo.requestedScopes.length > 0 && (+ <ul className="mt-3 flex flex-col gap-2">+ {authorizeInfo.requestedScopes.map(({ scope, description }) => (+ <li key={scope} className="flex items-start gap-2 text-sm text-foreground">+ <CheckCircle2 className="mt-0.5 size-4 shrink-0 text-success" />+ <span>+ {description}+ <span className="ml-1 text-xs text-muted">({scope})</span>+ </span>+ </li>+ ))}+ </ul>+ )}</div>)}{!isInfoPending && authorizeInfoError && (