Skip to content

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

add oauth clients and oauth 2.0 exchange flow

Thiago Araujo da Silva72accf763c82
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.ts
index e3fc7592a3..9048cc2462 100644
--- a/backend/src/@types/fastify.d.ts
+++ b/backend/src/@types/fastify.d.ts
@@ -134,6 +134,7 @@ import { TMembershipUserServiceFactory } from "@app/services/membership-user/mem
import { TMfaSessionServiceFactory } from "@app/services/mfa-session/mfa-session-service";
import { TMicrosoftTeamsServiceFactory } from "@app/services/microsoft-teams/microsoft-teams-service";
import { TNotificationServiceFactory } from "@app/services/notification/notification-service";
+import { TOauthClientServiceFactory } from "@app/services/oauth-client/oauth-client-service";
import { TOfflineUsageReportServiceFactory } from "@app/services/offline-usage-report/offline-usage-report-service";
import { TOrgServiceFactory } from "@app/services/org/org-service";
import { TOrgAdminServiceFactory } from "@app/services/org-admin/org-admin-service";
@@ -278,6 +279,7 @@ declare module "fastify" {
accountRecovery: TAccountRecoveryServiceFactory;
signup: TAuthSignupFactory;
authToken: TAuthTokenServiceFactory;
+ oauthClient: TOauthClientServiceFactory;
permission: TPermissionServiceFactory;
org: TOrgServiceFactory;
oidc: TOidcConfigServiceFactory;
diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.ts
index 1503624f66..696b868165 100644
--- a/backend/src/@types/knex.d.ts
+++ b/backend/src/@types/knex.d.ts
@@ -308,6 +308,9 @@ import {
TMemberships,
TMembershipsInsert,
TMembershipsUpdate,
+ TOauthClients,
+ TOauthClientsInsert,
+ TOauthClientsUpdate,
TOidcConfigs,
TOidcConfigsInsert,
TOidcConfigsUpdate,
@@ -1371,6 +1374,7 @@ declare module "knex/types/tables" {
>;
[TableName.EmailDomains]: KnexOriginal.CompositeTableType<TEmailDomains, TEmailDomainsInsert, TEmailDomainsUpdate>;
[TableName.SamlConfig]: KnexOriginal.CompositeTableType<TSamlConfigs, TSamlConfigsInsert, TSamlConfigsUpdate>;
+ [TableName.OauthClient]: KnexOriginal.CompositeTableType<TOauthClients, TOauthClientsInsert, TOauthClientsUpdate>;
[TableName.OidcConfig]: KnexOriginal.CompositeTableType<TOidcConfigs, TOidcConfigsInsert, TOidcConfigsUpdate>;
[TableName.LdapConfig]: KnexOriginal.CompositeTableType<TLdapConfigs, TLdapConfigsInsert, TLdapConfigsUpdate>;
[TableName.LdapGroupMap]: KnexOriginal.CompositeTableType<
diff --git a/backend/src/db/migrations/20260605000000_create-oauth-clients.ts b/backend/src/db/migrations/20260605000000_create-oauth-clients.ts
new file mode 100644
index 0000000000..a3f8c92f4a
--- /dev/null
+++ b/backend/src/db/migrations/20260605000000_create-oauth-clients.ts
@@ -0,0 +1,30 @@
+import { Knex } from "knex";
+
+import { TableName } from "@app/db/schemas";
+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "@app/db/utils";
+
+export async function up(knex: Knex): Promise<void> {
+ if (!(await knex.schema.hasTable(TableName.OauthClient))) {
+ await knex.schema.createTable(TableName.OauthClient, (t) => {
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+ t.uuid("orgId").notNullable();
+ t.foreign("orgId").references("id").inTable(TableName.Organization).onDelete("CASCADE");
+ t.string("name").notNullable();
+ t.text("description");
+ t.string("clientId").notNullable().unique();
+ t.string("clientSecretHash").notNullable();
+ t.string("clientSecretPrefix").notNullable();
+ t.specificType("redirectUris", "text[]").notNullable();
+ t.boolean("requirePkce").notNullable().defaultTo(false);
+ t.timestamps(true, true, true);
+ t.index(["orgId"]);
+ });
+
+ await createOnUpdateTrigger(knex, TableName.OauthClient);
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ await knex.schema.dropTableIfExists(TableName.OauthClient);
+ await dropOnUpdateTrigger(knex, TableName.OauthClient);
+}
diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.ts
index d43d2a6454..a381a4e19e 100644
--- a/backend/src/db/schemas/index.ts
+++ b/backend/src/db/schemas/index.ts
@@ -112,6 +112,7 @@ export * from "./membership-roles";
export * from "./memberships";
export * from "./microsoft-teams-integrations";
export * from "./models";
+export * from "./oauth-clients";
export * from "./oidc-configs";
export * from "./org-bots";
export * from "./org-gateway-config";
diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.ts
index fe1f074ab6..ef68f60760 100644
--- a/backend/src/db/schemas/models.ts
+++ b/backend/src/db/schemas/models.ts
@@ -301,6 +301,9 @@ export enum TableName {
CaSigningConfig = "ca_signing_configs",
SecretValidationRule = "secret_validation_rules",
+ // OAuth 2.0 authorization server (Infisical as an OAuth provider)
+ OauthClient = "oauth_clients",
+
// Honey Tokens
HoneyTokenConfig = "honey_token_configs",
HoneyToken = "honey_tokens",
diff --git a/backend/src/db/schemas/oauth-clients.ts b/backend/src/db/schemas/oauth-clients.ts
new file mode 100644
index 0000000000..00f49538c7
--- /dev/null
+++ b/backend/src/db/schemas/oauth-clients.ts
@@ -0,0 +1,26 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const OauthClientsSchema = z.object({
+ id: z.string().uuid(),
+ orgId: z.string().uuid(),
+ name: z.string(),
+ description: z.string().nullable().optional(),
+ clientId: z.string(),
+ clientSecretHash: z.string(),
+ clientSecretPrefix: z.string(),
+ redirectUris: z.string().array(),
+ requirePkce: z.boolean().default(false),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export type TOauthClients = z.infer<typeof OauthClientsSchema>;
+export type TOauthClientsInsert = Omit<z.input<typeof OauthClientsSchema>, TImmutableDBKeys>;
+export type TOauthClientsUpdate = Partial<Omit<z.input<typeof OauthClientsSchema>, TImmutableDBKeys>>;
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index faea68bbaa..9f05e80459 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -859,6 +859,14 @@ export enum EventType {
EXTERNAL_MIGRATION_CREATE = "external-migration-create",
EXTERNAL_MIGRATION_UPDATE = "external-migration-update",
EXTERNAL_MIGRATION_DELETE = "external-migration-delete",
+
+ // OAuth 2.0 authorization server clients
+ CREATE_OAUTH_CLIENT = "create-oauth-client",
+ UPDATE_OAUTH_CLIENT = "update-oauth-client",
+ DELETE_OAUTH_CLIENT = "delete-oauth-client",
+ ROTATE_OAUTH_CLIENT_SECRET = "rotate-oauth-client-secret",
+ OAUTH_CLIENT_AUTHORIZE = "oauth-client-authorize",
+
// Email Domains
CREATE_EMAIL_DOMAIN = "create-email-domain",
VERIFY_EMAIL_DOMAIN = "verify-email-domain",
@@ -7071,6 +7079,50 @@ interface ExternalMigrationDeleteEvent {
provider: string;
};
}
+interface CreateOauthClientEvent {
+ type: EventType.CREATE_OAUTH_CLIENT;
+ metadata: {
+ clientDbId: string;
+ clientId: string;
+ name: string;
+ };
+}
+
+interface UpdateOauthClientEvent {
+ type: EventType.UPDATE_OAUTH_CLIENT;
+ metadata: {
+ clientDbId: string;
+ clientId: string;
+ name: string;
+ };
+}
+
+interface DeleteOauthClientEvent {
+ type: EventType.DELETE_OAUTH_CLIENT;
+ metadata: {
+ clientDbId: string;
+ clientId: string;
+ name: string;
+ };
+}
+
+interface RotateOauthClientSecretEvent {
+ type: EventType.ROTATE_OAUTH_CLIENT_SECRET;
+ metadata: {
+ clientDbId: string;
+ clientId: string;
+ name: string;
+ };
+}
+
+interface OauthClientAuthorizeEvent {
+ type: EventType.OAUTH_CLIENT_AUTHORIZE;
+ metadata: {
+ clientId: string;
+ clientName: string;
+ };
+}
+
interface CreateEmailDomainEvent {
type: EventType.CREATE_EMAIL_DOMAIN;
metadata: {
@@ -7921,6 +7973,11 @@ export type Event =
| ExternalMigrationCreateEvent
| ExternalMigrationUpdateEvent
| ExternalMigrationDeleteEvent
+ | CreateOauthClientEvent
+ | UpdateOauthClientEvent
+ | DeleteOauthClientEvent
+ | RotateOauthClientSecretEvent
+ | OauthClientAuthorizeEvent
| CreateEmailDomainEvent
| VerifyEmailDomainEvent
| DeleteEmailDomainEvent
diff --git a/backend/src/ee/services/permission/org-permission.ts b/backend/src/ee/services/permission/org-permission.ts
index 1f84baceb3..a2642b46e1 100644
--- a/backend/src/ee/services/permission/org-permission.ts
+++ b/backend/src/ee/services/permission/org-permission.ts
@@ -172,7 +172,8 @@ export enum OrgPermissionSubjects {
SubOrganization = "sub-organization",
EmailDomains = "email-domains",
CertManager = "certificate-manager",
- HoneyTokens = "honey-tokens"
+ HoneyTokens = "honey-tokens",
+ OauthClients = "oauth-clients"
}
export type AppConnectionSubjectFields = {
@@ -215,7 +216,8 @@ export type OrgPermissionSet =
| [OrgPermissionSecretShareAction, OrgPermissionSubjects.SecretShare]
| [OrgPermissionEmailDomainActions, OrgPermissionSubjects.EmailDomains]
| [OrgPermissionCertManagerActions, OrgPermissionSubjects.CertManager]
- | [OrgPermissionHoneyTokenActions, OrgPermissionSubjects.HoneyTokens];
+ | [OrgPermissionHoneyTokenActions, OrgPermissionSubjects.HoneyTokens]
+ | [OrgPermissionActions, OrgPermissionSubjects.OauthClients];
const AppConnectionConditionSchema = z
.object({
@@ -392,6 +394,10 @@ export const OrgPermissionSchema = z.discriminatedUnion("subject", [
action: CASL_ACTION_SCHEMA_NATIVE_ENUM(OrgPermissionHoneyTokenActions).describe(
"Describe what action an entity can take."
)
+ }),
+ z.object({
+ subject: z.literal(OrgPermissionSubjects.OauthClients).describe("The entity this permission pertains to."),
+ action: CASL_ACTION_SCHEMA_NATIVE_ENUM(OrgPermissionActions).describe("Describe what action an entity can take.")
})
]);
@@ -557,6 +563,11 @@ const buildAdminPermission = () => {
can(OrgPermissionCertManagerActions.ManageInstance, OrgPermissionSubjects.CertManager);
can(OrgPermissionCertManagerActions.ManageSettings, OrgPermissionSubjects.CertManager);
+ can(OrgPermissionActions.Read, OrgPermissionSubjects.OauthClients);
+ can(OrgPermissionActions.Create, OrgPermissionSubjects.OauthClients);
+ can(OrgPermissionActions.Edit, OrgPermissionSubjects.OauthClients);
+ can(OrgPermissionActions.Delete, OrgPermissionSubjects.OauthClients);
+
return rules;
};
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index 9016f89a70..a1f6e08b47 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -99,6 +99,9 @@ export const KeyStorePrefixes = {
AiMcpEndpointOAuthClient: (clientId: string) => `ai-mcp-endpoint-oauth-client:${clientId}` as const,
AiMcpEndpointOAuthCode: (clientId: string, code: string) => `ai-mcp-endpoint-oauth-code:${clientId}:${code}` as const,
+ // OAuth 2.0 authorization server (Infisical as an OAuth provider)
+ OauthAuthorizationCode: (code: string) => `oauth-authorization-code:${code}` as const,
+
// Project SSE Connection Rate Limiting
ProjectSSEConnectionsSet: (projectId: string) => `project-sse-connections:${projectId}` as const,
ProjectSSEConnectionsLockoutKey: (projectId: string) => `project-sse-connections:lockout:${projectId}` as const,
@@ -159,6 +162,7 @@ export const KeyStoreTtls = {
AuditLogMigrationAlertInSeconds: 604800, // 7 days
LicenseCloudPlanInSeconds: 300, // 5 minutes
AiMcpEndpointOAuthFlowInSeconds: 300, // 5 minutes
+ OauthAuthorizationCodeInSeconds: 600, // 10 minutes
AiMcpServerOAuthSessionInSeconds: 600, // 10 minutes
DashboardCacheInSeconds: 600, // 10 minutes
ProjectEnvironmentOperationMarkerInSeconds: 10,
diff --git a/backend/src/server/plugins/auth/inject-identity.ts b/backend/src/server/plugins/auth/inject-identity.ts
index 973fd065e0..4b983491a1 100644
--- a/backend/src/server/plugins/auth/inject-identity.ts
+++ b/backend/src/server/plugins/auth/inject-identity.ts
@@ -212,6 +212,10 @@ export const injectIdentity = fp(
return;
}
+ if (pathname === "/api/v1/oauth/token") {
+ return;
+ }
+
// Authentication is handled on a route-level
if (pathname === "/api/v1/relays/register-instance-relay") {
return;
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 4ff02593da..e27bfed496 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -389,6 +389,8 @@ import { projectMicrosoftTeamsConfigDALFactory } from "@app/services/microsoft-t
import { notificationQueueServiceFactory } from "@app/services/notification/notification-queue";
import { notificationServiceFactory } from "@app/services/notification/notification-service";
import { userNotificationDALFactory } from "@app/services/notification/user-notification-dal";
+import { oauthClientDALFactory } from "@app/services/oauth-client/oauth-client-dal";
+import { oauthClientServiceFactory } from "@app/services/oauth-client/oauth-client-service";
import { offlineUsageReportDALFactory } from "@app/services/offline-usage-report/offline-usage-report-dal";
import { offlineUsageReportServiceFactory } from "@app/services/offline-usage-report/offline-usage-report-service";
import { incidentContactDALFactory } from "@app/services/org/incident-contacts-dal";
@@ -792,6 +794,15 @@ export const registerRoutes = async (
approvalPolicyDAL
});
+ const oauthClientDAL = oauthClientDALFactory(db);
+ const oauthClientService = oauthClientServiceFactory({
+ oauthClientDAL,
+ permissionService,
+ keyStore,
+ tokenService,
+ orgDAL
+ });
+
const membershipUserService = membershipUserServiceFactory({
licenseService,
membershipRoleDAL,
@@ -3608,6 +3619,7 @@ export const registerRoutes = async (
subOrganization: subOrgService,
oidc: oidcService,
authToken: tokenService,
+ oauthClient: oauthClientService,
superAdmin: superAdminService,
offlineUsageReport: offlineUsageReportService,
orgProductStats: orgProductStatsService,
diff --git a/backend/src/server/routes/v1/index.ts b/backend/src/server/routes/v1/index.ts
index 1769a70480..9b6a656a76 100644
--- a/backend/src/server/routes/v1/index.ts
+++ b/backend/src/server/routes/v1/index.ts
@@ -64,6 +64,7 @@ import { registerIntegrationRouter } from "./integration-router";
import { registerInviteOrgRouter } from "./invite-org-router";
import { registerMicrosoftTeamsRouter } from "./microsoft-teams-router";
import { registerNotificationRouter } from "./notification-router";
+import { registerOAuthRouter } from "./oauth-router";
import { registerOrgAdminRouter } from "./org-admin-router";
import { registerOrgIdentityRouter } from "./org-identity-router";
import { registerOrganizationMembershipsRouter } from "./organization-memberships-router";
@@ -119,6 +120,7 @@ export const registerV1Routes = async (server: FastifyZodProvider) => {
);
await server.register(registerPasswordRouter, { prefix: "/password" });
await server.register(registerAccountRecoveryRouter, { prefix: "/account-recovery" });
+ await server.register(registerOAuthRouter, { prefix: "/oauth" });
await server.register(
async (orgRouter) => {
await orgRouter.register(registerOrgRouter);
diff --git a/backend/src/server/routes/v1/oauth-router.ts b/backend/src/server/routes/v1/oauth-router.ts
new file mode 100644
index 0000000000..52c37dd07e
--- /dev/null
+++ b/backend/src/server/routes/v1/oauth-router.ts
@@ -0,0 +1,435 @@
+import { z } from "zod";
+
+import { OauthClientsSchema } from "@app/db/schemas";
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { BadRequestError } from "@app/lib/errors";
+import { authRateLimit, readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AuthMode } from "@app/services/auth/auth-type";
+import { parseBasicAuthHeader } from "@app/services/oauth-client/oauth-client-fns";
+
+const SanitizedOauthClientSchema = OauthClientsSchema.omit({ clientSecretHash: true });
+
+const redirectUriSchema = z
+ .string()
+ .url()
+ .refine(
+ (uri) => uri.startsWith("https://") || uri.startsWith("http://"),
+ "Redirect URI must start with https:// or http://"
+ );
+
+export const registerOAuthRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "POST",
+ url: "/clients",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ operationId: "createOauthClient",
+ body: z.object({
+ name: z.string().trim().min(1).max(64),
+ description: z.string().trim().max(256).optional(),
+ redirectUris: redirectUriSchema.array().min(1),
+ requirePkce: z.boolean().optional()
+ }),
+ response: {
+ 200: z.object({
+ client: SanitizedOauthClientSchema,
+ clientSecret: z.string()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const { client, clientSecret } = await server.services.oauthClient.createOauthClient(req.body, req.permission);
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ event: {
+ type: EventType.CREATE_OAUTH_CLIENT,
+ metadata: {
+ clientDbId: client.id,
+ clientId: client.clientId,
+ name: client.name
+ }
+ }
+ });
+
+ return { client, clientSecret };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/clients",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ operationId: "listOauthClients",
+ response: {
+ 200: z.object({
+ clients: SanitizedOauthClientSchema.array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const clients = await server.services.oauthClient.listOauthClients(req.permission);
+ return { clients };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/clients/:clientDbId",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ operationId: "getOauthClientById",
+ params: z.object({
+ clientDbId: z.string().uuid()
+ }),
+ response: {
+ 200: z.object({
+ client: SanitizedOauthClientSchema
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const client = await server.services.oauthClient.getOauthClientById(req.params.clientDbId, req.permission);
+ return { client };
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/clients/:clientDbId",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ operationId: "updateOauthClient",
+ params: z.object({
+ clientDbId: z.string().uuid()
+ }),
+ body: z.object({
+ name: z.string().trim().min(1).max(64).optional(),
+ description: z.string().trim().max(256).nullable().optional(),
+ redirectUris: redirectUriSchema.array().min(1).optional(),
+ requirePkce: z.boolean().optional()
+ }),
+ response: {
+ 200: z.object({
+ client: SanitizedOauthClientSchema
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const client = await server.services.oauthClient.updateOauthClient(
+ { clientDbId: req.params.clientDbId, ...req.body },
+ req.permission
+ );
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ event: {
+ type: EventType.UPDATE_OAUTH_CLIENT,
+ metadata: {
+ clientDbId: client.id,
+ clientId: client.clientId,
+ name: client.name
+ }
+ }
+ });
+
+ return { client };
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/clients/:clientDbId/rotate-secret",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ operationId: "rotateOauthClientSecret",
+ params: z.object({
+ clientDbId: z.string().uuid()
+ }),
+ response: {
+ 200: z.object({
+ client: SanitizedOauthClientSchema,
+ clientSecret: z.string()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const { client, clientSecret } = await server.services.oauthClient.rotateOauthClientSecret(
+ req.params.clientDbId,
+ req.permission
+ );
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ event: {
+ type: EventType.ROTATE_OAUTH_CLIENT_SECRET,
+ metadata: {
+ clientDbId: client.id,
+ clientId: client.clientId,
+ name: client.name
+ }
+ }
+ });
+
+ return { client, clientSecret };
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/clients/:clientDbId",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ operationId: "deleteOauthClient",
+ params: z.object({
+ clientDbId: z.string().uuid()
+ }),
+ response: {
+ 200: z.object({
+ client: SanitizedOauthClientSchema
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const client = await server.services.oauthClient.deleteOauthClient(req.params.clientDbId, req.permission);
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ event: {
+ type: EventType.DELETE_OAUTH_CLIENT,
+ metadata: {
+ clientDbId: client.id,
+ clientId: client.clientId,
+ name: client.name
+ }
+ }
+ });
+
+ return { client };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/authorize",
+ config: {
+ rateLimit: authRateLimit
+ },
+ schema: {
+ querystring: z.object({
+ response_type: z.literal("code"),
+ client_id: z.string(),
+ redirect_uri: z.string().url(),
+ state: z.string().optional(),
+ code_challenge: z.string().optional(),
+ code_challenge_method: z.enum(["S256"]).optional(),
+ scope: z.string().optional()
+ })
+ },
+ handler: async (req, res) => {
+ // Validates client + redirect URI before redirecting (never redirect to an
+ // unregistered URI per RFC 6749 §3.1.2.4)
+ const info = await server.services.oauthClient.getAuthorizeInfo({
+ clientId: req.query.client_id,
+ redirectUri: req.query.redirect_uri
+ });
+
+ // Surface the PKCE requirement up front rather than after the user has consented
+ if (info.requirePkce && !req.query.code_challenge) {
+ throw new BadRequestError({ message: "This OAuth client requires PKCE (code_challenge is missing)" });
+ }
+
+ const query = new URLSearchParams(
+ Object.entries(req.query).filter(([, value]) => value !== undefined)
+ ).toString();
+
+ void res.redirect(`/organization/oauth-consent?${query}`);
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/authorize/info",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ querystring: z.object({
+ client_id: z.string(),
+ redirect_uri: z.string().url()
+ }),
+ response: {
+ 200: z.object({
+ clientName: z.string(),
+ clientDescription: z.string().nullable().optional(),
+ requirePkce: z.boolean()
+ })
+ }
+ },
+ handler: async (req) => {
+ const info = await server.services.oauthClient.getAuthorizeInfo({
+ clientId: req.query.client_id,
+ redirectUri: req.query.redirect_uri
+ });
+
+ return {
+ clientName: info.clientName,
+ clientDescription: info.clientDescription,
+ requirePkce: info.requirePkce
+ };
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/authorize/consent",
+ config: {
+ rateLimit: authRateLimit
+ },
+ schema: {
+ body: z.object({
+ client_id: z.string(),
+ redirect_uri: z.string().url(),
+ state: z.string().optional(),
+ code_challenge: z.string().optional(),
+ code_challenge_method: z.enum(["S256"]).optional(),
+ scope: z.string().optional()
+ }),
+ response: {
+ 200: z.object({
+ callbackUrl: z.string()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ if (req.auth.authMode !== AuthMode.JWT) throw new BadRequestError({ message: "Invalid auth mode" });
+
+ const { callbackUrl, clientName, orgId } = await server.services.oauthClient.authorizeConsent({
+ clientId: req.body.client_id,
+ redirectUri: req.body.redirect_uri,
+ state: req.body.state,
+ codeChallenge: req.body.code_challenge,
+ codeChallengeMethod: req.body.code_challenge_method,
+ scope: req.body.scope,
+ userId: req.auth.userId,
+ authMethod: req.auth.authMethod,
+ isMfaVerified: req.auth.isMfaVerified,
+ mfaMethod: req.auth.mfaMethod,
+ ip: req.realIp
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId,
+ event: {
+ type: EventType.OAUTH_CLIENT_AUTHORIZE,
+ metadata: {
+ clientId: req.body.client_id,
+ clientName
+ }
+ }
+ });
+
+ return { callbackUrl };
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/token",
+ config: {
+ rateLimit: authRateLimit
+ },
+ schema: {
+ body: z.object({
+ grant_type: z.enum(["authorization_code", "refresh_token"]),
+ code: z.string().optional(),
+ redirect_uri: z.string().optional(),
+ code_verifier: z.string().optional(),
+ refresh_token: z.string().optional(),
+ client_id: z.string().optional(),
+ client_secret: z.string().optional()
+ }),
+ response: {
+ 200: z.object({
+ access_token: z.string(),
+ token_type: z.string(),
+ expires_in: z.number(),
+ refresh_token: z.string(),
+ scope: z.string()
+ })
+ }
+ },
+ handler: async (req, res) => {
+ const basicAuth = parseBasicAuthHeader(req.headers.authorization);
+ const clientId = basicAuth?.clientId ?? req.body.client_id;
+ const clientSecret = basicAuth?.clientSecret ?? req.body.client_secret;
+
+ void res.header("Cache-Control", "no-store");
+
+ if (req.body.grant_type === "authorization_code") {
+ if (!req.body.code) throw new BadRequestError({ message: "Missing authorization code" });
+
+ return server.services.oauthClient.exchangeToken({
+ grantType: "authorization_code",
+ code: req.body.code,
+ redirectUri: req.body.redirect_uri,
+ codeVerifier: req.body.code_verifier,
+ clientId,
+ clientSecret
+ });
+ }
+
+ if (!req.body.refresh_token) throw new BadRequestError({ message: "Missing refresh token" });
+
+ return server.services.oauthClient.exchangeToken({
+ grantType: "refresh_token",
+ refreshToken: req.body.refresh_token,
+ clientId,
+ clientSecret
+ });
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/validate",
+ config: {
+ rateLimit: authRateLimit
+ },
+ schema: {
+ response: {
+ 200: z.object({
+ active: z.literal(true)
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: () => ({ active: true as const })
+ });
+};
diff --git a/backend/src/services/oauth-client/oauth-client-dal.ts b/backend/src/services/oauth-client/oauth-client-dal.ts
new file mode 100644
index 0000000000..f4c18c8df5
--- /dev/null
+++ b/backend/src/services/oauth-client/oauth-client-dal.ts
@@ -0,0 +1,11 @@
+import { TDbClient } from "@app/db";
+import { TableName } from "@app/db/schemas";
+import { ormify } from "@app/lib/knex";
+
+export type TOauthClientDALFactory = ReturnType<typeof oauthClientDALFactory>;
+
+export const oauthClientDALFactory = (db: TDbClient) => {
+ const oauthClientOrm = ormify(db, TableName.OauthClient);
+
+ return oauthClientOrm;
+};
diff --git a/backend/src/services/oauth-client/oauth-client-fns.test.ts b/backend/src/services/oauth-client/oauth-client-fns.test.ts
new file mode 100644
index 0000000000..e050693bfc
--- /dev/null
+++ b/backend/src/services/oauth-client/oauth-client-fns.test.ts
@@ -0,0 +1,80 @@
+import crypto from "node:crypto";
+
+import { computePkceChallenge, isRegisteredRedirectUri, parseBasicAuthHeader } from "./oauth-client-fns";
+
+describe("parseBasicAuthHeader", () => {
+ test("parses a valid Basic auth header", () => {
+ const header = `Basic ${Buffer.from("my-client:my-secret").toString("base64")}`;
+ expect(parseBasicAuthHeader(header)).toEqual({ clientId: "my-client", clientSecret: "my-secret" });
+ });
+
+ test("decodes form-urlencoded credentials", () => {
+ const header = `Basic ${Buffer.from("client%3Aid:se%2Fcret").toString("base64")}`;
+ expect(parseBasicAuthHeader(header)).toEqual({ clientId: "client:id", clientSecret: "se/cret" });
+ });
+
+ test("handles secrets containing colons", () => {
+ const header = `Basic ${Buffer.from("client:sec:ret").toString("base64")}`;
+ expect(parseBasicAuthHeader(header)).toEqual({ clientId: "client", clientSecret: "sec:ret" });
+ });
+
+ test("returns null for missing header", () => {
+ expect(parseBasicAuthHeader(undefined)).toBeNull();
+ });
+
+ test("returns null for Bearer header", () => {
+ expect(parseBasicAuthHeader("Bearer some-jwt")).toBeNull();
+ });
+
+ test("returns null when credentials have no separator", () => {
+ const header = `Basic ${Buffer.from("no-separator").toString("base64")}`;
+ expect(parseBasicAuthHeader(header)).toBeNull();
+ });
+});
+
+describe("computePkceChallenge", () => {
+ test("computes the S256 challenge of a verifier", () => {
+ const verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
+ const expected = crypto.createHash("sha256").update(verifier).digest("base64url");
+ expect(computePkceChallenge(verifier)).toEqual(expected);
+ });
+
+ test("matches the RFC 7636 appendix B test vector", () => {
+ expect(computePkceChallenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk")).toEqual(
+ "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
+ );
+ });
+});
+
+describe("isRegisteredRedirectUri", () => {
+ test("matches exact URI", () => {
+ expect(
+ isRegisteredRedirectUri(
+ ["https://coder.example.com/external-auth/infisical/callback"],
+ "https://coder.example.com/external-auth/infisical/callback"
+ )
+ ).toBe(true);
+ });
+
+ test("matches URL-normalized URI", () => {
+ expect(isRegisteredRedirectUri(["https://coder.example.com"], "https://coder.example.com/")).toBe(true);
+ });
+
+ test("rejects unregistered URI", () => {
+ expect(
+ isRegisteredRedirectUri(
+ ["https://coder.example.com/external-auth/infisical/callback"],
+ "https://evil.example.com/callback"
+ )
+ ).toBe(false);
+ });
+
+ test("rejects URI with extra path segments", () => {
+ expect(
+ isRegisteredRedirectUri(
+ ["https://coder.example.com/external-auth"],
+ "https://coder.example.com/external-auth/other"
+ )
+ ).toBe(false);
+ });
+});
diff --git a/backend/src/services/oauth-client/oauth-client-fns.ts b/backend/src/services/oauth-client/oauth-client-fns.ts
new file mode 100644
index 0000000000..4299086575
--- /dev/null
+++ b/backend/src/services/oauth-client/oauth-client-fns.ts
@@ -0,0 +1,44 @@
+import crypto from "node:crypto";
+
+export const parseBasicAuthHeader = (
+ authorizationHeader?: string
+): { clientId: string; clientSecret: string } | null => {
+ if (!authorizationHeader) return null;
+
+ const [scheme, value] = authorizationHeader.split(" ");
+ if (scheme?.toLowerCase() !== "basic" || !value) return null;
+
+ let decoded: string;
+ try {
+ decoded = Buffer.from(value, "base64").toString("utf8");
+ } catch {
+ return null;
+ }
+
+ const separatorIndex = decoded.indexOf(":");
+ if (separatorIndex === -1) return null;
+
+ try {
+ return {
+ clientId: decodeURIComponent(decoded.slice(0, separatorIndex)),
+ clientSecret: decodeURIComponent(decoded.slice(separatorIndex + 1))
+ };
+ } catch {
+ return null;
+ }
+};
+
+export const computePkceChallenge = (codeVerifier: string) => {
+ const sha256 = crypto.createHash("sha256").update(codeVerifier).digest();
+ return Buffer.from(sha256).toString("base64url");
+};
+
+export const isRegisteredRedirectUri = (registeredUris: string[], redirectUri: string) =>
+ registeredUris.some((uri) => {
+ if (uri === redirectUri) return true;
+ try {
+ return new URL(uri).toString() === new URL(redirectUri).toString();
+ } catch {
+ return false;
+ }
+ });
diff --git a/backend/src/services/oauth-client/oauth-client-service.ts b/backend/src/services/oauth-client/oauth-client-service.ts
new file mode 100644
index 0000000000..6400e58282
--- /dev/null
+++ b/backend/src/services/oauth-client/oauth-client-service.ts
@@ -0,0 +1,424 @@
+import { ForbiddenError } from "@casl/ability";
+
+import { OrganizationActionScope, TOauthClients } from "@app/db/schemas";
+import { OrgPermissionActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";
+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";
+import { getConfig } from "@app/lib/config/env";
+import { crypto } from "@app/lib/crypto";
+import { BadRequestError, NotFoundError, UnauthorizedError } from "@app/lib/errors";
+import { getMinExpiresIn } from "@app/lib/fn";
+import { ms } from "@app/lib/ms";
+import { OrgServiceActor } from "@app/lib/types";
+import { ActorType, AuthMethod, AuthTokenType, MfaMethod } from "@app/services/auth/auth-type";
+import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";
+import { TOrgDALFactory } from "@app/services/org/org-dal";
+
+import { TOauthClientDALFactory } from "./oauth-client-dal";
+import { computePkceChallenge, isRegisteredRedirectUri } from "./oauth-client-fns";
+import {
+ OauthAuthorizationCodePayloadSchema,
+ TCreateOauthClientDTO,
+ TOauthAuthorizeInfoDTO,
+ TOauthConsentDTO,
+ TOauthRefreshJwtTokenPayload,
+ TOauthTokenExchangeDTO,
+ TUpdateOauthClientDTO
+} from "./oauth-client-types";
+
+type TOauthClientServiceFactoryDep = {
+ oauthClientDAL: TOauthClientDALFactory;
+ permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;
+ keyStore: Pick<TKeyStoreFactory, "setItemWithExpiry" | "getItem" | "deleteItem">;
+ tokenService: Pick<
+ TAuthTokenServiceFactory,
+ "getUserTokenSession" | "getUserTokenSessionById" | "validateRefreshToken" | "rotateRefreshToken"
+ >;
+ orgDAL: Pick<TOrgDALFactory, "findById">;
+};
+
+export type TOauthClientServiceFactory = ReturnType<typeof oauthClientServiceFactory>;
+
+const sanitizeOauthClient = (client: TOauthClients) => {
+ const { clientSecretHash, ...rest } = client;
+ return rest;
+};
+
+const expiresInToSeconds = (expiresIn: string | number) =>
+ typeof expiresIn === "number" ? expiresIn : Math.floor(ms(expiresIn) / 1000);
+
+type TOauthTokenClaims = {
+ authMethod: AuthMethod;
+ userId: string;
+ tokenVersionId: string;
+ organizationId: string;
+ isMfaVerified?: boolean;
+ mfaMethod?: MfaMethod;
+};
+
+const signOauthAccessToken = (claims: TOauthTokenClaims & { accessVersion: number }, expiresIn: string | number) => {
+ const appCfg = getConfig();
+ return crypto.jwt().sign(
+ {
+ authMethod: claims.authMethod,
+ authTokenType: AuthTokenType.ACCESS_TOKEN,
+ userId: claims.userId,
+ tokenVersionId: claims.tokenVersionId,
+ accessVersion: claims.accessVersion,
+ organizationId: claims.organizationId,
+ isMfaVerified: claims.isMfaVerified,
+ mfaMethod: claims.mfaMethod
+ },
+ appCfg.AUTH_SECRET,
+ { expiresIn }
+ );
+};
+
+const signOauthRefreshToken = (
+ claims: TOauthTokenClaims & { refreshVersion: number; oauthClientId: string },
+ expiresIn: string | number
+) => {
+ const appCfg = getConfig();
+ return crypto.jwt().sign(
+ {
+ authMethod: claims.authMethod,
+ authTokenType: AuthTokenType.REFRESH_TOKEN,
+ userId: claims.userId,
+ tokenVersionId: claims.tokenVersionId,
+ refreshVersion: claims.refreshVersion,
+ organizationId: claims.organizationId,
+ isMfaVerified: claims.isMfaVerified,
+ mfaMethod: claims.mfaMethod,
+ oauthClientId: claims.oauthClientId
+ },
+ appCfg.AUTH_SECRET,
+ { expiresIn }
+ );
+};
+
+export const oauthClientServiceFactory = ({
+ oauthClientDAL,
+ permissionService,
+ keyStore,
+ tokenService,
+ orgDAL
+}: TOauthClientServiceFactoryDep) => {
+ const checkOauthClientPermission = async (actor: OrgServiceActor, action: OrgPermissionActions) => {
+ const { permission } = await permissionService.getOrgPermission({
+ actor: actor.type,
+ actorId: actor.id,
+ orgId: actor.orgId,
+ actorAuthMethod: actor.authMethod,
+ actorOrgId: actor.orgId,
+ scope: OrganizationActionScope.ParentOrganization
+ });
+
+ ForbiddenError.from(permission).throwUnlessCan(action, OrgPermissionSubjects.OauthClients);
+ };
+
+ const createOauthClient = async (dto: TCreateOauthClientDTO, actor: OrgServiceActor) => {
+ await checkOauthClientPermission(actor, OrgPermissionActions.Create);
+
+ const appCfg = getConfig();
+ const clientId = `oauth_client_${crypto.randomBytes(16).toString("hex")}`;
+ const clientSecret = crypto.randomBytes(32).toString("hex");
+ const clientSecretHash = await crypto.hashing().createHash(clientSecret, appCfg.SALT_ROUNDS);
+
+ const client = await oauthClientDAL.create({
+ orgId: actor.orgId,
+ name: dto.name,
+ description: dto.description,
+ clientId,
+ clientSecretHash,
+ clientSecretPrefix: clientSecret.slice(0, 4),
+ redirectUris: dto.redirectUris,
+ requirePkce: dto.requirePkce ?? false
+ });
+
+ return { client: sanitizeOauthClient(client), clientSecret };
+ };
+
+ const listOauthClients = async (actor: OrgServiceActor) => {
+ await checkOauthClientPermission(actor, OrgPermissionActions.Read);
+
+ const clients = await oauthClientDAL.find({ orgId: actor.orgId });
+ return clients.map(sanitizeOauthClient);
+ };
+
+ const getOauthClientById = async (clientDbId: string, actor: OrgServiceActor) => {
+ await checkOauthClientPermission(actor, OrgPermissionActions.Read);
+
+ const client = await oauthClientDAL.findOne({ id: clientDbId, orgId: actor.orgId });
+ if (!client) throw new NotFoundError({ message: `OAuth client with ID '${clientDbId}' not found` });
+
+ return sanitizeOauthClient(client);
+ };
+
+ const updateOauthClient = async (dto: TUpdateOauthClientDTO, actor: OrgServiceActor) => {
+ await checkOauthClientPermission(actor, OrgPermissionActions.Edit);
+
+ const client = await oauthClientDAL.findOne({ id: dto.clientDbId, orgId: actor.orgId });
+ if (!client) throw new NotFoundError({ message: `OAuth client with ID '${dto.clientDbId}' not found` });
+
+ const updatedClient = await oauthClientDAL.updateById(client.id, {
+ name: dto.name,
+ description: dto.description,
+ redirectUris: dto.redirectUris,
+ requirePkce: dto.requirePkce
+ });
+
+ return sanitizeOauthClient(updatedClient);
+ };
+
+ const deleteOauthClient = async (clientDbId: string, actor: OrgServiceActor) => {
+ await checkOauthClientPermission(actor, OrgPermissionActions.Delete);
+
+ const client = await oauthClientDAL.findOne({ id: clientDbId, orgId: actor.orgId });
+ if (!client) throw new NotFoundError({ message: `OAuth client with ID '${clientDbId}' not found` });
+
+ const deletedClient = await oauthClientDAL.deleteById(client.id);
+ return sanitizeOauthClient(deletedClient);
+ };
+
+ const rotateOauthClientSecret = async (clientDbId: string, actor: OrgServiceActor) => {
+ await checkOauthClientPermission(actor, OrgPermissionActions.Edit);
+
+ const client = await oauthClientDAL.findOne({ id: clientDbId, orgId: actor.orgId });
+ if (!client) throw new NotFoundError({ message: `OAuth client with ID '${clientDbId}' not found` });
+
+ const appCfg = getConfig();
+ const clientSecret = crypto.randomBytes(32).toString("hex");
+ const clientSecretHash = await crypto.hashing().createHash(clientSecret, appCfg.SALT_ROUNDS);
+
+ const updatedClient = await oauthClientDAL.updateById(client.id, {
+ clientSecretHash,
+ clientSecretPrefix: clientSecret.slice(0, 4)
+ });
+
+ return { client: sanitizeOauthClient(updatedClient), clientSecret };
+ };
+
+ const getAuthorizeInfo = async ({ clientId, redirectUri }: TOauthAuthorizeInfoDTO) => {
+ const client = await oauthClientDAL.findOne({ clientId });
+ if (!client) throw new UnauthorizedError({ message: "OAuth client not found" });
+
+ if (!isRegisteredRedirectUri(client.redirectUris, redirectUri)) {
+ throw new BadRequestError({ message: "Redirect URI is not registered for this OAuth client" });
+ }
+
+ return {
+ clientName: client.name,
+ clientDescription: client.description,
+ orgId: client.orgId,
+ requirePkce: client.requirePkce
+ };
+ };
+
+ const authorizeConsent = async (dto: TOauthConsentDTO) => {
+ const client = await oauthClientDAL.findOne({ clientId: dto.clientId });
+ if (!client) throw new UnauthorizedError({ message: "OAuth client not found" });
+
+ if (!isRegisteredRedirectUri(client.redirectUris, dto.redirectUri)) {
+ throw new BadRequestError({ message: "Redirect URI is not registered for this OAuth client" });
+ }
+
+ if (client.requirePkce && !dto.codeChallenge) {
+ throw new BadRequestError({ message: "This OAuth client requires PKCE (code_challenge is missing)" });
+ }
+
+ await permissionService.getOrgPermission({
+ actor: ActorType.USER,
+ actorId: dto.userId,
+ orgId: client.orgId,
+ actorAuthMethod: dto.authMethod,
+ actorOrgId: client.orgId,
+ scope: OrganizationActionScope.ParentOrganization
+ });
+
+ const tokenSession = await tokenService.getUserTokenSession({
+ userId: dto.userId,
+ ip: dto.ip,
+ userAgent: `Infisical OAuth - ${client.name}`
+ });
+ if (!tokenSession) throw new BadRequestError({ message: "Failed to create user token session" });
+
+ const code = crypto.randomBytes(32).toString("hex");
+ await keyStore.setItemWithExpiry(
+ KeyStorePrefixes.OauthAuthorizationCode(code),
+ KeyStoreTtls.OauthAuthorizationCodeInSeconds,
+ JSON.stringify({
+ clientId: client.clientId,
+ orgId: client.orgId,
+ userId: dto.userId,
+ authMethod: dto.authMethod,
+ isMfaVerified: dto.isMfaVerified,
+ mfaMethod: dto.mfaMethod,
+ tokenVersionId: tokenSession.id,
+ redirectUri: dto.redirectUri,
+ codeChallenge: dto.codeChallenge,
+ codeChallengeMethod: dto.codeChallengeMethod,
+ scope: dto.scope
+ })
+ );
+
+ const callbackUrl = new URL(dto.redirectUri);
+ callbackUrl.searchParams.set("code", code);
+ if (dto.state) callbackUrl.searchParams.set("state", dto.state);
+
+ return { callbackUrl: callbackUrl.toString(), clientName: client.name, orgId: client.orgId };
+ };
+
+ const authenticateClient = async (clientId?: string, clientSecret?: string) => {
+ if (!clientId || !clientSecret) {
+ throw new UnauthorizedError({ message: "Missing OAuth client credentials" });
+ }
+
+ const client = await oauthClientDAL.findOne({ clientId });
+ if (!client) throw new UnauthorizedError({ message: "Invalid OAuth client credentials" });
+
+ const isValidSecret = await crypto.hashing().compareHash(clientSecret, client.clientSecretHash);
+ if (!isValidSecret) throw new UnauthorizedError({ message: "Invalid OAuth client credentials" });
+
+ return client;
+ };
+
+ const getTokenLifetimes = async (orgId: string) => {
+ const appCfg = getConfig();
+ let accessTokenExpiresIn: string | number = appCfg.JWT_AUTH_LIFETIME;
+ let refreshTokenExpiresIn: string | number = appCfg.JWT_REFRESH_LIFETIME;
+
+ const org = await orgDAL.findById(orgId);
+ if (org?.userTokenExpiration) {
+ accessTokenExpiresIn = getMinExpiresIn(appCfg.JWT_AUTH_LIFETIME, org.userTokenExpiration);
+ refreshTokenExpiresIn = org.userTokenExpiration;
+ }
+
+ return { accessTokenExpiresIn, refreshTokenExpiresIn };
+ };
+
+ const exchangeToken = async (dto: TOauthTokenExchangeDTO) => {
+ const client = await authenticateClient(dto.clientId, dto.clientSecret);
+
+ if (dto.grantType === "authorization_code") {
+ const codeKey = KeyStorePrefixes.OauthAuthorizationCode(dto.code);
+ const codePayloadRaw = await keyStore.getItem(codeKey);
+ if (!codePayloadRaw) {
+ throw new UnauthorizedError({ message: "Invalid or expired authorization code" });
+ }
+
+ // One-time use: delete before any further validation
+ await keyStore.deleteItem(codeKey);
+
+ const codePayload = await OauthAuthorizationCodePayloadSchema.parseAsync(JSON.parse(codePayloadRaw));
+
+ if (codePayload.clientId !== client.clientId) {
+ throw new UnauthorizedError({ message: "Authorization code was not issued to this client" });
+ }
+
+ if (!dto.redirectUri || dto.redirectUri !== codePayload.redirectUri) {
+ throw new BadRequestError({ message: "Redirect URI mismatch" });
+ }
+
+ if (codePayload.codeChallenge) {
+ if (!dto.codeVerifier) throw new BadRequestError({ message: "Missing PKCE code_verifier" });
+ if (computePkceChallenge(dto.codeVerifier) !== codePayload.codeChallenge) {
+ throw new BadRequestError({ message: "PKCE challenge mismatch" });
+ }
+ } else if (client.requirePkce) {
+ throw new BadRequestError({ message: "This OAuth client requires PKCE" });
+ }
+
+ const tokenSession = await tokenService.getUserTokenSessionById(codePayload.tokenVersionId, codePayload.userId);
+ if (!tokenSession) throw new UnauthorizedError({ message: "User session not found" });
+
+ const { accessTokenExpiresIn, refreshTokenExpiresIn } = await getTokenLifetimes(codePayload.orgId);
+
+ const sharedClaims = {
+ authMethod: codePayload.authMethod,
+ userId: codePayload.userId,
+ tokenVersionId: tokenSession.id,
+ organizationId: codePayload.orgId,
+ isMfaVerified: codePayload.isMfaVerified,
+ mfaMethod: codePayload.mfaMethod
+ };
+
+ const accessToken = signOauthAccessToken(
+ { ...sharedClaims, accessVersion: tokenSession.accessVersion },
+ accessTokenExpiresIn
+ );
+
+ const refreshToken = signOauthRefreshToken(
+ { ...sharedClaims, refreshVersion: tokenSession.refreshVersion, oauthClientId: client.clientId },
+ refreshTokenExpiresIn
+ );
+
+ return {
+ access_token: accessToken,
+ token_type: "Bearer" as const,
+ expires_in: expiresInToSeconds(accessTokenExpiresIn),
+ refresh_token: refreshToken,
+ scope: codePayload.scope ?? ""
+ };
+ }
+
+ const { decodedToken, tokenVersion, isGraceHit } = await tokenService.validateRefreshToken(dto.refreshToken);
+ const oauthDecodedToken = decodedToken as TOauthRefreshJwtTokenPayload;
+
+ if (oauthDecodedToken.oauthClientId !== client.clientId) {
+ throw new UnauthorizedError({ message: "Refresh token was not issued to this client" });
+ }
+
+ if (!decodedToken.organizationId) {
+ throw new UnauthorizedError({ message: "Invalid refresh token" });
+ }
+
+ const { accessTokenExpiresIn, refreshTokenExpiresIn } = await getTokenLifetimes(decodedToken.organizationId);
+
+ let { refreshToken } = dto;
+ let { refreshVersion } = tokenVersion;
+
+ const sharedClaims = {
+ authMethod: decodedToken.authMethod,
+ userId: decodedToken.userId,
+ tokenVersionId: tokenVersion.id,
+ organizationId: decodedToken.organizationId,
+ isMfaVerified: decodedToken.isMfaVerified,
+ mfaMethod: decodedToken.mfaMethod
+ };
+
+ if (!isGraceHit) {
+ const { updatedSession } = await tokenService.rotateRefreshToken(decodedToken, tokenVersion);
+ refreshVersion = updatedSession.refreshVersion;
+
+ refreshToken = signOauthRefreshToken(
+ { ...sharedClaims, refreshVersion, oauthClientId: client.clientId },
+ refreshTokenExpiresIn
+ );
+ }
+
+ const accessToken = signOauthAccessToken(
+ { ...sharedClaims, accessVersion: tokenVersion.accessVersion },
+ accessTokenExpiresIn
+ );
+
+ return {
+ access_token: accessToken,
+ token_type: "Bearer" as const,
+ expires_in: expiresInToSeconds(accessTokenExpiresIn),
+ refresh_token: refreshToken,
+ scope: ""
+ };
+ };
+
+ return {
+ createOauthClient,
+ listOauthClients,
+ getOauthClientById,
+ updateOauthClient,
+ deleteOauthClient,
+ rotateOauthClientSecret,
+ getAuthorizeInfo,
+ authorizeConsent,
+ exchangeToken
+ };
+};
diff --git a/backend/src/services/oauth-client/oauth-client-types.ts b/backend/src/services/oauth-client/oauth-client-types.ts
new file mode 100644
index 0000000000..c81934abe6
--- /dev/null
+++ b/backend/src/services/oauth-client/oauth-client-types.ts
@@ -0,0 +1,73 @@
+import { z } from "zod";
+
+import { AuthMethod, AuthModeRefreshJwtTokenPayload, MfaMethod } from "@app/services/auth/auth-type";
+
+export type TCreateOauthClientDTO = {
+ name: string;
+ description?: string;
+ redirectUris: string[];
+ requirePkce?: boolean;
+};
+
+export type TUpdateOauthClientDTO = {
+ clientDbId: string;
+ name?: string;
+ description?: string | null;
+ redirectUris?: string[];
+ requirePkce?: boolean;
+};
+
+export type TOauthAuthorizeInfoDTO = {
+ clientId: string;
+ redirectUri: string;
+};
+
+export type TOauthConsentDTO = {
+ clientId: string;
+ redirectUri: string;
+ state?: string;
+ codeChallenge?: string;
+ codeChallengeMethod?: "S256";
+ scope?: string;
+ userId: string;
+ authMethod: AuthMethod;
+ isMfaVerified?: boolean;
+ mfaMethod?: MfaMethod;
+ ip: string;
+};
+
+export type TOauthTokenExchangeDTO = {
+ clientId?: string;
+ clientSecret?: string;
+} & (
+ | {
+ grantType: "authorization_code";
+ code: string;
+ redirectUri?: string;
+ codeVerifier?: string;
+ }
+ | {
+ grantType: "refresh_token";
+ refreshToken: string;
+ }
+);
+
+export const OauthAuthorizationCodePayloadSchema = z.object({
+ clientId: z.string(),
+ orgId: z.string(),
+ userId: z.string(),
+ authMethod: z.nativeEnum(AuthMethod),
+ isMfaVerified: z.boolean().optional(),
+ mfaMethod: z.nativeEnum(MfaMethod).optional(),
+ tokenVersionId: z.string(),
+ redirectUri: z.string(),
+ codeChallenge: z.string().optional(),
+ codeChallengeMethod: z.literal("S256").optional(),
+ scope: z.string().optional()
+});
+
+export type TOauthAuthorizationCodePayload = z.infer<typeof OauthAuthorizationCodePayloadSchema>;
+
+export type TOauthRefreshJwtTokenPayload = AuthModeRefreshJwtTokenPayload & {
+ oauthClientId?: string;
+};
diff --git a/frontend/src/context/OrgPermissionContext/types.ts b/frontend/src/context/OrgPermissionContext/types.ts
index 6632e59cee..89228c9151 100644
--- a/frontend/src/context/OrgPermissionContext/types.ts
+++ b/frontend/src/context/OrgPermissionContext/types.ts
@@ -85,7 +85,8 @@ export enum OrgPermissionSubjects {
SubOrganization = "sub-organization",
EmailDomains = "email-domains",
CertManager = "certificate-manager",
- HoneyTokens = "honey-tokens"
+ HoneyTokens = "honey-tokens",
+ OauthClients = "oauth-clients"
}
export enum OrgPermissionCertManagerActions {
@@ -209,6 +210,7 @@ export type OrgPermissionSet =
| [OrgPermissionSubOrgActions, OrgPermissionSubjects.SubOrganization]
| [OrgPermissionEmailDomainActions, OrgPermissionSubjects.EmailDomains]
| [OrgPermissionCertManagerActions, OrgPermissionSubjects.CertManager]
- | [OrgPermissionHoneyTokenActions, OrgPermissionSubjects.HoneyTokens];
+ | [OrgPermissionHoneyTokenActions, OrgPermissionSubjects.HoneyTokens]
+ | [OrgPermissionActions, OrgPermissionSubjects.OauthClients];
export type TOrgPermission = MongoAbility<OrgPermissionSet>;
diff --git a/frontend/src/hooks/api/index.tsx b/frontend/src/hooks/api/index.tsx
index 135483edb7..3c1bece124 100644
--- a/frontend/src/hooks/api/index.tsx
+++ b/frontend/src/hooks/api/index.tsx
@@ -35,6 +35,7 @@ export * from "./integrations";
export * from "./kms";
export * from "./ldapConfig";
export * from "./mfaSession";
+export * from "./oauthClients";
export * from "./oidcConfig";
export * from "./orgAdmin";
export * from "./organization";
diff --git a/frontend/src/hooks/api/oauthClients/index.tsx b/frontend/src/hooks/api/oauthClients/index.tsx
new file mode 100644
index 0000000000..a25e07c847
--- /dev/null
+++ b/frontend/src/hooks/api/oauthClients/index.tsx
@@ -0,0 +1,9 @@
+export {
+ useCreateOauthClient,
+ useDeleteOauthClient,
+ useOauthConsent,
+ useRotateOauthClientSecret,
+ useUpdateOauthClient
+} from "./mutations";
+export { useGetOauthAuthorizeInfo, useGetOauthClients } from "./queries";
+export type { TOauthAuthorizeInfo, TOauthClient } from "./types";
diff --git a/frontend/src/hooks/api/oauthClients/mutations.tsx b/frontend/src/hooks/api/oauthClients/mutations.tsx
new file mode 100644
index 0000000000..335f399c5f
--- /dev/null
+++ b/frontend/src/hooks/api/oauthClients/mutations.tsx
@@ -0,0 +1,102 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+
+import { apiRequest } from "@app/config/request";
+
+import { oauthClientKeys } from "./queries";
+import {
+ TCreateOauthClientDTO,
+ TDeleteOauthClientDTO,
+ TOauthClient,
+ TOauthConsentDTO,
+ TRotateOauthClientSecretDTO,
+ TUpdateOauthClientDTO
+} from "./types";
+
+export const useCreateOauthClient = () => {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async (dto: TCreateOauthClientDTO) => {
+ const { data } = await apiRequest.post<{ client: TOauthClient; clientSecret: string }>(
+ "/api/v1/oauth/clients",
+ dto
+ );
+ return data;
+ },
+ onSuccess: ({ client }) => {
+ queryClient.invalidateQueries({
+ queryKey: oauthClientKeys.list(client.orgId)
+ });
+ }
+ });
+};
+
+export const useUpdateOauthClient = () => {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ clientDbId, ...dto }: TUpdateOauthClientDTO) => {
+ const { data } = await apiRequest.patch<{ client: TOauthClient }>(
+ `/api/v1/oauth/clients/${clientDbId}`,
+ dto
+ );
+ return data.client;
+ },
+ onSuccess: ({ orgId }) => {
+ queryClient.invalidateQueries({
+ queryKey: oauthClientKeys.list(orgId)
+ });
+ }
+ });
+};
+
+export const useDeleteOauthClient = () => {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ clientDbId }: TDeleteOauthClientDTO) => {
+ const { data } = await apiRequest.delete<{ client: TOauthClient }>(
+ `/api/v1/oauth/clients/${clientDbId}`
+ );
+ return data.client;
+ },
+ onSuccess: ({ orgId }) => {
+ queryClient.invalidateQueries({
+ queryKey: oauthClientKeys.list(orgId)
+ });
+ }
+ });
+};
+
+export const useRotateOauthClientSecret = () => {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ clientDbId }: TRotateOauthClientSecretDTO) => {
+ const { data } = await apiRequest.post<{ client: TOauthClient; clientSecret: string }>(
+ `/api/v1/oauth/clients/${clientDbId}/rotate-secret`
+ );
+ return data;
+ },
+ onSuccess: ({ client }) => {
+ queryClient.invalidateQueries({
+ queryKey: oauthClientKeys.list(client.orgId)
+ });
+ }
+ });
+};
+
+export const useOauthConsent = () => {
+ return useMutation({
+ mutationFn: async (dto: TOauthConsentDTO) => {
+ const { data } = await apiRequest.post<{ callbackUrl: string }>(
+ "/api/v1/oauth/authorize/consent",
+ {
+ client_id: dto.clientId,
+ redirect_uri: dto.redirectUri,
+ state: dto.state,
+ code_challenge: dto.codeChallenge,
+ code_challenge_method: dto.codeChallengeMethod,
+ scope: dto.scope
+ }
+ );
+ return data;
+ }
+ });
+};
diff --git a/frontend/src/hooks/api/oauthClients/queries.tsx b/frontend/src/hooks/api/oauthClients/queries.tsx
new file mode 100644
index 0000000000..ca8697e358
--- /dev/null
+++ b/frontend/src/hooks/api/oauthClients/queries.tsx
@@ -0,0 +1,40 @@
+import { useQuery } from "@tanstack/react-query";
+
+import { apiRequest } from "@app/config/request";
+
+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,
+ all: ["oauth-clients"] as const
+};
+
+export const useGetOauthClients = (orgId: string) => {
+ return useQuery({
+ queryKey: oauthClientKeys.list(orgId),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<{ clients: TOauthClient[] }>("/api/v1/oauth/clients");
+ return data.clients;
+ },
+ enabled: Boolean(orgId)
+ });
+};
+
+export const useGetOauthAuthorizeInfo = (clientId: string, redirectUri: string) => {
+ return useQuery({
+ queryKey: oauthClientKeys.authorizeInfo(clientId, redirectUri),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<TOauthAuthorizeInfo>("/api/v1/oauth/authorize/info", {
+ params: {
+ client_id: clientId,
+ redirect_uri: redirectUri
+ }
+ });
+ return data;
+ },
+ enabled: Boolean(clientId) && Boolean(redirectUri),
+ retry: false
+ });
+};
diff --git a/frontend/src/hooks/api/oauthClients/types.ts b/frontend/src/hooks/api/oauthClients/types.ts
new file mode 100644
index 0000000000..a29fe1775c
--- /dev/null
+++ b/frontend/src/hooks/api/oauthClients/types.ts
@@ -0,0 +1,50 @@
+export type TOauthClient = {
+ id: string;
+ orgId: string;
+ name: string;
+ description?: string | null;
+ clientId: string;
+ clientSecretPrefix: string;
+ redirectUris: string[];
+ requirePkce: boolean;
+ createdAt: string;
+ updatedAt: string;
+};
+
+export type TCreateOauthClientDTO = {
+ name: string;
+ description?: string;
+ redirectUris: string[];
+ requirePkce?: boolean;
+};
+
+export type TUpdateOauthClientDTO = {
+ clientDbId: string;
+ name?: string;
+ description?: string | null;
+ redirectUris?: string[];
+ requirePkce?: boolean;
+};
+
+export type TDeleteOauthClientDTO = {
+ clientDbId: string;
+};
+
+export type TRotateOauthClientSecretDTO = {
+ clientDbId: string;
+};
+
+export type TOauthAuthorizeInfo = {
+ clientName: string;
+ clientDescription?: string | null;
+ requirePkce: boolean;
+};
+
+export type TOauthConsentDTO = {
+ clientId: string;
+ redirectUri: string;
+ state?: string;
+ codeChallenge?: string;
+ codeChallengeMethod?: string;
+ scope?: string;
+};
diff --git a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/submenus.ts b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/submenus.ts
index 48ab071b70..6e2a7a8640 100644
--- a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/submenus.ts
+++ b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/submenus.ts
@@ -16,6 +16,7 @@ import {
HardDrive,
IdCardLanyard,
Key,
+ KeyRound,
Lock,
MapPin,
Plug,
@@ -152,6 +153,7 @@ export const getOrgSettingsSubmenu = ({
{ label: "Encryption", icon: Lock, tab: "tab-org-encryption" },
{ label: "Workflow Integrations", icon: Plug, tab: "workflow-integrations" },
{ label: "Audit Log Streams", icon: FileText, tab: "tag-audit-log-streams" },
+ { label: "OAuth Applications", icon: KeyRound, tab: "oauth-applications" },
{ label: "External Migrations", icon: Database, tab: "tab-external-migrations" },
{ label: "Project Templates", icon: FolderCog, tab: "project-templates" },
{ label: "Product Settings", icon: ClipboardList, tab: "product-settings" },
diff --git a/frontend/src/pages/organization/OauthConsentPage/OauthConsentPage.tsx b/frontend/src/pages/organization/OauthConsentPage/OauthConsentPage.tsx
new file mode 100644
index 0000000000..87a2a86384
--- /dev/null
+++ b/frontend/src/pages/organization/OauthConsentPage/OauthConsentPage.tsx
@@ -0,0 +1,171 @@
+import { useState } from "react";
+import { Helmet } from "react-helmet";
+import { Link, useSearch } from "@tanstack/react-router";
+import { CheckCircle2, Loader2 } from "lucide-react";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ Alert,
+ AlertDescription,
+ Button,
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ Skeleton
+} from "@app/components/v3";
+import { useGetOauthAuthorizeInfo, useOauthConsent } from "@app/hooks/api";
+
+export const OauthConsentPage = () => {
+ const [isRedirecting, setIsRedirecting] = useState(false);
+
+ const search = useSearch({
+ from: "/_authenticate/organization/oauth-consent"
+ });
+
+ const {
+ data: authorizeInfo,
+ isPending: isInfoPending,
+ error: authorizeInfoError
+ } = useGetOauthAuthorizeInfo(search.client_id, search.redirect_uri);
+
+ const { mutateAsync: consentOauth, isPending: isConsenting } = useOauthConsent();
+
+ // The backend validates client + redirect URI when fetching authorize info. Until that
+ // succeeds we must not trust the redirect_uri from the URL (otherwise Deny is an open redirect).
+ const isRequestValidated = !isInfoPending && Boolean(authorizeInfo) && !authorizeInfoError;
+
+ // This client requires PKCE but the request did not include a code_challenge. Surface it
+ // before the user consents instead of failing the authorize call afterwards.
+ const isPkceMissing = Boolean(authorizeInfo?.requirePkce) && !search.code_challenge;
+
+ const handleAuthorize = async () => {
+ try {
+ const { callbackUrl } = await consentOauth({
+ clientId: search.client_id,
+ redirectUri: search.redirect_uri,
+ state: search.state,
+ codeChallenge: search.code_challenge,
+ codeChallengeMethod: search.code_challenge_method,
+ scope: search.scope
+ });
+
+ setIsRedirecting(true);
+ window.location.href = callbackUrl;
+ } catch (error) {
+ const axiosError = error as { response?: { data?: { message?: string } } };
+ createNotification({
+ text: axiosError?.response?.data?.message || "Failed to authorize application",
+ type: "error"
+ });
+ }
+ };
+
+ const handleDeny = () => {
+ // Only redirect once the backend has confirmed the redirect_uri is registered for this client
+ if (!isRequestValidated) return;
+
+ const denyUrl = new URL(search.redirect_uri);
+ denyUrl.searchParams.set("error", "access_denied");
+ if (search.state) denyUrl.searchParams.set("state", search.state);
+ window.location.href = denyUrl.toString();
+ };
+
+ if (isRedirecting) {
+ return (
+ <div className="flex min-h-screen flex-col items-center justify-center bg-bunker-800">
+ <Card className="w-full max-w-md items-center text-center">
+ <div className="flex size-16 items-center justify-center rounded-full bg-success/10">
+ <CheckCircle2 className="size-8 text-success" />
+ </div>
+ <CardTitle className="justify-center">Authorization Successful</CardTitle>
+ <CardDescription className="flex items-center justify-center gap-2">
+ <Loader2 className="size-3.5 animate-spin" />
+ Redirecting back to the application
+ </CardDescription>
+ </Card>
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex min-h-screen flex-col items-center justify-center bg-bunker-800">
+ <Helmet>
+ <title>Authorize Application</title>
+ <link rel="icon" href="/infisical.ico" />
+ </Helmet>
+
+ <Card className="w-full max-w-md">
+ <Link to="/" className="block">
+ <img src="/images/gradientLogo.svg" className="mx-auto h-16" alt="Infisical logo" />
+ </Link>
+
+ <CardHeader className="text-center">
+ <CardTitle className="justify-center">Authorize Application</CardTitle>
+ <CardDescription>
+ An external application is requesting access to your Infisical account.
+ </CardDescription>
+ </CardHeader>
+
+ <CardContent className="flex flex-col gap-6">
+ {isInfoPending && (
+ <div className="flex flex-col gap-2 rounded-md border border-border bg-container p-4">
+ <Skeleton className="h-4 w-1/3" />
+ <Skeleton className="h-3 w-2/3" />
+ </div>
+ )}
+ {!isInfoPending && authorizeInfo && (
+ <div className="rounded-md border border-border bg-container p-4">
+ <p className="text-xs text-accent">Application</p>
+ <p className="mt-1 font-medium text-foreground">{authorizeInfo.clientName}</p>
+ {authorizeInfo.clientDescription && (
+ <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.
+ </p>
+ </div>
+ )}
+ {!isInfoPending && authorizeInfoError && (
+ <Alert variant="danger">
+ <AlertDescription>
+ {(authorizeInfoError as { response?: { data?: { message?: string } } })?.response
+ ?.data?.message || "This authorization request is invalid."}
+ </AlertDescription>
+ </Alert>
+ )}
+ {isRequestValidated && isPkceMissing && (
+ <Alert variant="danger">
+ <AlertDescription>
+ This application requires PKCE, but the authorization request is missing a code
+ challenge. The application must initiate the request with PKCE enabled.
+ </AlertDescription>
+ </Alert>
+ )}
+
+ <div className="flex gap-3">
+ <Button
+ variant="outline"
+ isFullWidth
+ onClick={handleDeny}
+ isDisabled={isConsenting || !isRequestValidated}
+ >
+ Deny
+ </Button>
+ <Button
+ variant="org"
+ isFullWidth
+ onClick={handleAuthorize}
+ isPending={isConsenting}
+ isDisabled={isConsenting || !isRequestValidated || isPkceMissing}
+ >
+ Authorize
+ </Button>
+ </div>
+ </CardContent>
+ </Card>
+ </div>
+ );
+};
diff --git a/frontend/src/pages/organization/OauthConsentPage/route.tsx b/frontend/src/pages/organization/OauthConsentPage/route.tsx
new file mode 100644
index 0000000000..89240c2747
--- /dev/null
+++ b/frontend/src/pages/organization/OauthConsentPage/route.tsx
@@ -0,0 +1,20 @@
+import { createFileRoute } from "@tanstack/react-router";
+import { zodValidator } from "@tanstack/zod-adapter";
+import { z } from "zod";
+
+import { OauthConsentPage } from "./OauthConsentPage";
+
+const OauthConsentPageQuerySchema = z.object({
+ response_type: z.string(),
+ client_id: z.string(),
+ redirect_uri: z.string(),
+ state: z.string().optional(),
+ code_challenge: z.string().optional(),
+ code_challenge_method: z.string().optional(),
+ scope: z.string().optional()
+});
+
+export const Route = createFileRoute("/_authenticate/organization/oauth-consent")({
+ component: OauthConsentPage,
+ validateSearch: zodValidator(OauthConsentPageQuerySchema)
+});
diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgOauthClientsTab/OauthClientModal.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgOauthClientsTab/OauthClientModal.tsx
new file mode 100644
index 0000000000..ef19d67863
--- /dev/null
+++ b/frontend/src/pages/organization/SettingsPage/components/OrgOauthClientsTab/OauthClientModal.tsx
@@ -0,0 +1,258 @@
+import { useEffect } from "react";
+import { Controller, useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { z } from "zod";
+
+import { createNotification } from "@app/components/notifications";
+import {
+ Button,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldLabel,
+ FieldTitle,
+ Input,
+ Switch,
+ TextArea
+} from "@app/components/v3";
+import { TOauthClient, useCreateOauthClient, useUpdateOauthClient } from "@app/hooks/api";
+import { UsePopUpState } from "@app/hooks/usePopUp";
+
+const isValidRedirectUri = (uri: string) => {
+ try {
+ const parsed = new URL(uri);
+ return parsed.protocol === "https:" || parsed.protocol === "http:";
+ } catch {
+ return false;
+ }
+};
+
+const oauthClientFormSchema = z.object({
+ name: z.string().trim().min(1, "Name is required").max(64),
+ description: z.string().trim().max(256).optional(),
+ redirectUris: z
+ .string()
+ .trim()
+ .min(1, "At least one redirect URI is required")
+ .superRefine((value, ctx) => {
+ const uris = value
+ .split("\n")
+ .map((uri) => uri.trim())
+ .filter(Boolean);
+ const invalidUri = uris.find((uri) => !isValidRedirectUri(uri));
+ if (invalidUri) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: `Invalid redirect URI: ${invalidUri}`
+ });
+ }
+ }),
+ requirePkce: z.boolean()
+});
+
+type TOauthClientForm = z.infer<typeof oauthClientFormSchema>;
+
+type Props = {
+ popUp: UsePopUpState<["clientForm"]>;
+ handlePopUpClose: (popUpName: keyof UsePopUpState<["clientForm"]>) => void;
+ handlePopUpToggle: (popUpName: keyof UsePopUpState<["clientForm"]>, state?: boolean) => void;
+ onCreated?: (client: TOauthClient, clientSecret: string) => void;
+};
+
+export const OauthClientModal = ({
+ popUp,
+ handlePopUpClose,
+ handlePopUpToggle,
+ onCreated
+}: Props) => {
+ const editingClient = popUp?.clientForm?.data as TOauthClient | undefined;
+ const isEditing = Boolean(editingClient);
+
+ const { control, handleSubmit, reset } = useForm<TOauthClientForm>({
+ resolver: zodResolver(oauthClientFormSchema),
+ defaultValues: {
+ name: "",
+ description: "",
+ redirectUris: "",
+ requirePkce: false
+ }
+ });
+
+ useEffect(() => {
+ if (popUp?.clientForm?.isOpen) {
+ reset({
+ name: editingClient?.name ?? "",
+ description: editingClient?.description ?? "",
+ redirectUris: editingClient?.redirectUris?.join("\n") ?? "",
+ requirePkce: editingClient?.requirePkce ?? false
+ });
+ }
+ }, [popUp?.clientForm?.isOpen]);
+
+ const { mutateAsync: createOauthClient, isPending: isCreating } = useCreateOauthClient();
+ const { mutateAsync: updateOauthClient, isPending: isUpdating } = useUpdateOauthClient();
+
+ const onFormSubmit = async ({
+ name,
+ description,
+ redirectUris,
+ requirePkce
+ }: TOauthClientForm) => {
+ const parsedRedirectUris = redirectUris
+ .split("\n")
+ .map((uri) => uri.trim())
+ .filter(Boolean);
+
+ try {
+ if (isEditing && editingClient) {
+ await updateOauthClient({
+ clientDbId: editingClient.id,
+ name,
+ description: description || null,
+ redirectUris: parsedRedirectUris,
+ requirePkce
+ });
+ createNotification({
+ text: "Successfully updated OAuth application",
+ type: "success"
+ });
+ } else {
+ const { client, clientSecret } = await createOauthClient({
+ name,
+ description: description || undefined,
+ redirectUris: parsedRedirectUris,
+ requirePkce
+ });
+ createNotification({
+ text: "Successfully created OAuth application",
+ type: "success"
+ });
+ onCreated?.(client, clientSecret);
+ }
+ handlePopUpClose("clientForm");
+ reset();
+ } catch (error) {
+ createNotification({
+ text:
+ (error as Error)?.message ||
+ `Failed to ${isEditing ? "update" : "create"} OAuth application`,
+ type: "error"
+ });
+ }
+ };
+
+ return (
+ <Dialog
+ open={popUp?.clientForm?.isOpen}
+ onOpenChange={(isOpen) => {
+ handlePopUpToggle("clientForm", isOpen);
+ reset();
+ }}
+ >
+ <DialogContent className="sm:max-w-lg">
+ <DialogHeader>
+ <DialogTitle>
+ {isEditing ? "Edit OAuth application" : "Add OAuth application"}
+ </DialogTitle>
+ <DialogDescription>
+ External platforms can use this application to sign users in with their Infisical
+ identity via OAuth 2.0.
+ </DialogDescription>
+ </DialogHeader>
+ <form onSubmit={handleSubmit(onFormSubmit)} className="flex flex-col gap-6">
+ <Controller
+ control={control}
+ name="name"
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel htmlFor="oauth-client-name">Name</FieldLabel>
+ <Input
+ id="oauth-client-name"
+ placeholder="e.g. Coder"
+ isError={Boolean(error)}
+ {...field}
+ />
+ <FieldError>{error?.message}</FieldError>
+ </Field>
+ )}
+ />
+ <Controller
+ control={control}
+ name="description"
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel htmlFor="oauth-client-description">Description (optional)</FieldLabel>
+ <Input
+ id="oauth-client-description"
+ placeholder="What this application is used for"
+ isError={Boolean(error)}
+ {...field}
+ />
+ <FieldError>{error?.message}</FieldError>
+ </Field>
+ )}
+ />
+ <Controller
+ control={control}
+ name="redirectUris"
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel htmlFor="oauth-client-redirect-uris">Redirect URIs</FieldLabel>
+ <TextArea
+ id="oauth-client-redirect-uris"
+ placeholder="https://coder.example.com/external-auth/infisical/callback"
+ rows={3}
+ {...field}
+ />
+ <FieldDescription>
+ One URI per line. The authorization flow only redirects to these exact URIs.
+ </FieldDescription>
+ <FieldError>{error?.message}</FieldError>
+ </Field>
+ )}
+ />
+ <Controller
+ control={control}
+ name="requirePkce"
+ render={({ field: { value, onChange } }) => (
+ <Field orientation="horizontal">
+ <FieldContent>
+ <FieldTitle>Require PKCE (S256)</FieldTitle>
+ <FieldDescription>
+ Reject authorization requests that do not include a PKCE code challenge.
+ </FieldDescription>
+ </FieldContent>
+ <Switch
+ id="oauth-client-require-pkce"
+ variant="org"
+ checked={value}
+ onCheckedChange={onChange}
+ />
+ </Field>
+ )}
+ />
+ <DialogFooter>
+ <Button variant="ghost" type="button" onClick={() => handlePopUpClose("clientForm")}>
+ Cancel
+ </Button>
+ <Button
+ variant="org"
+ type="submit"
+ isPending={isCreating || isUpdating}
+ isDisabled={isCreating || isUpdating}
+ >
+ {isEditing ? "Save Changes" : "Create Application"}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgOauthClientsTab/OauthClientSecretModal.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgOauthClientsTab/OauthClientSecretModal.tsx
new file mode 100644
index 0000000000..441f73ff8b
--- /dev/null
+++ b/frontend/src/pages/organization/SettingsPage/components/OrgOauthClientsTab/OauthClientSecretModal.tsx
@@ -0,0 +1,90 @@
+import { Check, Copy } from "lucide-react";
+
+import {
+ Alert,
+ AlertDescription,
+ Button,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ IconButton
+} from "@app/components/v3";
+import { useTimedReset } from "@app/hooks";
+import { UsePopUpState } from "@app/hooks/usePopUp";
+
+export type TOauthClientSecretData = {
+ clientName: string;
+ clientId: string;
+ clientSecret: string;
+};
+
+type Props = {
+ popUp: UsePopUpState<["clientSecret"]>;
+ handlePopUpClose: (popUpName: keyof UsePopUpState<["clientSecret"]>) => void;
+ handlePopUpToggle: (popUpName: keyof UsePopUpState<["clientSecret"]>, state?: boolean) => void;
+};
+
+const CopyableValue = ({ label, value }: { label: string; value: string }) => {
+ const [, isCopying, setCopyText] = useTimedReset<string>({
+ initialState: "Copy to clipboard"
+ });
+
+ return (
+ <div className="flex flex-col gap-1">
+ <span className="text-xs text-accent">{label}</span>
+ <div className="flex items-center gap-2 rounded-md border border-border bg-container p-2">
+ <p className="grow font-mono text-sm break-all text-foreground">{value}</p>
+ <IconButton
+ variant="ghost"
+ size="xs"
+ aria-label={`Copy ${label}`}
+ onClick={() => {
+ navigator.clipboard.writeText(value);
+ setCopyText("Copied");
+ }}
+ >
+ {isCopying ? <Check /> : <Copy />}
+ </IconButton>
+ </div>
+ </div>
+ );
+};
+
+export const OauthClientSecretModal = ({ popUp, handlePopUpClose, handlePopUpToggle }: Props) => {
+ const data = popUp?.clientSecret?.data as TOauthClientSecretData | undefined;
+
+ return (
+ <Dialog
+ open={popUp?.clientSecret?.isOpen}
+ onOpenChange={(isOpen) => handlePopUpToggle("clientSecret", isOpen)}
+ >
+ <DialogContent className="sm:max-w-lg">
+ <DialogHeader>
+ <DialogTitle>OAuth client credentials</DialogTitle>
+ <DialogDescription>
+ Use these credentials to register {data?.clientName || "this application"} as an OAuth
+ provider on the external platform.
+ </DialogDescription>
+ </DialogHeader>
+ <div className="flex flex-col gap-4">
+ <Alert variant="warning">
+ <AlertDescription>
+ The client secret is only shown once. Store it securely — you will not be able to
+ retrieve it again, only rotate it.
+ </AlertDescription>
+ </Alert>
+ <CopyableValue label="Client ID" value={data?.clientId ?? ""} />
+ <CopyableValue label="Client Secret" value={data?.clientSecret ?? ""} />
+ </div>
+ <DialogFooter>
+ <Button variant="org" type="button" onClick={() => handlePopUpClose("clientSecret")}>
+ Done
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgOauthClientsTab/OrgOauthClientsTab.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgOauthClientsTab/OrgOauthClientsTab.tsx
new file mode 100644
index 0000000000..b474ca5ff7
--- /dev/null
+++ b/frontend/src/pages/organization/SettingsPage/components/OrgOauthClientsTab/OrgOauthClientsTab.tsx
@@ -0,0 +1,399 @@
+import { useState } from "react";
+import { format } from "date-fns";
+import {
+ Check,
+ Copy,
+ KeyRound,
+ MoreHorizontal,
+ Pencil,
+ Plus,
+ RefreshCw,
+ Search,
+ Trash2
+} from "lucide-react";
+
+import { createNotification } from "@app/components/notifications";
+import { OrgPermissionCan, PermissionDeniedBanner } from "@app/components/permissions";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogMedia,
+ AlertDialogTitle,
+ Badge,
+ Button,
+ Card,
+ CardAction,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ Empty,
+ EmptyDescription,
+ EmptyHeader,
+ EmptyTitle,
+ IconButton,
+ InputGroup,
+ InputGroupAddon,
+ InputGroupInput,
+ Skeleton,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow
+} from "@app/components/v3";
+import {
+ OrgPermissionActions,
+ OrgPermissionSubjects,
+ useOrganization,
+ useOrgPermission
+} from "@app/context";
+import { usePopUp, useTimedReset } from "@app/hooks";
+import {
+ TOauthClient,
+ useDeleteOauthClient,
+ useGetOauthClients,
+ useRotateOauthClientSecret
+} from "@app/hooks/api";
+
+import { OauthClientModal } from "./OauthClientModal";
+import { OauthClientSecretModal } from "./OauthClientSecretModal";
+
+const ClientIdCell = ({ clientId }: { clientId: string }) => {
+ const [, isCopying, setCopyText] = useTimedReset<string>({
+ initialState: "Copy to clipboard"
+ });
+
+ return (
+ <div className="flex items-center gap-1">
+ <span className="font-mono text-xs">{clientId}</span>
+ <IconButton
+ variant="ghost"
+ size="xs"
+ aria-label="Copy client ID"
+ onClick={() => {
+ navigator.clipboard.writeText(clientId);
+ setCopyText("Copied");
+ }}
+ >
+ {isCopying ? <Check /> : <Copy />}
+ </IconButton>
+ </div>
+ );
+};
+
+export const OrgOauthClientsTab = () => {
+ const { currentOrg } = useOrganization();
+ const { permission } = useOrgPermission();
+ const { data: oauthClients, isPending } = useGetOauthClients(currentOrg?.id ?? "");
+ const [search, setSearch] = useState("");
+
+ const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([
+ "clientForm",
+ "clientSecret",
+ "deleteClient",
+ "rotateSecret"
+ ] as const);
+
+ const { mutateAsync: deleteOauthClient } = useDeleteOauthClient();
+ const { mutateAsync: rotateOauthClientSecret } = useRotateOauthClientSecret();
+
+ const onDeleteClient = async () => {
+ const client = popUp?.deleteClient?.data as TOauthClient | undefined;
+ if (!client) return;
+
+ try {
+ await deleteOauthClient({ clientDbId: client.id });
+ createNotification({
+ text: "Successfully deleted OAuth application",
+ type: "success"
+ });
+ handlePopUpClose("deleteClient");
+ } catch (error) {
+ createNotification({
+ text: (error as Error)?.message || "Failed to delete OAuth application",
+ type: "error"
+ });
+ }
+ };
+
+ const onRotateSecret = async () => {
+ const client = popUp?.rotateSecret?.data as TOauthClient | undefined;
+ if (!client) return;
+
+ try {
+ const { client: updatedClient, clientSecret } = await rotateOauthClientSecret({
+ clientDbId: client.id
+ });
+ handlePopUpClose("rotateSecret");
+ handlePopUpOpen("clientSecret", {
+ clientName: updatedClient.name,
+ clientId: updatedClient.clientId,
+ clientSecret
+ });
+ createNotification({
+ text: "Successfully rotated client secret",
+ type: "success"
+ });
+ } catch (error) {
+ createNotification({
+ text: (error as Error)?.message || "Failed to rotate client secret",
+ type: "error"
+ });
+ }
+ };
+
+ const filteredClients = (oauthClients ?? []).filter(({ name }) =>
+ name.toLowerCase().includes(search.toLowerCase())
+ );
+
+ const canRead = permission.can(OrgPermissionActions.Read, OrgPermissionSubjects.OauthClients);
+
+ return (
+ <>
+ <Card>
+ <CardHeader>
+ <CardTitle>
+ <KeyRound className="size-4 text-accent" />
+ OAuth Applications
+ </CardTitle>
+ <CardDescription>
+ Register external platforms that sign users in with their Infisical identity via OAuth
+ 2.0.
+ </CardDescription>
+ <CardAction>
+ <OrgPermissionCan
+ I={OrgPermissionActions.Create}
+ a={OrgPermissionSubjects.OauthClients}
+ >
+ {(isAllowed) => (
+ <Button
+ variant="outline"
+ isDisabled={!isAllowed}
+ onClick={() => handlePopUpOpen("clientForm")}
+ >
+ <Plus />
+ Add Application
+ </Button>
+ )}
+ </OrgPermissionCan>
+ </CardAction>
+ </CardHeader>
+ <CardContent>
+ {!canRead ? (
+ <PermissionDeniedBanner />
+ ) : (
+ <div className="flex flex-col gap-4">
+ <InputGroup>
+ <InputGroupAddon>
+ <Search />
+ </InputGroupAddon>
+ <InputGroupInput
+ placeholder="Search applications"
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ />
+ </InputGroup>
+ {!isPending && filteredClients.length === 0 ? (
+ <Empty className="border">
+ <EmptyHeader>
+ <EmptyTitle>No OAuth applications found</EmptyTitle>
+ <EmptyDescription>
+ Add an application to let an external platform authenticate users via
+ Infisical.
+ </EmptyDescription>
+ </EmptyHeader>
+ </Empty>
+ ) : (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Name</TableHead>
+ <TableHead>Client ID</TableHead>
+ <TableHead>Redirect URIs</TableHead>
+ <TableHead>PKCE</TableHead>
+ <TableHead>Created</TableHead>
+ <TableHead className="w-px text-right" aria-label="Actions" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {isPending &&
+ Array.from({ length: 3 }).map((_, idx) => (
+ // eslint-disable-next-line react/no-array-index-key
+ <TableRow key={`oauth-client-skeleton-${idx}`}>
+ <TableCell colSpan={6}>
+ <Skeleton className="h-5 w-full" />
+ </TableCell>
+ </TableRow>
+ ))}
+ {filteredClients.map((client) => (
+ <TableRow key={client.id}>
+ <TableCell className="font-medium text-foreground">{client.name}</TableCell>
+ <TableCell>
+ <ClientIdCell clientId={client.clientId} />
+ </TableCell>
+ <TableCell>
+ <div className="flex flex-col gap-0.5">
+ {client.redirectUris.map((uri) => (
+ <span key={uri} className="font-mono text-xs break-all">
+ {uri}
+ </span>
+ ))}
+ </div>
+ </TableCell>
+ <TableCell>
+ {client.requirePkce ? (
+ <Badge variant="success">Required</Badge>
+ ) : (
+ <span className="text-muted">Optional</span>
+ )}
+ </TableCell>
+ <TableCell>{format(new Date(client.createdAt), "MMM d, yyyy")}</TableCell>
+ <TableCell className="text-right">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ variant="ghost"
+ size="xs"
+ aria-label={`Actions for ${client.name}`}
+ >
+ <MoreHorizontal />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-44">
+ <OrgPermissionCan
+ I={OrgPermissionActions.Edit}
+ a={OrgPermissionSubjects.OauthClients}
+ >
+ {(isAllowed) => (
+ <DropdownMenuItem
+ isDisabled={!isAllowed}
+ onClick={() => handlePopUpOpen("clientForm", client)}
+ >
+ <Pencil />
+ Edit
+ </DropdownMenuItem>
+ )}
+ </OrgPermissionCan>
+ <OrgPermissionCan
+ I={OrgPermissionActions.Edit}
+ a={OrgPermissionSubjects.OauthClients}
+ >
+ {(isAllowed) => (
+ <DropdownMenuItem
+ isDisabled={!isAllowed}
+ onClick={() => handlePopUpOpen("rotateSecret", client)}
+ >
+ <RefreshCw />
+ Rotate Secret
+ </DropdownMenuItem>
+ )}
+ </OrgPermissionCan>
+ <OrgPermissionCan
+ I={OrgPermissionActions.Delete}
+ a={OrgPermissionSubjects.OauthClients}
+ >
+ {(isAllowed) => (
+ <DropdownMenuItem
+ variant="danger"
+ isDisabled={!isAllowed}
+ onClick={() => handlePopUpOpen("deleteClient", client)}
+ >
+ <Trash2 />
+ Delete
+ </DropdownMenuItem>
+ )}
+ </OrgPermissionCan>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ )}
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ <OauthClientModal
+ popUp={popUp}
+ handlePopUpClose={handlePopUpClose}
+ handlePopUpToggle={handlePopUpToggle}
+ onCreated={(client, clientSecret) =>
+ handlePopUpOpen("clientSecret", {
+ clientName: client.name,
+ clientId: client.clientId,
+ clientSecret
+ })
+ }
+ />
+ <OauthClientSecretModal
+ popUp={popUp}
+ handlePopUpClose={handlePopUpClose}
+ handlePopUpToggle={handlePopUpToggle}
+ />
+ <AlertDialog
+ open={popUp.deleteClient.isOpen}
+ onOpenChange={(isOpen) => handlePopUpToggle("deleteClient", isOpen)}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogMedia>
+ <Trash2 />
+ </AlertDialogMedia>
+ <AlertDialogTitle>
+ Delete &quot;{(popUp?.deleteClient?.data as TOauthClient | undefined)?.name}&quot;?
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ External platforms using this application will no longer be able to authenticate users
+ or refresh tokens.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction variant="danger" onClick={onDeleteClient}>
+ Delete
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ <AlertDialog
+ open={popUp.rotateSecret.isOpen}
+ onOpenChange={(isOpen) => handlePopUpToggle("rotateSecret", isOpen)}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogMedia>
+ <RefreshCw />
+ </AlertDialogMedia>
+ <AlertDialogTitle>
+ Rotate secret for &quot;
+ {(popUp?.rotateSecret?.data as TOauthClient | undefined)?.name}&quot;?
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ The current client secret stops working immediately. You will need to update the
+ external platform with the new secret.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction variant="danger" onClick={onRotateSecret}>
+ Rotate Secret
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
+ );
+};
diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgOauthClientsTab/index.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgOauthClientsTab/index.tsx
new file mode 100644
index 0000000000..a2dca9e194
--- /dev/null
+++ b/frontend/src/pages/organization/SettingsPage/components/OrgOauthClientsTab/index.tsx
@@ -0,0 +1 @@
+export { OrgOauthClientsTab } from "./OrgOauthClientsTab";
diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgTabGroup/OrgTabGroup.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgTabGroup/OrgTabGroup.tsx
index bdf79ee996..dc1cb1a7a3 100644
--- a/frontend/src/pages/organization/SettingsPage/components/OrgTabGroup/OrgTabGroup.tsx
+++ b/frontend/src/pages/organization/SettingsPage/components/OrgTabGroup/OrgTabGroup.tsx
@@ -10,6 +10,7 @@ import { AuditLogStreamsTab } from "../AuditLogStreamTab";
import { ExternalMigrationsTab } from "../ExternalMigrationsTab";
import { OrgEncryptionTab } from "../OrgEncryptionTab";
import { OrgGeneralTab } from "../OrgGeneralTab";
+import { OrgOauthClientsTab } from "../OrgOauthClientsTab";
import { OrgProductSettingsTab } from "../OrgProductSettingsTab";
import { OrgProvisioningTab } from "../OrgProvisioningTab";
import { OrgSecurityTab } from "../OrgSecurityTab";
@@ -58,6 +59,11 @@ export const OrgTabGroup = () => {
component: OrgWorkflowIntegrationTab
},
{ name: "Audit Log Streams", key: "tag-audit-log-streams", component: AuditLogStreamsTab },
+ {
+ name: "OAuth Applications",
+ key: "oauth-applications",
+ component: OrgOauthClientsTab
+ },
{
name: "External Migrations",
key: "tab-external-migrations",
diff --git a/frontend/src/routeTree.gen.ts b/frontend/src/routeTree.gen.ts
index 7ed310f6bb..9df154c86f 100644
--- a/frontend/src/routeTree.gen.ts
+++ b/frontend/src/routeTree.gen.ts
@@ -35,6 +35,7 @@ import { Route as authLoginLdapPageRouteImport } from './pages/auth/LoginLdapPag
import { Route as authAdminLoginPageRouteImport } from './pages/auth/AdminLoginPage/route'
import { Route as adminSignUpPageRouteImport } from './pages/admin/SignUpPage/route'
import { Route as organizationNoOrgPageRouteImport } from './pages/organization/NoOrgPage/route'
+import { Route as organizationOauthConsentPageRouteImport } from './pages/organization/OauthConsentPage/route'
import { Route as organizationMcpEndpointFinalizePageRouteImport } from './pages/organization/McpEndpointFinalizePage/route'
import { Route as MfaSessionPageRouteImport } from './pages/MfaSessionPage/route'
import { Route as authSignUpPageRouteImport } from './pages/auth/SignUpPage/route'
@@ -600,6 +601,13 @@ const organizationNoOrgPageRouteRoute = organizationNoOrgPageRouteImport.update(
} as any,
)
+const organizationOauthConsentPageRouteRoute =
+ organizationOauthConsentPageRouteImport.update({
+ id: '/organization/oauth-consent',
+ path: '/organization/oauth-consent',
+ getParentRoute: () => middlewaresAuthenticateRoute,
+ } as any)
+
const organizationMcpEndpointFinalizePageRouteRoute =
organizationMcpEndpointFinalizePageRouteImport.update({
id: '/organization/mcp-endpoint-finalize',
@@ -2878,6 +2886,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof organizationMcpEndpointFinalizePageRouteImport
parentRoute: typeof middlewaresAuthenticateImport
}
+ '/_authenticate/organization/oauth-consent': {
+ id: '/_authenticate/organization/oauth-consent'
+ path: '/organization/oauth-consent'
+ fullPath: '/organization/oauth-consent'
+ preLoaderRoute: typeof organizationOauthConsentPageRouteImport
+ parentRoute: typeof middlewaresAuthenticateImport
+ }
'/_authenticate/organizations/none': {
id: '/_authenticate/organizations/none'
path: '/organizations/none'
@@ -6201,6 +6216,7 @@ interface middlewaresAuthenticateRouteChildren {
AuthenticatePersonalSettingsRoute: typeof AuthenticatePersonalSettingsRouteWithChildren
MfaSessionPageRouteRoute: typeof MfaSessionPageRouteRoute
organizationMcpEndpointFinalizePageRouteRoute: typeof organizationMcpEndpointFinalizePageRouteRoute
+ organizationOauthConsentPageRouteRoute: typeof organizationOauthConsentPageRouteRoute
organizationNoOrgPageRouteRoute: typeof organizationNoOrgPageRouteRoute
}
@@ -6214,6 +6230,8 @@ const middlewaresAuthenticateRouteChildren: middlewaresAuthenticateRouteChildren
MfaSessionPageRouteRoute: MfaSessionPageRouteRoute,
organizationMcpEndpointFinalizePageRouteRoute:
organizationMcpEndpointFinalizePageRouteRoute,
+ organizationOauthConsentPageRouteRoute:
+ organizationOauthConsentPageRouteRoute,
organizationNoOrgPageRouteRoute: organizationNoOrgPageRouteRoute,
}
@@ -6308,6 +6326,7 @@ export interface FileRoutesByFullPath {
'/signup/': typeof authSignUpPageRouteRoute
'/mfa-session/$mfaSessionId': typeof MfaSessionPageRouteRoute
'/organization/mcp-endpoint-finalize': typeof organizationMcpEndpointFinalizePageRouteRoute
+ '/organization/oauth-consent': typeof organizationOauthConsentPageRouteRoute
'/organizations/none': typeof organizationNoOrgPageRouteRoute
'/admin/signup': typeof adminSignUpPageRouteRoute
'/login/admin': typeof authAdminLoginPageRouteRoute
@@ -6602,6 +6621,7 @@ export interface FileRoutesByTo {
'/signup': typeof authSignUpPageRouteRoute
'/mfa-session/$mfaSessionId': typeof MfaSessionPageRouteRoute
'/organization/mcp-endpoint-finalize': typeof organizationMcpEndpointFinalizePageRouteRoute
+ '/organization/oauth-consent': typeof organizationOauthConsentPageRouteRoute
'/organizations/none': typeof organizationNoOrgPageRouteRoute
'/admin/signup': typeof adminSignUpPageRouteRoute
'/login/admin': typeof authAdminLoginPageRouteRoute
@@ -6874,6 +6894,7 @@ export interface FileRoutesById {
'/_restrict-login-signup/signup/': typeof authSignUpPageRouteRoute
'/_authenticate/mfa-session/$mfaSessionId': typeof MfaSessionPageRouteRoute
'/_authenticate/organization/mcp-endpoint-finalize': typeof organizationMcpEndpointFinalizePageRouteRoute
+ '/_authenticate/organization/oauth-consent': typeof organizationOauthConsentPageRouteRoute
'/_authenticate/organizations/none': typeof organizationNoOrgPageRouteRoute
'/_restrict-login-signup/admin/signup': typeof adminSignUpPageRouteRoute
'/_restrict-login-signup/login/admin': typeof authAdminLoginPageRouteRoute
@@ -7182,6 +7203,7 @@ export interface FileRouteTypes {
| '/signup/'
| '/mfa-session/$mfaSessionId'
| '/organization/mcp-endpoint-finalize'
+ | '/organization/oauth-consent'
| '/organizations/none'
| '/admin/signup'
| '/login/admin'
@@ -7475,6 +7497,7 @@ export interface FileRouteTypes {
| '/signup'
| '/mfa-session/$mfaSessionId'
| '/organization/mcp-endpoint-finalize'
+ | '/organization/oauth-consent'
| '/organizations/none'
| '/admin/signup'
| '/login/admin'
@@ -7745,6 +7768,7 @@ export interface FileRouteTypes {
| '/_restrict-login-signup/signup/'
| '/_authenticate/mfa-session/$mfaSessionId'
| '/_authenticate/organization/mcp-endpoint-finalize'
+ | '/_authenticate/organization/oauth-consent'
| '/_authenticate/organizations/none'
| '/_restrict-login-signup/admin/signup'
| '/_restrict-login-signup/login/admin'
@@ -8093,6 +8117,7 @@ export const routeTree = rootRoute
"/_authenticate/personal-settings",
"/_authenticate/mfa-session/$mfaSessionId",
"/_authenticate/organization/mcp-endpoint-finalize",
+ "/_authenticate/organization/oauth-consent",
"/_authenticate/organizations/none"
]
},
@@ -8187,6 +8212,10 @@ export const routeTree = rootRoute
"filePath": "organization/McpEndpointFinalizePage/route.tsx",
"parent": "/_authenticate"
},
+ "/_authenticate/organization/oauth-consent": {
+ "filePath": "organization/OauthConsentPage/route.tsx",
+ "parent": "/_authenticate"
+ },
"/_authenticate/organizations/none": {
"filePath": "organization/NoOrgPage/route.tsx",
"parent": "/_authenticate"
diff --git a/frontend/src/routes.ts b/frontend/src/routes.ts
index 9f890d9821..00ccdb8e2c 100644
--- a/frontend/src/routes.ts
+++ b/frontend/src/routes.ts
@@ -506,6 +506,7 @@ export const routes = rootRoute("root.tsx", [
]),
route("/organizations/none", "organization/NoOrgPage/route.tsx"),
route("/organization/mcp-endpoint-finalize", "organization/McpEndpointFinalizePage/route.tsx"),
+ route("/organization/oauth-consent", "organization/OauthConsentPage/route.tsx"),
middleware("inject-org-details.tsx", [
adminRoute,
pamAccessRoute,