The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Add admin endpoints for OAuth clients and tokens (#74933)
Braden Shepherdson5f7c893f985f
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 409eb41cc60..531b535754d 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -1443,7 +1443,8 @@oauth-server{:team "UX West"- :api #{metabase.oauth-server.api+ :api #{metabase.oauth-server.api ;; Special case OAuth standard endpoints under `/`+ metabase.oauth-server.api.admin ;; The usual Metabase internal API endpoints under `/api`metabase.oauth-server.coremetabase.oauth-server.init}:uses #{apidiff --git a/e2e/test/scenarios/admin/oauth-authorizations.cy.spec.ts b/e2e/test/scenarios/admin/oauth-authorizations.cy.spec.tsnew file mode 100644index 00000000000..3fdf351935d--- /dev/null+++ b/e2e/test/scenarios/admin/oauth-authorizations.cy.spec.ts@@ -0,0 +1,169 @@+import { USERS } from "e2e/support/cypress_data";++const { H } = cy;++const PATH = "/admin/metabot/mcp/authorizations";+const REDIRECT_URI = "https://example.com/callback";++/**+ * End-to-end coverage for the OAuth Authorizations admin page.+ *+ * Events are seeded through the *real* OAuth endpoints rather than stubbed, so this exercises the+ * full contract: the DCR registration write-path, the consent/decision write-path, and the admin+ * read endpoint the page consumes. `approved`/`denied` rendering paths are also covered by the+ * backend integration tests in `oauth_server/api_test.clj` and `oauth_server/api/admin_test.clj`.+ *+ * Note: `POST /oauth/register` is throttled to 10/min/IP, so we deliberately seed only a handful of+ * events here. Pagination is covered by the page's unit test instead.+ */+describe("scenarios > admin > metabot > oauth authorizations", () => {+ beforeEach(() => {+ H.restore("default");+ cy.signInAsAdmin();+ });++ it("lists registration, approval, and denial events with client and user details", () => {+ registerClient("E2E MCP Client A");+ registerClient("E2E MCP Client B", {+ token_endpoint_auth_method: "client_secret_basic",+ }).then(approveClient);+ registerClient("E2E MCP Client C", {+ token_endpoint_auth_method: "client_secret_basic",+ }).then(denyClient);++ cy.visit(PATH);++ // Every client's registration row renders, and each decision event lands in the same row as+ // its client (and the deciding user). Client A's row also shows the registered redirect URI.+ assertEventRow("E2E MCP Client A", "Registered", REDIRECT_URI);+ assertEventRow("E2E MCP Client B", "Registered");+ assertEventRow("E2E MCP Client C", "Registered");+ assertEventRow("E2E MCP Client B", "Approved", USERS.admin.email);+ assertEventRow("E2E MCP Client C", "Denied", USERS.admin.email);+ });++ it("filters events by type via the API", () => {+ registerClient("E2E Filter Client", {+ token_endpoint_auth_method: "client_secret_basic",+ }).then(approveClient);++ cy.intercept("GET", "/api/oauth/authorizations*").as("list");+ cy.visit(PATH);+ cy.wait("@list");++ cy.findByLabelText("Filter by event").click();+ cy.findByRole("option", { name: "Approved" }).click();++ cy.wait("@list")+ .its("request.url")+ .should("include", "event-type=approved");++ cy.findByTestId("oauth-authorizations-table").within(() => {+ cy.findByText("Approved").should("be.visible");+ cy.findByText("Registered").should("not.exist");+ });+ });++ it("is accessible to superusers only", () => {+ cy.signInAsNormalUser();+ cy.request({+ method: "GET",+ url: "/api/oauth/authorizations",+ failOnStatusCode: false,+ })+ .its("status")+ .should("eq", 403);+ });+});++type RegisteredClient = { client_id: string };++/**+ * Register a dynamic client via `POST /oauth/register`, creating a `registered` audit event.+ * `extra` merges into the registration body — pass+ * `{ token_endpoint_auth_method: "client_secret_basic" }` for a confidential client that can+ * complete the consent flow without PKCE. Yields the registration response.+ */+function registerClient(+ clientName: string,+ extra: Record<string, unknown> = {},+) {+ return cy+ .request("POST", "/oauth/register", {+ client_name: clientName,+ redirect_uris: [REDIRECT_URI],+ ...extra,+ })+ .then(({ body }) => body as RegisteredClient);+}++function approveClient(client: RegisteredClient) {+ return decideClient(client, true);+}++function denyClient(client: RegisteredClient) {+ return decideClient(client, false);+}++/**+ * Drive the consent flow to a decision for a registered client, recording an `approved` or `denied`+ * event stamped with the signed-in user. `scope` is omitted (it's optional, and the DCR client's+ * agent scopes don't include `profile`); the client must be confidential so the public-client PKCE+ * requirement doesn't apply. Mirrors the real browser flow: GET the consent page, lift the CSRF+ * token + params signature from its hidden fields, then POST the decision (Cypress carries the+ * CSRF cookie). Both approve and deny redirect (302).+ */+function decideClient(client: RegisteredClient, approved: boolean) {+ const clientId = client.client_id;+ const authorizeUrl =+ `/oauth/authorize?client_id=${clientId}` ++ `&redirect_uri=${encodeURIComponent(REDIRECT_URI)}` ++ "&response_type=code&state=test-state";++ return cy.request("GET", authorizeUrl).then(({ body }) => {+ cy.request({+ method: "POST",+ url: "/oauth/authorize/decision",+ form: true,+ followRedirect: false,+ body: {+ approved: String(approved),+ csrf_token: extractHiddenField(body, "csrf_token"),+ params_sig: extractHiddenField(body, "params_sig"),+ client_id: clientId,+ redirect_uri: REDIRECT_URI,+ response_type: "code",+ state: "test-state",+ },+ })+ .its("status")+ .should("eq", 302);+ });+}++/**+ * Assert exactly one table row contains all of the given texts together — ties a specific event+ * (and the deciding user) to the expected client's row rather than checking page-wide counts.+ */+function assertEventRow(...texts: string[]) {+ cy.findByTestId("oauth-authorizations-table")+ .findAllByRole("row")+ .then(($rows) => {+ const matching = $rows.filter((_index, el) =>+ texts.every((text) => el.textContent?.includes(text)),+ );+ expect(matching, `row matching ${texts.join(" / ")}`).to.have.length(1);+ });+}++/** Pull the `value` of a hidden form input by `name` out of the consent page HTML. */+function extractHiddenField(html: string, name: string): string {+ const tag = html.match(new RegExp(`<input[^>]*name="${name}"[^>]*>`));+ const value = tag?.[0].match(/value="([^"]+)"/);+ if (!value) {+ throw new Error(+ `Could not find hidden field "${name}" in the consent page`,+ );+ }+ return value[1];+}diff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.cljindex fe16e1df3fa..638a068a410 100644--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj@@ -107,6 +107,7 @@"OAuthAccessToken""OAuthAuthorizationCode""OAuthClient"+ "OAuthClientEvent""OAuthRefreshToken""Permissions""PermissionsGroup"diff --git a/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.cljindex bfe1d6f10e2..c790317e9c1 100644--- a/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj+++ b/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj@@ -81,6 +81,7 @@:model/OAuthAccessToken:model/OAuthAuthorizationCode:model/OAuthClient+ :model/OAuthClientEvent:model/OAuthRefreshToken:model/ParameterCard:model/Permissionsdiff --git a/frontend/src/metabase-types/api/index.ts b/frontend/src/metabase-types/api/index.tsindex af0e8cf07cf..c8457421b08 100644--- a/frontend/src/metabase-types/api/index.ts+++ b/frontend/src/metabase-types/api/index.ts@@ -41,6 +41,7 @@ export * from "./models";export * from "./moderation";export * from "./notification";export * from "./notification-channels";+export * from "./oauth";export * from "./pagination";export * from "./parameters";export * from "./performance";diff --git a/frontend/src/metabase-types/api/mocks/index.ts b/frontend/src/metabase-types/api/mocks/index.tsindex 81351d05139..e8b913a32d9 100644--- a/frontend/src/metabase-types/api/mocks/index.ts+++ b/frontend/src/metabase-types/api/mocks/index.ts@@ -22,6 +22,7 @@ export * from "./metabot";export * from "./modelIndexes";export * from "./models";export * from "./notification";+export * from "./oauth";export * from "./parameters";export * from "./performance";export * from "./permissions";diff --git a/frontend/src/metabase-types/api/mocks/oauth.ts b/frontend/src/metabase-types/api/mocks/oauth.tsnew file mode 100644index 00000000000..da2fbb375c5--- /dev/null+++ b/frontend/src/metabase-types/api/mocks/oauth.ts@@ -0,0 +1,34 @@+import type {+ ListOAuthAuthorizationsResponse,+ OAuthAuthorization,+} from "metabase-types/api";++export const createMockOAuthAuthorization = (+ opts?: Partial<OAuthAuthorization>,+): OAuthAuthorization => ({+ id: 1,+ oauth_client_id: 10,+ client_id: "8f1b2c3d-0000-4a5b-8c9d-000000000001",+ user_id: 3,+ event_type: "approved",+ created_at: "2026-05-01T10:00:00Z",+ client_name: "Claude Code",+ client_uri: "https://claude.ai",+ registration_type: "dynamic",+ application_type: "native",+ redirect_uris: ["https://claude.ai/oauth/callback"],+ user_email: "[email protected]",+ user_first_name: "Test",+ user_last_name: "User",+ ...opts,+});++export const createMockListOAuthAuthorizationsResponse = (+ opts?: Partial<ListOAuthAuthorizationsResponse>,+): ListOAuthAuthorizationsResponse => ({+ data: [createMockOAuthAuthorization()],+ total: 1,+ limit: 50,+ offset: 0,+ ...opts,+});diff --git a/frontend/src/metabase-types/api/oauth.ts b/frontend/src/metabase-types/api/oauth.tsnew file mode 100644index 00000000000..56ffc9358ac--- /dev/null+++ b/frontend/src/metabase-types/api/oauth.ts@@ -0,0 +1,31 @@+import type { PaginationRequest, PaginationResponse } from "./pagination";++export type OAuthClientEventType = "registered" | "approved" | "denied";++/** One row of the OAuth client audit log. Client columns are `null` once the client is deleted. */+export interface OAuthAuthorization {+ id: number;+ oauth_client_id: number | null;+ client_id: string | null;+ /** The deciding user; null for `registered` events. */+ user_id: number | null;+ event_type: OAuthClientEventType;+ created_at: string;+ client_name: string | null;+ client_uri: string | null;+ registration_type: string | null;+ application_type: string | null;+ redirect_uris: string[] | null;+ user_email: string | null;+ user_first_name: string | null;+ user_last_name: string | null;+}++export type ListOAuthAuthorizationsRequest = {+ "client-id"?: string | null;+ "event-type"?: OAuthClientEventType | null;+} & PaginationRequest;++export type ListOAuthAuthorizationsResponse = {+ data: OAuthAuthorization[];+} & PaginationResponse;diff --git a/frontend/src/metabase/admin/ai/MetabotNavPane.tsx b/frontend/src/metabase/admin/ai/MetabotNavPane.tsxindex f817ba8c7f6..dfd9074519d 100644--- a/frontend/src/metabase/admin/ai/MetabotNavPane.tsx+++ b/frontend/src/metabase/admin/ai/MetabotNavPane.tsx@@ -25,8 +25,19 @@ export function MetabotNavPane() {disabled={!areAiFeaturesEnabled}icon="mcp"label={t`MCP`}- path="/admin/metabot/mcp"- />+ folderPattern="/admin/metabot/mcp"+ >+ <AdminNavItem+ disabled={!areAiFeaturesEnabled}+ label={t`Settings`}+ path="/admin/metabot/mcp"+ />+ <AdminNavItem+ disabled={!areAiFeaturesEnabled}+ label={t`Authorizations`}+ path="/admin/metabot/mcp/authorizations"+ />+ </AdminNavItem>{AiControlsNavItems}{AiAnalyticsNavItems}</AdminNavWrapper>diff --git a/frontend/src/metabase/admin/ai/MetabotNavPane.unit.spec.tsx b/frontend/src/metabase/admin/ai/MetabotNavPane.unit.spec.tsxindex a13a30a2adc..99a5d2828bb 100644--- a/frontend/src/metabase/admin/ai/MetabotNavPane.unit.spec.tsx+++ b/frontend/src/metabase/admin/ai/MetabotNavPane.unit.spec.tsx@@ -1,3 +1,4 @@+import userEvent from "@testing-library/user-event";import { Route } from "react-router";import { setupEnterprisePlugins } from "__support__/enterprise";@@ -14,11 +15,13 @@ const setup = ({aiControlsEnabled = false,auditAppEnabled = false,isConfigured = true,+ initialRoute = "/admin/metabot",}: {aiFeaturesEnabled?: boolean;aiControlsEnabled?: boolean;auditAppEnabled?: boolean;isConfigured?: boolean;+ initialRoute?: string;} = {}) => {mockSettings({"ai-features-enabled?": aiFeaturesEnabled,@@ -34,7 +37,7 @@ const setup = ({<Route path="/admin/metabot*" component={MetabotNavPane} />,{withRouter: true,- initialRoute: "/admin/metabot",+ initialRoute,storeInitialState: {settings: createMockSettingsState({"ai-features-enabled?": aiFeaturesEnabled,@@ -95,10 +98,7 @@ describe("MetabotNavPane", () => {setup({ aiControlsEnabled: false, aiFeaturesEnabled: true });expect(await screen.findByText("AI Settings")).toBeInTheDocument();- expect(screen.getByRole("link", { name: /MCP/ })).toHaveAttribute(- "href",- "/admin/metabot/mcp",- );+ expect(screen.getByText("MCP")).toBeInTheDocument();expect(screen.getByRole("link", { name: /Usage controls/ }),@@ -113,6 +113,15 @@ describe("MetabotNavPane", () => {expect(screen.getByRole("link", { name: /System prompts/ }),).toHaveAttribute("href", "/admin/metabot/system-prompts/metabot-chat");++ await userEvent.click(await screen.findByText("MCP"));++ expect(+ await screen.findByRole("link", { name: "Settings" }),+ ).toHaveAttribute("href", "/admin/metabot/mcp");+ expect(+ screen.getByRole("link", { name: "Authorizations" }),+ ).toHaveAttribute("href", "/admin/metabot/mcp/authorizations");});it("displays the usage auditing upsell link when audit app is available and ai controls is unavailable", async () => {diff --git a/frontend/src/metabase/admin/ai/OAuthAuthorizationsPage.module.css b/frontend/src/metabase/admin/ai/OAuthAuthorizationsPage.module.cssnew file mode 100644index 00000000000..923f0e8b28a--- /dev/null+++ b/frontend/src/metabase/admin/ai/OAuthAuthorizationsPage.module.css@@ -0,0 +1,9 @@+.staticRow {+ cursor: default;+}++/* doubled selector to beat .content:hover's specificity regardless of bundle order */+.staticRow.staticRow:hover,+.staticRow.staticRow:focus {+ background-color: transparent;+}diff --git a/frontend/src/metabase/admin/ai/OAuthAuthorizationsPage.tsx b/frontend/src/metabase/admin/ai/OAuthAuthorizationsPage.tsxnew file mode 100644index 00000000000..0ad1243e2a1--- /dev/null+++ b/frontend/src/metabase/admin/ai/OAuthAuthorizationsPage.tsx@@ -0,0 +1,251 @@+import { useMemo } from "react";+import type { WithRouterProps } from "react-router";+import { t } from "ttag";++import NoResults from "assets/img/no_results.svg";+import { SettingsPageWrapper } from "metabase/admin/components/SettingsSection";+import { useListOAuthAuthorizationsQuery } from "metabase/api";+import { DateTime } from "metabase/common/components/DateTime";+import { EmptyState } from "metabase/common/components/EmptyState";+import { DelayedLoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper/DelayedLoadingAndErrorWrapper";+import { PaginationControls } from "metabase/common/components/PaginationControls";+import {+ type QueryParam,+ type UrlStateConfig,+ getFirstParamValue,+ useUrlState,+} from "metabase/common/hooks/use-url-state";+import CS from "metabase/css/core/index.css";+import {+ Badge,+ Box,+ Card,+ Ellipsified,+ Group,+ Select,+ TreeTable,+ type TreeTableColumnDef,+ useTreeTableInstance,+} from "metabase/ui";+import type { MetabaseColorKey } from "metabase/ui/colors/types";+import type {+ OAuthAuthorization,+ OAuthClientEventType,+} from "metabase-types/api";++import S from "./OAuthAuthorizationsPage.module.css";+import {+ OAUTH_EVENT_TYPES,+ OAUTH_PAGE_SIZE,+ getOAuthEventTypeLabel,+ isOAuthEventType,+} from "./oauth-utils";++const ALL_EVENT_TYPES = "all";++type EventTypeFilter = OAuthClientEventType | typeof ALL_EVENT_TYPES;++const EVENT_COLORS: Record<OAuthClientEventType, MetabaseColorKey> = {+ registered: "text-secondary",+ approved: "success",+ denied: "error",+};++type UrlState = {+ page: number;+ eventType: EventTypeFilter;+};++const urlStateConfig: UrlStateConfig<UrlState> = {+ parse: (query) => ({+ page: parsePage(query.page),+ eventType: parseEventType(query.event_type),+ }),+ serialize: ({ page, eventType }) => ({+ page: page === 0 ? undefined : String(page),+ event_type: eventType === ALL_EVENT_TYPES ? undefined : eventType,+ }),+};++function parsePage(param: QueryParam): number {+ const parsed = parseInt(getFirstParamValue(param) || "0", 10);+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : 0;+}++function parseEventType(param: QueryParam): EventTypeFilter {+ const value = getFirstParamValue(param);+ return value && isOAuthEventType(value) ? value : ALL_EVENT_TYPES;+}++export const OAuthAuthorizationsPage = ({ location }: WithRouterProps) => {+ const [{ page, eventType }, { patchUrlState }] = useUrlState(+ location,+ urlStateConfig,+ );++ const { data, isLoading, error } = useListOAuthAuthorizationsQuery(+ {+ limit: OAUTH_PAGE_SIZE,+ offset: page * OAUTH_PAGE_SIZE,+ "event-type": eventType === ALL_EVENT_TYPES ? undefined : eventType,+ },+ { refetchOnMountOrArgChange: true },+ );++ const authorizations = data?.data ?? [];+ const total = data?.total ?? 0;++ return (+ <SettingsPageWrapper+ title={t`Authorization logs`}+ description={t`An audit log of MCP and Agent API client registrations and the authorization decisions users have approved or denied.`}+ h="100%"+ mih={0}+ w="100%"+ maw="60rem"+ mx="auto"+ p="xl"+ >+ <Select+ data={[+ { value: ALL_EVENT_TYPES, label: t`All events` },+ ...OAUTH_EVENT_TYPES.map((value) => ({+ value,+ label: getOAuthEventTypeLabel(value),+ })),+ ]}+ value={eventType}+ onChange={(value) =>+ patchUrlState({+ eventType: value ?? ALL_EVENT_TYPES,+ page: 0,+ })+ }+ aria-label={t`Filter by event`}+ style={{ alignSelf: "start" }}+ />++ <AuthorizationsTable+ authorizations={authorizations}+ isLoading={isLoading}+ error={error}+ />+ <Group justify="end">+ <PaginationControls+ page={page}+ pageSize={OAUTH_PAGE_SIZE}+ itemsLength={authorizations.length}+ total={total}+ onPreviousPage={() => patchUrlState({ page: page - 1 })}+ onNextPage={() => patchUrlState({ page: page + 1 })}+ />+ </Group>+ </SettingsPageWrapper>+ );+};++function getAuthorizationColumns(): TreeTableColumnDef<OAuthAuthorization>[] {+ // The text columns stretch to fill the container (no `width`) so the table never grows+ // wider than its parent. `client`/`user` cap at 220; `redirect-uri` stays uncapped to+ // absorb leftover width. `event`/`created-at` are fixed.+ return [+ {+ id: "client",+ header: t`Client`,+ minWidth: 120,+ maxWidth: 180,+ accessorFn: (auth) => auth.client_name || auth.client_id || "—",+ cell: ({ getValue }) => (+ <Ellipsified className={CS.textBold}>{String(getValue())}</Ellipsified>+ ),+ },+ {+ id: "user",+ header: t`User`,+ minWidth: 120,+ maxWidth: 180,+ accessorFn: (auth) => auth.user_email ?? "—",+ cell: ({ getValue }) => <Ellipsified>{String(getValue())}</Ellipsified>,+ },+ {+ id: "redirect-uri",+ header: t`Redirect URI`,+ minWidth: 120,+ accessorFn: (auth) =>+ auth.redirect_uris?.length ? auth.redirect_uris.join(", ") : "—",+ cell: ({ getValue }) => <Ellipsified>{String(getValue())}</Ellipsified>,+ },+ {+ id: "event",+ header: t`Event`,+ width: 120,+ cell: ({ row }) => {+ const { event_type } = row.original;+ return (+ <Badge color={EVENT_COLORS[event_type]} variant="light">+ {getOAuthEventTypeLabel(event_type)}+ </Badge>+ );+ },+ },+ {+ id: "created-at",+ header: t`Date`,+ width: 160,+ accessorFn: (auth) => auth.created_at,+ cell: ({ row }) => (+ <DateTime value={row.original.created_at} unit="minute" />+ ),+ },+ ];+}++function AuthorizationsTable({+ authorizations,+ isLoading,+ error,+}: {+ authorizations: OAuthAuthorization[];+ isLoading: boolean;+ error: unknown;+}) {+ const columns = useMemo(() => getAuthorizationColumns(), []);+ const instance = useTreeTableInstance<OAuthAuthorization>({+ data: authorizations,+ columns,+ getNodeId: (auth) => String(auth.id),+ enableSorting: false,+ });++ if (isLoading || error) {+ return <DelayedLoadingAndErrorWrapper loading={isLoading} error={error} />;+ }++ return (+ <Card+ withBorder+ p={0}+ flex="1"+ mih={0}+ display="flex"+ style={{ flexDirection: "column", overflow: "hidden" }}+ data-testid="oauth-authorizations-table"+ >+ <TreeTable+ instance={instance}+ hierarchical={false}+ classNames={{ row: S.staticRow }}+ ariaLabel={t`OAuth authorizations`}+ emptyState={+ <Box p="xl" ta="center" data-testid="oauth-authorizations-empty">+ <EmptyState+ title={t`No events`}+ illustrationElement={<img src={NoResults} />}+ spacing="sm"+ />+ </Box>+ }+ />+ </Card>+ );+}diff --git a/frontend/src/metabase/admin/ai/OAuthAuthorizationsPage.unit.spec.tsx b/frontend/src/metabase/admin/ai/OAuthAuthorizationsPage.unit.spec.tsxnew file mode 100644index 00000000000..0ef61cb6b24--- /dev/null+++ b/frontend/src/metabase/admin/ai/OAuthAuthorizationsPage.unit.spec.tsx@@ -0,0 +1,236 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";+import type { ReactNode } from "react";+import { Route } from "react-router";++import { setupOAuthAuthorizationsEndpoint } from "__support__/server-mocks";+import { renderWithProviders, screen, waitFor, within } from "__support__/ui";+import type { ListOAuthAuthorizationsResponse } from "metabase-types/api";+import {+ createMockListOAuthAuthorizationsResponse,+ createMockOAuthAuthorization,+} from "metabase-types/api/mocks";++import { OAuthAuthorizationsPage } from "./OAuthAuthorizationsPage";+import { OAUTH_PAGE_SIZE } from "./oauth-utils";++// TreeTable virtualizes its rows, which renders nothing in jsdom. Mock it to+// render each row's cells via flexRender so the column cell logic is exercised.+jest.mock("metabase/ui/components/data-display/TreeTable/TreeTable", () => {+ const { flexRender } = jest.requireActual("@tanstack/react-table");+ return {+ TreeTable: ({+ instance,+ emptyState,+ }: {+ instance: { table: { getRowModel: () => { rows: any[] } } };+ emptyState: ReactNode;+ }) => {+ const rows = instance.table.getRowModel().rows;+ if (rows.length === 0) {+ return <div>{emptyState}</div>;+ }+ return (+ <div>+ {rows.map((row) => (+ <div key={row.id} role="row">+ {row.getVisibleCells().map((cell: any) => (+ <span key={cell.id}>+ {flexRender(cell.column.columnDef.cell, cell.getContext())}+ </span>+ ))}+ </div>+ ))}+ </div>+ );+ },+ };+});++const PATHNAME = "/admin/metabot/mcp/authorizations";++const setup = ({+ response = createMockListOAuthAuthorizationsResponse(),+ error = false,+ initialRoute = PATHNAME,+}: {+ response?: ListOAuthAuthorizationsResponse;+ error?: boolean;+ initialRoute?: string;+} = {}) => {+ if (error) {+ fetchMock.get("path:/api/oauth/authorizations", { status: 500 });+ } else {+ setupOAuthAuthorizationsEndpoint(response);+ }++ return renderWithProviders(+ <Route path={PATHNAME} component={OAuthAuthorizationsPage} />,+ { withRouter: true, initialRoute },+ );+};++const lastCallUrl = () => {+ const calls = fetchMock.callHistory.calls("path:/api/oauth/authorizations");+ return calls[calls.length - 1]?.url ?? "";+};++describe("OAuthAuthorizationsPage", () => {+ it("shows an empty state when no authorizations match", async () => {+ setup({+ response: createMockListOAuthAuthorizationsResponse({+ data: [],+ total: 0,+ }),+ });++ expect(+ await screen.findByTestId("oauth-authorizations-empty"),+ ).toBeInTheDocument();+ expect(screen.queryByRole("row")).not.toBeInTheDocument();+ });++ it("renders a row per event with client, user, and event type", async () => {+ setup({+ response: createMockListOAuthAuthorizationsResponse({+ data: [+ createMockOAuthAuthorization({+ client_name: "Claude Code",+ user_email: "[email protected]",+ event_type: "approved",+ }),+ ],+ total: 1,+ }),+ });++ const table = await screen.findByTestId("oauth-authorizations-table");++ expect(within(table).getByText("Claude Code")).toBeInTheDocument();+ expect(within(table).getByText("[email protected]")).toBeInTheDocument();+ expect(within(table).getByText("Approved")).toBeInTheDocument();+ });++ it("renders the client's redirect URIs", async () => {+ setup({+ response: createMockListOAuthAuthorizationsResponse({+ data: [+ createMockOAuthAuthorization({+ redirect_uris: [+ "https://app.example.com/cb",+ "https://app.example.com/cb2",+ ],+ }),+ ],+ total: 1,+ }),+ });++ const table = await screen.findByTestId("oauth-authorizations-table");+ expect(+ within(table).getByText(+ "https://app.example.com/cb, https://app.example.com/cb2",+ ),+ ).toBeInTheDocument();+ });++ it("renders a registration event with no deciding user", async () => {+ setup({+ response: createMockListOAuthAuthorizationsResponse({+ data: [+ createMockOAuthAuthorization({+ event_type: "registered",+ user_id: null,+ user_email: null,+ }),+ ],+ total: 1,+ }),+ });++ const table = await screen.findByTestId("oauth-authorizations-table");+ expect(within(table).getByText("Registered")).toBeInTheDocument();+ expect(within(table).getByText("—")).toBeInTheDocument();+ });++ it("falls back to the client id when there is no client name", async () => {+ setup({+ response: createMockListOAuthAuthorizationsResponse({+ data: [+ createMockOAuthAuthorization({+ client_name: null,+ client_id: "client-abc",+ }),+ ],+ total: 1,+ }),+ });++ const table = await screen.findByTestId("oauth-authorizations-table");+ expect(within(table).getByText("client-abc")).toBeInTheDocument();+ });++ it("renders a denied event", async () => {+ setup({+ response: createMockListOAuthAuthorizationsResponse({+ data: [createMockOAuthAuthorization({ event_type: "denied" })],+ total: 1,+ }),+ });++ const table = await screen.findByTestId("oauth-authorizations-table");+ expect(within(table).getByText("Denied")).toBeInTheDocument();+ });++ it("does not filter by event type by default", async () => {+ setup();++ await waitFor(() => {+ expect(lastCallUrl()).toContain("/api/oauth/authorizations");+ });+ expect(lastCallUrl()).not.toContain("event-type=");+ });++ it("refetches with the selected event type when the filter changes", async () => {+ setup();++ await screen.findByTestId("oauth-authorizations-table");++ await userEvent.click(screen.getByLabelText("Filter by event"));+ await userEvent.click(await screen.findByText("Denied"));++ await waitFor(() => {+ expect(lastCallUrl()).toContain("event-type=denied");+ });+ });++ it("requests the next page when paginating", async () => {+ setup({+ response: createMockListOAuthAuthorizationsResponse({+ data: [createMockOAuthAuthorization()],+ total: OAUTH_PAGE_SIZE * 5,+ limit: OAUTH_PAGE_SIZE,+ offset: 0,+ }),+ });++ const nextPage = await screen.findByRole("button", { name: "Next page" });+ await userEvent.click(nextPage);++ await waitFor(() => {+ expect(lastCallUrl()).toContain(`offset=${OAUTH_PAGE_SIZE}`);+ });+ });++ it("does not render any rows when the request fails", async () => {+ setup({ error: true });++ await waitFor(() => {+ expect(lastCallUrl()).toContain("/api/oauth/authorizations");+ });+ expect(screen.queryByRole("row")).not.toBeInTheDocument();+ expect(+ screen.queryByTestId("oauth-authorizations-empty"),+ ).not.toBeInTheDocument();+ });+});diff --git a/frontend/src/metabase/admin/ai/oauth-utils.ts b/frontend/src/metabase/admin/ai/oauth-utils.tsnew file mode 100644index 00000000000..6d6dbe8931c--- /dev/null+++ b/frontend/src/metabase/admin/ai/oauth-utils.ts@@ -0,0 +1,28 @@+import { t } from "ttag";++import type { OAuthClientEventType } from "metabase-types/api";++export const OAUTH_PAGE_SIZE = 50;++export const OAUTH_EVENT_TYPES: OAuthClientEventType[] = [+ "registered",+ "approved",+ "denied",+];++export function getOAuthEventTypeLabel(+ eventType: OAuthClientEventType,+): string {+ switch (eventType) {+ case "registered":+ return t`Registered`;+ case "approved":+ return t`Approved`;+ case "denied":+ return t`Denied`;+ }+}++export function isOAuthEventType(value: string): value is OAuthClientEventType {+ return OAUTH_EVENT_TYPES.some((v) => v === value);+}diff --git a/frontend/src/metabase/admin/routes.tsx b/frontend/src/metabase/admin/routes.tsxindex a85a4afea44..ef0c0258596 100644--- a/frontend/src/metabase/admin/routes.tsx+++ b/frontend/src/metabase/admin/routes.tsx@@ -70,6 +70,7 @@ import { getTokenFeature } from "metabase/selectors/settings";import { AISettingsPage, McpSettingsPage } from "./ai/AISettingsPage";import { MetabotAdminLayout } from "./ai/MetabotAdminLayout";+import { OAuthAuthorizationsPage } from "./ai/OAuthAuthorizationsPage";import { ModelPersistenceConfiguration } from "./performance/components/ModelPersistenceConfiguration";import { StrategyEditorForDatabases } from "./performance/components/StrategyEditorForDatabases";import { getSettingsRoutes } from "./settingsRoutes";@@ -280,6 +281,21 @@ export const getRoutes = (<IndexRoute key="index" component={AISettingsPage} /><Route key="mcp" path="mcp" component={McpSettingsPage} /></Route>+ <Route+ key="mcp-authorizations-layout"+ component={(props) => (+ <MetabotAdminLayout+ {...props}+ fullWidth+ innerContentProps={{ fullWidth: true, fullHeight: true }}+ />+ )}+ >+ <Route+ path="mcp/authorizations"+ component={OAuthAuthorizationsPage}+ />+ </Route><Routekey="layout"component={(props) => (diff --git a/frontend/src/metabase/api/index.ts b/frontend/src/metabase/api/index.tsindex 526cce2cdde..923c7e926f1 100644--- a/frontend/src/metabase/api/index.ts+++ b/frontend/src/metabase/api/index.ts@@ -32,6 +32,7 @@ export * from "./metric";export * from "./model-index";export * from "./moderation";export * from "./notification";+export * from "./oauth";export * from "./parameters";export * from "./permission";export * from "./persist";diff --git a/frontend/src/metabase/api/oauth.ts b/frontend/src/metabase/api/oauth.tsnew file mode 100644index 00000000000..6b988d188b7--- /dev/null+++ b/frontend/src/metabase/api/oauth.ts@@ -0,0 +1,26 @@+import type {+ ListOAuthAuthorizationsRequest,+ ListOAuthAuthorizationsResponse,+} from "metabase-types/api";++import { Api } from "./api";+import { provideOAuthAuthorizationListTags } from "./tags";++export const oauthApi = Api.injectEndpoints({+ endpoints: (builder) => ({+ listOAuthAuthorizations: builder.query<+ ListOAuthAuthorizationsResponse,+ ListOAuthAuthorizationsRequest | void+ >({+ query: (params) => ({+ method: "GET",+ url: "/api/oauth/authorizations",+ params,+ }),+ providesTags: (response) =>+ response ? provideOAuthAuthorizationListTags(response.data) : [],+ }),+ }),+});++export const { useListOAuthAuthorizationsQuery } = oauthApi;diff --git a/frontend/src/metabase/api/tags/constants.ts b/frontend/src/metabase/api/tags/constants.tsindex f84301c5307..1f3361f7484 100644--- a/frontend/src/metabase/api/tags/constants.ts+++ b/frontend/src/metabase/api/tags/constants.ts@@ -33,6 +33,7 @@ export const TAG_TYPES = ["measure","model-index","notification",+ "oauth-authorization","parameter-values","permissions-group","persisted-info",diff --git a/frontend/src/metabase/api/tags/utils.ts b/frontend/src/metabase/api/tags/utils.tsindex bf7794927dd..7feb558a19d 100644--- a/frontend/src/metabase/api/tags/utils.ts+++ b/frontend/src/metabase/api/tags/utils.ts@@ -37,6 +37,7 @@ import type {ModelIndex,NativeQuerySnippet,NotificationChannel,+ OAuthAuthorization,ParameterId,PopularItem,RecentItem,@@ -486,6 +487,21 @@ export const provideAdminNotificationListTags = (),];+export function provideOAuthAuthorizationListTags(+ authorizations: OAuthAuthorization[],+): TagDescription<TagType>[] {+ return [+ listTag("oauth-authorization"),+ ...authorizations.flatMap(provideOAuthAuthorizationTags),+ ];+}++export function provideOAuthAuthorizationTags(+ authorization: OAuthAuthorization,+): TagDescription<TagType>[] {+ return [idTag("oauth-authorization", authorization.id)];+}+export function providePermissionsGroupListTags(groups: GroupListQuery[],): TagDescription<TagType>[] {diff --git a/frontend/test/__support__/server-mocks/index.ts b/frontend/test/__support__/server-mocks/index.tsindex 2bc0a90cb23..a9126edd7dd 100644--- a/frontend/test/__support__/server-mocks/index.ts+++ b/frontend/test/__support__/server-mocks/index.ts@@ -35,6 +35,7 @@ export * from "./metabot";export * from "./metric";export * from "./model-indexes";export * from "./native-query-snippet";+export * from "./oauth";export * from "./performance";export * from "./permissions";export * from "./premium-features";diff --git a/frontend/test/__support__/server-mocks/oauth.ts b/frontend/test/__support__/server-mocks/oauth.tsnew file mode 100644index 00000000000..3f9963985fe--- /dev/null+++ b/frontend/test/__support__/server-mocks/oauth.ts@@ -0,0 +1,10 @@+import fetchMock, { type UserRouteConfig } from "fetch-mock";++import type { ListOAuthAuthorizationsResponse } from "metabase-types/api";++export function setupOAuthAuthorizationsEndpoint(+ response: ListOAuthAuthorizationsResponse,+ options?: UserRouteConfig,+) {+ fetchMock.get("path:/api/oauth/authorizations", response, options);+}diff --git a/resources/migrations/063/20260601_oauth_client_event.yaml b/resources/migrations/063/20260601_oauth_client_event.yamlnew file mode 100644index 00000000000..d05ddb19402--- /dev/null+++ b/resources/migrations/063/20260601_oauth_client_event.yaml@@ -0,0 +1,96 @@+## Append-only audit trail for the OAuth dynamic client registration (DCR) lifecycle.+## One row is recorded when a client registers, and one row per approve/deny decision.++databaseChangeLog:+ - changeSet:+ id: v63.k7m2qd+ author: bshepherdson+ comment: Create oauth_client_event table to audit DCR registration and decision events+ changes:+ - createTable:+ tableName: oauth_client_event+ remarks: Append-only audit log of dynamic client registration and authorization events+ columns:+ - column:+ name: id+ type: int+ remarks: Auto-incrementing primary key+ autoIncrement: true+ constraints:+ primaryKey: true+ nullable: false+ - column:+ name: oauth_client_id+ type: int+ remarks: FK to oauth_client.id; nulled out if the client is deleted+ constraints:+ nullable: true+ - column:+ name: user_id+ type: int+ remarks: FK to core_user.id of the user who made the decision; null for registration events+ constraints:+ nullable: true+ - column:+ name: event_type+ type: varchar(20)+ remarks: "Event type: registered, approved, or denied"+ constraints:+ nullable: false+ - column:+ name: created_at+ type: ${timestamp_type}+ remarks: Timestamp when the event occurred+ defaultValueComputed: current_timestamp+ constraints:+ nullable: false++ - changeSet:+ id: v63.r9w4xb+ author: bshepherdson+ comment: Add index on oauth_client_event.oauth_client_id+ changes:+ - createIndex:+ tableName: oauth_client_event+ indexName: idx_oauth_client_event_oauth_client_id+ columns:+ - column:+ name: oauth_client_id++ - changeSet:+ id: v63.x2d7kq+ author: bshepherdson+ comment: Add index on oauth_client_event.user_id+ changes:+ - createIndex:+ tableName: oauth_client_event+ indexName: idx_oauth_client_event_user_id+ columns:+ - column:+ name: user_id++ - changeSet:+ id: v63.t3z8np+ author: bshepherdson+ comment: Add FK on oauth_client_event.oauth_client_id+ changes:+ - addForeignKeyConstraint:+ baseTableName: oauth_client_event+ baseColumnNames: oauth_client_id+ referencedTableName: oauth_client+ referencedColumnNames: id+ constraintName: fk_oauth_client_event_oauth_client_id+ onDelete: SET NULL++ - changeSet:+ id: v63.h5c1vj+ author: bshepherdson+ comment: Add FK on oauth_client_event.user_id+ changes:+ - addForeignKeyConstraint:+ baseTableName: oauth_client_event+ baseColumnNames: user_id+ referencedTableName: core_user+ referencedColumnNames: id+ constraintName: fk_oauth_client_event_user_id+ onDelete: SET NULLdiff --git a/src/metabase/api_routes/routes.clj b/src/metabase/api_routes/routes.cljindex 181c4464656..7309133999d 100644--- a/src/metabase/api_routes/routes.clj+++ b/src/metabase/api_routes/routes.clj@@ -42,6 +42,7 @@[metabase.model-persistence.api][metabase.native-query-snippets.api][metabase.notification.api]+ [metabase.oauth-server.api.admin][metabase.permissions-rest.api][metabase.premium-features.api][metabase.product-feedback.api]@@ -97,6 +98,7 @@metabase.login-history.api/keep-memetabase.mcp.api/keep-memetabase.mcp.callback-api/keep-me+ metabase.oauth-server.api.admin/keep-memetabase.measures.api/keep-memetabase.metrics.api/keep-memetabase.model-persistence.api/keep-me@@ -205,6 +207,7 @@"/native-query-snippet" (+auth 'metabase.native-query-snippets.api)"/notification" metabase.notification.api/notification-routes"/notify" (+static-apikey metabase.sync.api/notify-routes)+ "/oauth" (+auth 'metabase.oauth-server.api.admin)"/permissions" (+auth 'metabase.permissions-rest.api)"/persist" (+auth 'metabase.model-persistence.api)"/premium-features" (+auth metabase.premium-features.api/routes)diff --git a/src/metabase/cmd/copy.clj b/src/metabase/cmd/copy.cljindex fa3ea135334..175f351ce60 100644--- a/src/metabase/cmd/copy.clj+++ b/src/metabase/cmd/copy.clj@@ -128,6 +128,7 @@:model/Measure;; 60+:model/OAuthClient+ :model/OAuthClientEvent:model/OAuthAuthorizationCode:model/OAuthAccessToken:model/OAuthRefreshTokendiff --git a/src/metabase/models/resolution.clj b/src/metabase/models/resolution.cljindex 00e4ed4ff63..4ebefd1488e 100644--- a/src/metabase/models/resolution.clj+++ b/src/metabase/models/resolution.clj@@ -78,6 +78,7 @@:model/OAuthAccessToken metabase.oauth-server.models.oauth-access-token:model/OAuthAuthorizationCode metabase.oauth-server.models.oauth-authorization-code:model/OAuthClient metabase.oauth-server.models.oauth-client+ :model/OAuthClientEvent metabase.oauth-server.models.oauth-client-event:model/OAuthRefreshToken metabase.oauth-server.models.oauth-refresh-token:model/NotificationCard metabase.notification.models:model/NotificationHandler metabase.notification.modelsdiff --git a/src/metabase/oauth_server/api/admin.clj b/src/metabase/oauth_server/api/admin.cljnew file mode 100644index 00000000000..6970b653479--- /dev/null+++ b/src/metabase/oauth_server/api/admin.clj@@ -0,0 +1,71 @@+(ns metabase.oauth-server.api.admin+ "Admin-only endpoints for auditing OAuth dynamic client registration (DCR) events."+ (:require+ [metabase.api.common :as api]+ [metabase.api.macros :as api.macros]+ [metabase.request.current :as request]+ [metabase.util.json :as json]+ [metabase.util.malli.schema :as ms]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++(defn- present-event+ [row]+ ;; `redirect_uris` is stored as a JSON array but selected via raw SQL here, so the model's+ ;; JSON transform doesn't apply — decode it ourselves into a vector (nil for deleted clients).+ (-> row+ (select-keys [:id :oauth_client_id :client_id :event_type :created_at+ :client_name :client_uri :registration_type :application_type :redirect_uris+ :user_id :user_email :user_first_name :user_last_name])+ (update :redirect_uris #(some-> % json/decode))))++(defn- event-where-clause+ [client-id event-type]+ (let [clauses (cond-> []+ client-id (conj [:= :c.client_id client-id])+ event-type (conj [:= :e.event_type event-type]))]+ (when (seq clauses)+ (into [:and] clauses))))++(api.macros/defendpoint :get "/authorizations"+ :- [:map+ [:total ms/IntGreaterThanOrEqualToZero]+ [:limit ms/PositiveInt]+ [:offset ms/IntGreaterThanOrEqualToZero]+ [:data [:sequential :map]]]+ "List OAuth dynamic client registration events (registered, approved, or denied), newest first.+ Joins client info and, for decision events, the deciding user. Superuser only."+ [_route-params+ {:keys [client-id event-type]} :- [:map+ [:client-id {:optional true} [:maybe ms/NonBlankString]]+ [:event-type {:optional true} [:maybe [:enum "registered" "approved" "denied"]]]]]+ (api/check-superuser)+ (let [limit (or (request/limit) 50)+ offset (or (request/offset) 0)+ where (event-where-clause client-id event-type)+ total (:count (first (t2/query (cond-> {:select [[[:count :*] :count]]+ :from [[:oauth_client_event :e]]+ :left-join [[:oauth_client :c] [:= :e.oauth_client_id :c.id]]}+ where (assoc :where where)))))+ rows (t2/query (cond-> {:select [:e.id :e.oauth_client_id :e.user_id :e.event_type :e.created_at+ [:c.client_id :client_id]+ [:c.client_name :client_name]+ [:c.client_uri :client_uri]+ [:c.registration_type :registration_type]+ [:c.application_type :application_type]+ [:c.redirect_uris :redirect_uris]+ [:u.email :user_email]+ [:u.first_name :user_first_name]+ [:u.last_name :user_last_name]]+ :from [[:oauth_client_event :e]]+ :left-join [[:oauth_client :c] [:= :e.oauth_client_id :c.id]+ [:core_user :u] [:= :e.user_id :u.id]]+ :order-by [[:e.created_at :desc] [:e.id :desc]]+ :limit limit+ :offset offset}+ where (assoc :where where)))]+ {:total (or total 0)+ :limit limit+ :offset offset+ :data (mapv present-event rows)}))diff --git a/src/metabase/oauth_server/api/oauth.clj b/src/metabase/oauth_server/api/oauth.cljindex c720fb35feb..8fcd2b674c9 100644--- a/src/metabase/oauth_server/api/oauth.clj+++ b/src/metabase/oauth_server/api/oauth.clj@@ -9,6 +9,7 @@[metabase.api.macros :as api.macros][metabase.oauth-server.consent-page :as consent-page][metabase.oauth-server.core :as oauth-server]+ [metabase.oauth-server.models.oauth-client-event :as client-event][metabase.oauth-server.settings :as oauth-settings][metabase.request.core :as request][metabase.system.core :as system]@@ -110,6 +111,8 @@(let [url (if approved(oidc/authorize provider parsed (str (:metabase-user-id request)))(oidc/deny-authorization provider parsed "access_denied" "User denied the request"))]+ ;; Record an audit event for the user's decision on this client's registration.+ (client-event/record-decision! (:client_id parsed) (:metabase-user-id request) approved)(-> {:status 302:headers {"Location" url}:body ""}@@ -209,6 +212,8 @@client-id (:client_id response)];; Mark as dynamically registered (the library doesn't know about registration_type)(proto/update-client (:client-store provider) client-id {:registration-type "dynamic"})+ ;; Open the audit trail for this DCR client with a pending decision.+ (client-event/record-registration! client-id){:status 201:headers {"Content-Type" "application/json"}:body response})diff --git a/src/metabase/oauth_server/models/oauth_client_event.clj b/src/metabase/oauth_server/models/oauth_client_event.cljnew file mode 100644index 00000000000..b7dbde33af7--- /dev/null+++ b/src/metabase/oauth_server/models/oauth_client_event.clj@@ -0,0 +1,42 @@+(ns metabase.oauth-server.models.oauth-client-event+ "Append-only audit trail for the OAuth dynamic client registration (DCR) lifecycle.++ A `registered` event is recorded when a client registers via `POST /oauth/register` (which is+ unauthenticated, so it has no `user_id`). A separate `approved` or `denied` event is recorded for+ each decision a user makes via `POST /oauth/authorize/decision`, stamped with the deciding user's+ `user_id`."+ (:require+ [metabase.util.log :as log]+ [methodical.core :as methodical]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++(methodical/defmethod t2/table-name :model/OAuthClientEvent [_model] :oauth_client_event)++(doto :model/OAuthClientEvent+ (derive :metabase/model))++(defn- client-pk+ "Look up the numeric `oauth_client.id` primary key for the given OAuth `client-id` (UUID)."+ [client-id]+ (t2/select-one-pk :model/OAuthClient :client_id client-id))++(defn record-registration!+ "Record a `registered` event for the freshly-registered client identified by `client-id` (the OAuth+ UUID). No-op (with a warning) if the client row cannot be found."+ [client-id]+ (if-let [oauth-client-id (client-pk client-id)]+ (t2/insert! :model/OAuthClientEvent {:oauth_client_id oauth-client-id+ :event_type "registered"})+ (log/warnf "Cannot record OAuth registration event: no client found for client_id %s" client-id)))++(defn record-decision!+ "Record an `approved` or `denied` event for `client-id` (the OAuth UUID), made by `user-id`. No-op+ (with a warning) if the client row cannot be found."+ [client-id user-id approved?]+ (if-let [oauth-client-id (client-pk client-id)]+ (t2/insert! :model/OAuthClientEvent {:oauth_client_id oauth-client-id+ :user_id user-id+ :event_type (if approved? "approved" "denied")})+ (log/warnf "Cannot record OAuth decision event: no client found for client_id %s" client-id)))diff --git a/test/metabase/oauth_server/api/admin_test.clj b/test/metabase/oauth_server/api/admin_test.cljnew file mode 100644index 00000000000..bc1682fdc25--- /dev/null+++ b/test/metabase/oauth_server/api/admin_test.clj@@ -0,0 +1,157 @@+(ns metabase.oauth-server.api.admin-test+ (:require+ [clojure.test :refer [deftest is testing]]+ [metabase.test :as mt]+ [oidc-provider.util :as oidc-util]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++(defn- client-defaults []+ {:client_id (str (random-uuid))+ :client_type "confidential"+ :client_secret_hash (oidc-util/hash-client-secret (oidc-util/generate-client-secret))+ :redirect_uris ["https://example.com/callback"]+ :client_name "Test Auth Client"+ :grant_types ["authorization_code" "refresh_token"]+ :response_types ["code"]+ :scopes ["profile"]+ :application_type "web"+ :registration_type "dynamic"})++(defn- event-defaults+ ([oauth-client-id event-type]+ (event-defaults oauth-client-id event-type nil))+ ([oauth-client-id event-type user-id]+ (cond-> {:oauth_client_id oauth-client-id+ :event_type event-type}+ user-id (assoc :user_id user-id))))++;;; ----------------------------------------- GET /api/oauth/authorizations ----------------------------------------++(deftest authorizations-requires-superuser-test+ (testing "Non-admin gets 403"+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :get 403 "oauth/authorizations")))))++(deftest authorizations-response-shape-test+ (testing "Response has the expected pagination shape"+ (let [response (mt/user-http-request :crowberto :get 200 "oauth/authorizations")]+ (is (number? (:total response)))+ (is (sequential? (:data response)))+ (is (pos-int? (:limit response)))+ (is (number? (:offset response))))))++(deftest authorizations-returns-events-test+ (testing "Registration and decision events are returned with client info"+ (mt/with-temp [:model/OAuthClient client (merge (client-defaults)+ {:client_name "My MCP Client"+ :client_uri "https://mcp.example.com"})+ :model/OAuthClientEvent registered (event-defaults (:id client) "registered")+ :model/OAuthClientEvent approved (event-defaults (:id client) "approved" (mt/user->id :crowberto))+ :model/OAuthClientEvent denied (event-defaults (:id client) "denied" (mt/user->id :rasta))]+ (let [response (mt/user-http-request :crowberto :get 200 "oauth/authorizations"+ :client-id (:client_id client))+ ids (set (map :id (:data response)))]+ (is (= 3 (:total response)))+ (is (= #{(:id registered) (:id approved) (:id denied)} ids))+ (is (= #{"registered" "approved" "denied"} (set (map :event_type (:data response)))))+ (doseq [row (:data response)]+ (is (= "My MCP Client" (:client_name row)))+ (is (= "https://mcp.example.com" (:client_uri row)))+ (is (= ["https://example.com/callback"] (:redirect_uris row))+ "redirect_uris is decoded from JSON into a vector")+ (is (= (:client_id client) (:client_id row)))+ (is (= (:id client) (:oauth_client_id row))))))))++(deftest authorizations-decision-events-have-user-test+ (testing "Decision events expose the deciding user; registration events have no user"+ (mt/with-temp [:model/OAuthClient client (client-defaults)+ :model/OAuthClientEvent _registered (event-defaults (:id client) "registered")+ :model/OAuthClientEvent _approved (event-defaults (:id client) "approved" (mt/user->id :crowberto))]+ (let [rows (:data (mt/user-http-request :crowberto :get 200 "oauth/authorizations"+ :client-id (:client_id client)))+ by-typ (into {} (map (juxt :event_type identity)) rows)]+ (is (= (mt/user->id :crowberto) (:user_id (get by-typ "approved"))))+ (is (some? (:user_email (get by-typ "approved"))))+ (is (nil? (:user_id (get by-typ "registered"))))+ (is (nil? (:user_email (get by-typ "registered"))))))))++(deftest authorizations-filter-by-event-type-test+ (testing "Can filter by event-type=approved"+ (mt/with-temp [:model/OAuthClient client (client-defaults)+ :model/OAuthClientEvent _registered (event-defaults (:id client) "registered")+ :model/OAuthClientEvent _approved (event-defaults (:id client) "approved" (mt/user->id :crowberto))+ :model/OAuthClientEvent _denied (event-defaults (:id client) "denied" (mt/user->id :rasta))]+ (let [response (mt/user-http-request :crowberto :get 200 "oauth/authorizations"+ :client-id (:client_id client)+ :event-type "approved")]+ (is (= 1 (:total response)))+ (is (= "approved" (:event_type (first (:data response)))))))))++(deftest authorizations-filter-by-client-id-test+ (testing "Can filter by client-id"+ (mt/with-temp [:model/OAuthClient client-a (merge (client-defaults) {:client_name "Client A"})+ :model/OAuthClient client-b (merge (client-defaults) {:client_name "Client B"})+ :model/OAuthClientEvent _a (event-defaults (:id client-a) "registered")+ :model/OAuthClientEvent _b (event-defaults (:id client-b) "registered")]+ (let [response (mt/user-http-request :crowberto :get 200 "oauth/authorizations"+ :client-id (:client_id client-a))]+ (is (= 1 (:total response)))+ (is (= "Client A" (:client_name (first (:data response)))))))))++(deftest authorizations-ordered-by-created-at-desc-test+ (testing "Results are ordered by created_at descending"+ (mt/with-temp [:model/OAuthClient client (client-defaults)+ :model/OAuthClientEvent _first (event-defaults (:id client) "registered")]+ ;; Insert second event after a short delay so created_at differs+ (Thread/sleep 50)+ (mt/with-temp [:model/OAuthClientEvent _second (event-defaults (:id client) "approved" (mt/user->id :crowberto))]+ (let [rows (:data (mt/user-http-request :crowberto :get 200 "oauth/authorizations"+ :client-id (:client_id client)))]+ (is (= 2 (count rows)))+ (is (= "approved" (:event_type (first rows))))+ (is (= "registered" (:event_type (second rows)))))))))++(deftest authorizations-pagination-test+ (testing "Pagination works with limit and offset"+ (mt/with-temp [:model/OAuthClient client (client-defaults)+ :model/OAuthClientEvent _a (event-defaults (:id client) "registered")+ :model/OAuthClientEvent _b (event-defaults (:id client) "approved" (mt/user->id :crowberto))+ :model/OAuthClientEvent _c (event-defaults (:id client) "denied" (mt/user->id :crowberto))]+ (let [response (mt/user-http-request :crowberto :get 200 "oauth/authorizations"+ :client-id (:client_id client)+ :limit 2 :offset 0)]+ (is (= 3 (:total response)))+ (is (= 2 (count (:data response))))+ (is (= 2 (:limit response)))+ (is (= 0 (:offset response))))+ (let [response (mt/user-http-request :crowberto :get 200 "oauth/authorizations"+ :client-id (:client_id client)+ :limit 2 :offset 2)]+ (is (= 3 (:total response)))+ (is (= 1 (count (:data response))))))))++(deftest authorizations-retains-events-for-deleted-client-test+ (testing "Events whose client has been deleted still surface (LEFT JOIN), with null client fields"+ (mt/with-temp [:model/OAuthClient client (client-defaults)+ :model/OAuthClientEvent event (event-defaults (:id client) "registered")]+ (t2/delete! :model/OAuthClient (:id client))+ (let [rows (:data (mt/user-http-request :crowberto :get 200 "oauth/authorizations"))+ row (first (filter #(= (:id event) (:id %)) rows))]+ (is (some? row) "The orphaned audit event should still be returned")+ (is (= "registered" (:event_type row)))+ (is (nil? (:oauth_client_id row)))+ (is (nil? (:client_id row)))+ (is (nil? (:client_name row)))+ (is (nil? (:redirect_uris row)))))))++(deftest authorizations-does-not-leak-sensitive-fields-test+ (testing "Response does not include secrets or token-endpoint auth details"+ (mt/with-temp [:model/OAuthClient client (client-defaults)+ :model/OAuthClientEvent _registered (event-defaults (:id client) "registered")]+ (let [row (first (:data (mt/user-http-request :crowberto :get 200 "oauth/authorizations"+ :client-id (:client_id client))))]+ (is (nil? (:client_secret_hash row)))+ (is (nil? (:registration_access_token_hash row)))+ (is (nil? (:token_endpoint_auth_method row)))))))diff --git a/test/metabase/oauth_server/api_test.clj b/test/metabase/oauth_server/api_test.cljindex df861a6e3ea..ebc2a10476c 100644--- a/test/metabase/oauth_server/api_test.clj+++ b/test/metabase/oauth_server/api_test.clj@@ -135,6 +135,18 @@db-client (t2/select-one :model/OAuthClient :client_id client-id)](is (= "dynamic" (:registration_type db-client))))))))+(deftest dynamic-register-records-registered-event-test+ (testing "POST /oauth/register records a `registered` audit event with no user for the new client"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"+ oauth-server-dynamic-registration-enabled true]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [response (register-client! {:redirect_uris ["https://example.com/callback"]})+ client-pk (t2/select-one-pk :model/OAuthClient :client_id (:client_id response))+ events (t2/select :model/OAuthClientEvent :oauth_client_id client-pk)]+ (is (= 1 (count events)) "Exactly one client event row should have been created")+ (is (= "registered" (:event_type (first events))))+ (is (nil? (:user_id (first events)))))))))+(deftest dynamic-client-read-valid-test(testing "GET /oauth/register/:client-id with valid registration_access_token returns 200"(mt/with-temporary-setting-values [site-url "http://localhost:3000"@@ -396,6 +408,47 @@(is (str/includes? location "error=access_denied"))(is (str/includes? location "state=test-state")))))))+(defn- approve-or-deny!+ "Drive the consent + decision flow for `client-id` and return the decision response.+ `approved?` chooses approve vs deny."+ [user client-id approved?]+ (let [consent-resp (get-consent-page! user client-id)+ consent-body (:body consent-resp)]+ (form-post-decision!+ user+ {:approved (str approved?)+ :csrf_token (extract-csrf-token-from-consent consent-body)+ :params_sig (extract-params-sig-from-consent consent-body)+ :client_id client-id+ :redirect_uri "https://example.com/callback"+ :response_type "code"+ :scope "profile"+ :state "test-state"}+ 302+ :csrf-cookie (extract-csrf-cookie consent-resp))))++(deftest authorize-decision-records-approved-event-test+ (testing "Approving a registration records a separate `approved` event stamped with the deciding user"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [client (create-test-client!)]+ (approve-or-deny! :crowberto (:client_id client) true)+ (let [events (t2/select :model/OAuthClientEvent :oauth_client_id (:id client))]+ (is (= 1 (count events)))+ (is (= "approved" (:event_type (first events))))+ (is (= (mt/user->id :crowberto) (:user_id (first events))))))))))++(deftest authorize-decision-records-denied-event-test+ (testing "Denying a registration records a separate `denied` event stamped with the deciding user"+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (t2/with-transaction [_conn nil {:rollback-only true}]+ (let [client (create-test-client!)]+ (approve-or-deny! :crowberto (:client_id client) false)+ (let [events (t2/select :model/OAuthClientEvent :oauth_client_id (:id client))]+ (is (= 1 (count events)))+ (is (= "denied" (:event_type (first events))))+ (is (= (mt/user->id :crowberto) (:user_id (first events))))))))))+(deftest authorize-decision-csrf-missing-test(testing "POST /oauth/authorize/decision without CSRF token returns 403"(mt/with-temporary-setting-values [site-url "http://localhost:3000"]