World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#15143] feat(web-v2): Add the MCP gateway pages to the web UI (#15108)
Bharath Krishna18de8fcc3d4c
diff --git a/docs/webui-v2.md b/docs/webui-v2.mdindex 73d4842925..067e9bf81c 100644--- a/docs/webui-v2.md+++ b/docs/webui-v2.md@@ -371,3 +371,41 @@ Overview for Access Roles in the Web V2.Click **Create Role** to open the create form. A role can include multiple securable objects. Different securable object types have different available privileges. For details, see [Access control](security/access-control.md).++### MCP++The **MCP** section manages the+[Apache Gravitino MCP Gateway](https://github.com/apache/gravitino-mcp-gateway/blob/main/docs/gravitino-mcp-gateway.md),+which controls who may use which MCP servers and keeps an audit log of their calls. It appears+when Gravitino signs people in with OIDC and `conf/gravitino.conf` names the gateway:++```text+gravitino.mcpGateway.uri = https://mcp-gateway.example.com+gravitino.server.visibleConfigs = gravitino.mcpGateway.uri+```++Use an https URL, or http on `localhost`, because the browser sends each person's token there. If+`gravitino.server.visibleConfigs` already lists keys, add `gravitino.mcpGateway.uri` to them.++The web UI calls the gateway from the browser with the person's Gravitino sign-in, so the gateway+must accept it:++- The web UI's tokens must carry the gateway's `JWT_AUDIENCE`.+- The web UI's OAuth client, `gravitino.authenticator.oauth.clientId`, must be in the gateway's+ `GATEWAY_OAUTH_ADDITIONAL_CLIENT_IDS`, unless the gateway sets `GATEWAY_OAUTH_ACCEPT_ANY_CLIENT`.+- The web UI's origin must be in the gateway's `CORS_ALLOWED_ORIGINS`.+- The gateway's `GRAVITINO_URI` should point at Gravitino, so that Gravitino's service admins are+ the gateway's admins too.++The pages are:++- **My Servers** lists the gateway's MCP servers, with your access to each and the URL MCP+ clients use. Ask for access, read an admin's note on a denied request, or connect to and+ disconnect from a server that has its own sign-in.+- **Manage Servers** (gateway admins): register MCP servers, and edit, deactivate or delete them.+- **Access Requests** (gateway admins): approve or deny requests, and revoke granted access.+- **Audit Log** lists the calls you made through the gateway, including the ones it refused+ because you lacked access. Gateway admins see everyone's calls, people's and service accounts',+ and can narrow the list to one account. Export the list as CSV.+- **Service Accounts** (gateway admins): register the workloads that call MCP servers with their+ GKE, GCE or EKS identity, choose the servers each may call, and delete them.diff --git a/web-v2/web/src/app/mcp/McpGatewayProvider.js b/web-v2/web/src/app/mcp/McpGatewayProvider.jsnew file mode 100644index 0000000000..c1fd19bdff--- /dev/null+++ b/web-v2/web/src/app/mcp/McpGatewayProvider.js@@ -0,0 +1,134 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++'use client'++import { createContext, useContext, useEffect, useMemo, useState } from 'react'+import { useRouter } from 'next/navigation'+import { Button, Result, Spin } from 'antd'+import SectionContainer from '@/components/SectionContainer'+import {+ MCP_GATEWAY_URI_KEY,+ createMcpGatewayApi,+ gatewayErrorMessage,+ isOidcSignIn,+ isSignedOut+} from '@/lib/api/mcpGateway'+import { useAppSelector } from '@/lib/hooks/useStore'++const McpGatewayContext = createContext(null)++// The gateway's API, and the signed-in user as the gateway knows them.+export const useMcpGateway = () => useContext(McpGatewayContext)++// Wraps the pages for the gateway's admins: Gravitino's service admins, when the gateway+// knows Gravitino (GRAVITINO_URI), and the people in its ADMIN_EMAILS.+export const AdminOnly = ({ children }) => {+ const { me } = useMcpGateway()++ return me.is_admin ? children : <Result status='403' title='Only MCP gateway admins can use this page' />+}++export default function McpGatewayProvider({ children }) {+ const router = useRouter()+ const { systemConfig, authType } = useAppSelector(state => state.auth)+ const gatewayUri = systemConfig?.[MCP_GATEWAY_URI_KEY]+ const oidc = isOidcSignIn(systemConfig, authType)++ // A call that finds nobody signed in, on any page, goes back to the login page.+ const [api, uriError] = useMemo(() => {+ try {+ return [gatewayUri ? createMcpGatewayApi(gatewayUri, undefined, () => router.push('/login')) : null, undefined]+ } catch (err) {+ return [null, err.message]+ }+ }, [gatewayUri, router])+ const [me, setMe] = useState()+ const [error, setError] = useState()+ const [attempt, setAttempt] = useState(0)+ const value = useMemo(() => ({ api, me }), [api, me])++ useEffect(() => {+ if (!api || !oidc) {+ return+ }++ // Ignore an answer that comes after the gateway or the sign-in changed.+ let current = true+ api+ .getMe()+ .then(user => current && setMe(user))+ .catch(err => {+ if (current && !isSignedOut(err)) {+ setError(gatewayErrorMessage(err))+ }+ })++ return () => {+ current = false+ }+ }, [api, oidc, attempt])++ let unavailable = null+ if (systemConfig && !gatewayUri) {+ unavailable = (+ <Result+ status='info'+ title='The MCP gateway is not set up'+ subTitle={`Set ${MCP_GATEWAY_URI_KEY} on the Gravitino server and list it in gravitino.server.visibleConfigs.`}+ />+ )+ } else if (uriError) {+ unavailable = <Result status='error' title='The MCP gateway is not set up' subTitle={uriError} />+ } else if (systemConfig && !oidc) {+ unavailable = (+ <Result+ status='info'+ title='MCP servers need an OIDC sign-in'+ subTitle='The MCP gateway accepts the token of an OIDC sign-in to Gravitino, and no other.'+ />+ )+ } else if (error) {+ unavailable = (+ <Result+ status='error'+ title='The MCP gateway is unavailable'+ subTitle={error}+ extra={+ <Button+ onClick={() => {+ setError(undefined)+ setAttempt(n => n + 1)+ }}+ >+ Retry+ </Button>+ }+ />+ )+ } else if (!me) {+ unavailable = <Spin className='mt-20 w-full' />+ }++ if (unavailable) {+ return <SectionContainer classProps='block overflow-y-auto'>{unavailable}</SectionContainer>+ }++ return <McpGatewayContext.Provider value={value}>{children}</McpGatewayContext.Provider>+}diff --git a/web-v2/web/src/app/mcp/McpGatewayProvider.test.js b/web-v2/web/src/app/mcp/McpGatewayProvider.test.jsnew file mode 100644index 0000000000..077e2b89c1--- /dev/null+++ b/web-v2/web/src/app/mcp/McpGatewayProvider.test.js@@ -0,0 +1,148 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++import { act, createElement } from 'react'+import { createRoot } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++const store = { auth: {} }+const getMe = vi.fn()+const gateway = vi.hoisted(() => ({ onSignedOut: undefined }))++// Next.js returns the same router on every render.+const router = vi.hoisted(() => ({ push: vi.fn() }))+vi.mock('next/navigation', () => ({ useRouter: () => router }))+vi.mock('@/lib/hooks/useStore', () => ({ useAppSelector: select => select(store) }))+vi.mock('@/components/SectionContainer', () => ({ default: ({ children }) => children }))+vi.mock('@/lib/api/mcpGateway', async importOriginal => ({+ ...(await importOriginal()),+ createMcpGatewayApi: (uri, getAccessToken, onSignedOut) => {+ gateway.onSignedOut = onSignedOut++ return { getMe }+ }+}))++const { default: McpGatewayProvider, AdminOnly } = await import('./McpGatewayProvider')++let container+let root++const show = children =>+ act(async () => {+ root.render(createElement(McpGatewayProvider, null, children))+ })++const page = createElement(AdminOnly, null, 'admin page')++beforeEach(() => {+ globalThis.IS_REACT_ACT_ENVIRONMENT = true+ getMe.mockReset()+ router.push.mockReset()+ container = document.createElement('div')+ root = createRoot(container)+ store.auth = {+ authType: 'oauth',+ systemConfig: {+ 'gravitino.mcpGateway.uri': 'https://gw.example.com',+ 'gravitino.authenticator.oauth.provider': 'oidc'+ }+ }+})++afterEach(() => act(() => root.unmount()))++describe('AdminOnly', () => {+ it('shows the page to a gateway admin', async () => {+ getMe.mockResolvedValue({ username: 'alice', is_admin: true })++ await show(page)++ expect(container.textContent).toBe('admin page')+ })++ it('shows anyone else that the page is for admins', async () => {+ getMe.mockResolvedValue({ username: 'bob', is_admin: false })++ await show(page)++ expect(container.textContent).not.toContain('admin page')+ expect(container.textContent).toContain('Only MCP gateway admins can use this page')+ })+})++describe('McpGatewayProvider', () => {+ it('says the gateway is not set up when Gravitino names none', async () => {+ store.auth = { authType: 'oauth', systemConfig: {} }++ await show(page)++ expect(container.textContent).toContain('The MCP gateway is not set up')+ })++ it('needs an OIDC sign-in to Gravitino', async () => {+ store.auth = { ...store.auth, authType: 'simple' }++ await show(page)++ expect(container.textContent).toContain('MCP servers need an OIDC sign-in')+ expect(getMe).not.toHaveBeenCalled()+ })++ it("doesn't send the token of another OAuth sign-in to the gateway", async () => {+ store.auth = {+ ...store.auth,+ systemConfig: { ...store.auth.systemConfig, 'gravitino.authenticator.oauth.provider': 'default' }+ }++ await show(page)++ expect(container.textContent).toContain('MCP servers need an OIDC sign-in')+ expect(getMe).not.toHaveBeenCalled()+ })++ it('goes to the login page when a call finds nobody signed in', async () => {+ getMe.mockResolvedValue({ is_admin: true })+ await show(page)++ // As when renewing the sign-in fails after the pages have loaded.+ gateway.onSignedOut()++ expect(router.push).toHaveBeenCalledWith('/login')+ })++ it('says the gateway is unavailable when it does not answer', async () => {+ getMe.mockRejectedValue(new Error('Network Error'))++ await show(page)++ expect(container.textContent).toContain('The MCP gateway is unavailable')+ })++ it('tries the gateway again on Retry', async () => {+ getMe.mockRejectedValueOnce(new Error('Network Error')).mockResolvedValue({ is_admin: true })+ await show(page)++ const retry = [...container.querySelectorAll('button')].find(b => b.textContent === 'Retry')+ await act(async () => retry.click())++ expect(getMe).toHaveBeenCalledTimes(2)+ expect(container.textContent).toBe('admin page')+ })+})diff --git a/web-v2/web/src/app/mcp/McpNav.js b/web-v2/web/src/app/mcp/McpNav.jsnew file mode 100644index 0000000000..4a6d01173a--- /dev/null+++ b/web-v2/web/src/app/mcp/McpNav.js@@ -0,0 +1,59 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++'use client'++import { Menu } from 'antd'+import { usePathname, useRouter, useSearchParams } from 'next/navigation'+import { ROUTES } from '@/config/routes'+import { useMcpGateway } from './McpGatewayProvider'++export default function McpNav() {+ const router = useRouter()+ const pathname = usePathname()+ const currentMetalake = useSearchParams().get('metalake')+ const { me } = useMcpGateway()++ const items = [+ { key: ROUTES.Mcp, label: 'My Servers' },+ { key: ROUTES.McpAudit, label: 'Audit Log' },+ ...(me.is_admin+ ? [+ { key: ROUTES.McpServers, label: 'Manage Servers' },+ { key: ROUTES.McpAccessRequests, label: 'Access Requests' },+ { key: ROUTES.McpServiceAccounts, label: 'Service Accounts' }+ ]+ : [])+ ]++ const onClick = ({ key }) => {+ router.push(currentMetalake ? `${key}?metalake=${currentMetalake}` : key)+ }++ return (+ <Menu+ mode='inline'+ onClick={onClick}+ selectedKeys={[pathname]}+ style={{ width: 200 }}+ className='h-full'+ items={items}+ />+ )+}diff --git a/web-v2/web/src/app/mcp/RequestAccessDialog.js b/web-v2/web/src/app/mcp/RequestAccessDialog.jsnew file mode 100644index 0000000000..507874ad55--- /dev/null+++ b/web-v2/web/src/app/mcp/RequestAccessDialog.js@@ -0,0 +1,68 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++'use client'++import { useState } from 'react'+import { Form, Input, Modal } from 'antd'+import toast from 'react-hot-toast'+import { gatewayErrorMessage } from '@/lib/api/mcpGateway'+import { useMcpGateway } from './McpGatewayProvider'++export default function RequestAccessDialog({ server, onClose, onRequested }) {+ const { api } = useMcpGateway()+ const [form] = Form.useForm()+ const [submitting, setSubmitting] = useState(false)++ const submit = async () => {+ const values = await form.validateFields().catch(() => null)+ if (!values) return+ setSubmitting(true)+ try {+ await api.requestAccess(server.id, values.justification)+ toast.success(`Requested access to ${server.name}`)+ onRequested()+ } catch (error) {+ toast.error(gatewayErrorMessage(error))+ } finally {+ setSubmitting(false)+ }+ }++ return (+ <Modal+ open+ title={`Request access to ${server.name}`}+ okText='Request'+ confirmLoading={submitting}+ onOk={submit}+ onCancel={onClose}+ >+ <Form form={form} layout='vertical'>+ <Form.Item+ name='justification'+ label='Why do you need access?'+ rules={[{ required: true, whitespace: true, message: 'Tell an admin why you need access' }]}+ >+ <Input.TextArea rows={4} maxLength={1000} />+ </Form.Item>+ </Form>+ </Modal>+ )+}diff --git a/web-v2/web/src/app/mcp/accessRequests/ReviewDialog.js b/web-v2/web/src/app/mcp/accessRequests/ReviewDialog.jsnew file mode 100644index 0000000000..f59c122725--- /dev/null+++ b/web-v2/web/src/app/mcp/accessRequests/ReviewDialog.js@@ -0,0 +1,76 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++'use client'++import { useState } from 'react'+import { Form, Input, InputNumber, Modal } from 'antd'+import toast from 'react-hot-toast'+import { gatewayErrorMessage } from '@/lib/api/mcpGateway'+import { useMcpGateway } from '../McpGatewayProvider'++// Approves (`status` 'approved') or denies a request for access to an MCP server.+export default function ReviewDialog({ request, status, onClose, onReviewed }) {+ const { api } = useMcpGateway()+ const [form] = Form.useForm()+ const [saving, setSaving] = useState(false)+ const approving = status === 'approved'++ const submit = async () => {+ const values = await form.validateFields().catch(() => null)+ if (!values) return+ setSaving(true)+ try {+ await api.reviewRequest(request.id, { status, ...values })+ toast.success(`${approving ? 'Approved' : 'Denied'} access for ${request.username} to ${request.mcp_name}`)+ onReviewed()+ } catch (error) {+ toast.error(gatewayErrorMessage(error))+ } finally {+ setSaving(false)+ }+ }++ return (+ <Modal+ open+ title={`${approving ? 'Approve' : 'Deny'} access for ${request.username} to ${request.mcp_name}`}+ okText={approving ? 'Approve' : 'Deny'}+ okButtonProps={{ danger: !approving }}+ confirmLoading={saving}+ onOk={submit}+ onCancel={onClose}+ >+ <Form form={form} layout='vertical'>+ {approving && (+ <Form.Item+ name='expires_in_days'+ label='Expires after (days)'+ extra='Leave empty for access that does not expire.'+ >+ <InputNumber min={1} max={3650} className='w-full' />+ </Form.Item>+ )}+ <Form.Item name='admin_notes' label='Note to the user'>+ <Input.TextArea rows={3} maxLength={1000} />+ </Form.Item>+ </Form>+ </Modal>+ )+}diff --git a/web-v2/web/src/app/mcp/accessRequests/page.js b/web-v2/web/src/app/mcp/accessRequests/page.jsnew file mode 100644index 0000000000..0a89a2f4f4--- /dev/null+++ b/web-v2/web/src/app/mcp/accessRequests/page.js@@ -0,0 +1,245 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++'use client'++import { useCallback, useState } from 'react'+import { Button, Flex, Popconfirm, Spin, Table, Tabs, Tag, Typography } from 'antd'+import toast from 'react-hot-toast'+import SectionContainer from '@/components/SectionContainer'+import { gatewayErrorMessage } from '@/lib/api/mcpGateway'+import { formatToDateTime } from '@/lib/utils/date'+import { gatewayDate } from '@/lib/utils/mcpAccess'+import { useMcpGateway, AdminOnly } from '../McpGatewayProvider'+import useLastPageWhenEmpty from '../useLastPageWhenEmpty'+import useLatestResult from '../useLatestResult'+import ReviewDialog from './ReviewDialog'++const { Title, Paragraph, Text } = Typography++const STATUS_COLORS = { pending: 'gold', approved: 'green', denied: 'red' }++const NO_ROWS = { items: [], total: 0 }++const when = value => (value ? formatToDateTime(gatewayDate(value)) : '-')++const hasExpired = permission => Boolean(permission.expires_at) && gatewayDate(permission.expires_at) < new Date()++export default function AccessRequestsPage() {+ return (+ <AdminOnly>+ <AccessRequests />+ </AdminOnly>+ )+}++function AccessRequests() {+ const { api } = useMcpGateway()+ const [tab, setTab] = useState('pending')+ const [page, setPage] = useState({ current: 1, pageSize: 25 })+ const [review, setReview] = useState()+ const [reloads, setReloads] = useState(0)+ const load = () => setReloads(count => count + 1)++ // Only the answer for this tab and page is shown, however the answers arrive.+ const { loading, result: data = NO_ROWS } = useLatestResult(+ useCallback(() => {+ const fetchPage = { pending: api.getPendingRequests, all: api.getAllRequests, granted: api.getPermissions }[tab]++ return fetchPage(page.current, page.pageSize)+ }, [api, tab, page, reloads]),+ `${tab}:${page.current}:${page.pageSize}`+ )+ useLastPageWhenEmpty(loading, data.items.length, data.total, page, setPage)++ const revoke = async permission => {+ try {+ await api.revokePermission(permission.id)+ toast.success(`Revoked ${permission.username}'s access to ${permission.mcp_name}`)+ load()+ } catch (error) {+ toast.error(gatewayErrorMessage(error))+ }+ }++ const grantedColumns = [+ {+ title: 'User',+ key: 'user',+ width: 220,+ render: (_, permission) => (+ <>+ <div>{permission.username}</div>+ {permission.email && permission.email !== permission.username && (+ <Text type='secondary'>{permission.email}</Text>+ )}+ </>+ )+ },+ {+ title: 'Server',+ key: 'server',+ width: 200,+ render: (_, permission) => `${permission.mcp_icon || ''} ${permission.mcp_name}`+ },+ {+ title: 'Granted',+ key: 'granted',+ render: (_, permission) =>+ permission.granted_by+ ? `${when(permission.granted_at)} by ${permission.granted_by}`+ : when(permission.granted_at)+ },+ {+ title: 'Expires',+ key: 'expires',+ width: 220,+ render: (_, permission) => (+ <Flex gap='small' align='center'>+ {permission.expires_at ? when(permission.expires_at) : 'Never'}+ {hasExpired(permission) && <Tag>Expired</Tag>}+ </Flex>+ )+ },+ {+ title: 'Actions',+ key: 'actions',+ width: 110,+ fixed: 'right',+ render: (_, permission) => (+ <Popconfirm+ title={`Revoke ${permission.username}'s access to ${permission.mcp_name}?`}+ description='They can no longer use the server unless it is open to everyone.'+ okText='Revoke'+ okButtonProps={{ danger: true }}+ onConfirm={() => revoke(permission)}+ >+ <Button size='small' danger>+ Revoke+ </Button>+ </Popconfirm>+ )+ }+ ]++ const requestColumns = [+ { title: 'User', dataIndex: 'username', key: 'user', width: 160 },+ {+ title: 'Server',+ key: 'server',+ width: 200,+ render: (_, request) => `${request.mcp_icon || ''} ${request.mcp_name}`+ },+ {+ title: 'Justification',+ dataIndex: 'justification',+ key: 'justification',+ render: value => <Text ellipsis={{ tooltip: value }}>{value || '-'}</Text>+ },+ { title: 'Requested', key: 'requested', width: 180, render: (_, request) => when(request.requested_at) }+ ]++ const actionsColumn = {+ title: 'Actions',+ key: 'actions',+ width: 180,+ fixed: 'right',+ render: (_, request) => (+ <Flex gap='small'>+ <Button size='small' type='primary' onClick={() => setReview({ request, status: 'approved' })}>+ Approve+ </Button>+ <Button size='small' danger onClick={() => setReview({ request, status: 'denied' })}>+ Deny+ </Button>+ </Flex>+ )+ }++ const reviewColumns = [+ {+ title: 'Status',+ dataIndex: 'status',+ key: 'status',+ width: 110,+ render: value => <Tag color={STATUS_COLORS[value]}>{value}</Tag>+ },+ {+ title: 'Reviewed',+ key: 'reviewed',+ width: 220,+ render: (_, request) =>+ request.reviewed_at ? `${when(request.reviewed_at)} by ${request.reviewer_username || '-'}` : '-'+ },+ {+ title: 'Note',+ dataIndex: 'admin_notes',+ key: 'note',+ render: value => <Text ellipsis={{ tooltip: value }}>{value || '-'}</Text>+ }+ ]+ const columns = tab === 'pending' ? [...requestColumns, actionsColumn] : [...requestColumns, ...reviewColumns]++ return (+ <SectionContainer classProps='block overflow-y-auto'>+ <Title level={2}>Access Requests</Title>+ <Paragraph type='secondary'>+ Requests from users for access to MCP servers that require approval, and the access they have been granted.+ </Paragraph>+ <Tabs+ activeKey={tab}+ onChange={key => {+ setTab(key)+ setPage(current => ({ ...current, current: 1 }))+ }}+ items={[+ { key: 'pending', label: 'Pending' },+ { key: 'all', label: 'All' },+ { key: 'granted', label: 'Granted' }+ ]}+ />+ <Spin spinning={loading}>+ <Table+ dataSource={data.items.map(item => ({ ...item, key: item.id }))}+ columns={tab === 'granted' ? grantedColumns : columns}+ tableLayout='fixed'+ scroll={{ x: 960 }}+ pagination={{+ ...page,+ total: data.total,+ position: ['bottomCenter'],+ showSizeChanger: true,+ onChange: (current, pageSize) => setPage({ current, pageSize })+ }}+ />+ </Spin>+ {review && (+ <ReviewDialog+ request={review.request}+ status={review.status}+ onClose={() => setReview(undefined)}+ onReviewed={() => {+ setReview(undefined)+ load()+ }}+ />+ )}+ </SectionContainer>+ )+}diff --git a/web-v2/web/src/app/mcp/audit/AuditDetail.js b/web-v2/web/src/app/mcp/audit/AuditDetail.jsnew file mode 100644index 0000000000..372e11916d--- /dev/null+++ b/web-v2/web/src/app/mcp/audit/AuditDetail.js@@ -0,0 +1,105 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++'use client'++import { useEffect, useState } from 'react'+import { Descriptions, Drawer, Spin, Tag, Typography } from 'antd'+import toast from 'react-hot-toast'+import { gatewayErrorMessage } from '@/lib/api/mcpGateway'+import { formatToDateTime } from '@/lib/utils/date'+import { gatewayDate } from '@/lib/utils/mcpAccess'+import { useMcpGateway } from '../McpGatewayProvider'++const { Text } = Typography++export const STATUS_COLORS = { success: 'green', error: 'red', unauthorized: 'orange', cancelled: 'default' }++// A successful call's response is kept only when the gateway runs with AUDIT_LOG_RESPONSES.+const RESPONSE_NOT_KEPT = 'Not kept. The gateway keeps responses only when AUDIT_LOG_RESPONSES is set.'++function Json({ value, empty = '-' }) {+ if (value === null || value === undefined || (typeof value === 'object' && !Object.keys(value).length)) {+ return <Text type='secondary'>{empty}</Text>+ }++ return (+ <pre className='m-0 max-h-80 overflow-auto whitespace-pre-wrap break-all rounded bg-gray-50 p-2 text-xs'>+ {JSON.stringify(value, null, 2)}+ </pre>+ )+}++// One audit log entry, with what was sent and what came back.+export default function AuditDetail({ logId, onClose }) {+ const { api } = useMcpGateway()+ const [log, setLog] = useState()++ useEffect(() => {+ // Ignore an answer that comes after this entry closed, so it can't close another.+ let current = true+ api+ .getAuditLog(logId)+ .then(entry => current && setLog(entry))+ .catch(error => {+ if (!current) return+ toast.error(gatewayErrorMessage(error))+ onClose()+ })++ return () => {+ current = false+ }+ }, [api, logId, onClose])++ return (+ <Drawer open width={640} title={log ? `${log.service} · ${log.tool_name}` : 'Call'} onClose={onClose}>+ {!log ? (+ <Spin className='w-full' />+ ) : (+ <Descriptions column={1} size='small' bordered>+ <Descriptions.Item label='Time'>{formatToDateTime(gatewayDate(log.created_at))}</Descriptions.Item>+ <Descriptions.Item label='Account'>{log.username}</Descriptions.Item>+ <Descriptions.Item label='Server'>{log.service}</Descriptions.Item>+ <Descriptions.Item label='Tool'>{log.tool_name}</Descriptions.Item>+ <Descriptions.Item label='Method'>{log.method}</Descriptions.Item>+ <Descriptions.Item label='Status'>+ <Tag color={STATUS_COLORS[log.status]}>{log.status}</Tag>+ </Descriptions.Item>+ <Descriptions.Item label='Duration'>+ {log.duration_ms === null ? '-' : `${log.duration_ms} ms`}+ </Descriptions.Item>+ {log.error_message && <Descriptions.Item label='Error'>{log.error_message}</Descriptions.Item>}+ <Descriptions.Item label='Arguments'>+ <Json value={log.request_params} />+ </Descriptions.Item>+ <Descriptions.Item label='Workload headers'>+ <Json value={log.request_headers} />+ </Descriptions.Item>+ <Descriptions.Item label='Response'>+ <Json value={log.response_data} empty={log.status === 'success' ? RESPONSE_NOT_KEPT : '-'} />+ </Descriptions.Item>+ <Descriptions.Item label='Client'>+ {[log.ip_address, log.user_agent].filter(Boolean).join(' · ') || '-'}+ </Descriptions.Item>+ </Descriptions>+ )}+ </Drawer>+ )+}diff --git a/web-v2/web/src/app/mcp/audit/AuditDetail.test.js b/web-v2/web/src/app/mcp/audit/AuditDetail.test.jsnew file mode 100644index 0000000000..aa7e6c9c0b--- /dev/null+++ b/web-v2/web/src/app/mcp/audit/AuditDetail.test.js@@ -0,0 +1,69 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++import { act, createElement } from 'react'+import { createRoot } from 'react-dom/client'+import { afterEach, beforeEach, expect, it, vi } from 'vitest'++const getAuditLog = vi.fn()+vi.mock('../McpGatewayProvider', () => ({ useMcpGateway: () => ({ api: { getAuditLog } }) }))+vi.mock('react-hot-toast', () => ({ default: { error: vi.fn() } }))++// The drawer itself isn't under test, and jsdom can't measure it.+vi.mock('antd', async importOriginal => ({ ...(await importOriginal()), Drawer: ({ children }) => children }))++const { default: AuditDetail } = await import('./AuditDetail')++let root+let fail++beforeEach(() => {+ globalThis.IS_REACT_ACT_ENVIRONMENT = true+ getAuditLog.mockReset().mockReturnValue(+ new Promise((_, reject) => {+ fail = reject+ })+ )+ root = createRoot(document.createElement('div'))+})++afterEach(() => act(() => root.unmount()))++const open = onClose => act(async () => root.render(createElement(AuditDetail, { logId: 7, onClose })))++it('closes when the entry fails to load', async () => {+ const onClose = vi.fn()+ await open(onClose)++ await act(async () => fail(new Error('Network Error')))++ expect(getAuditLog).toHaveBeenCalledWith(7)+ expect(onClose).toHaveBeenCalledTimes(1)+})++it("ignores a failure that comes after the entry closed, so it can't close the next one", async () => {+ const onClose = vi.fn()+ await open(onClose)+ act(() => root.unmount())+ root = createRoot(document.createElement('div'))++ await act(async () => fail(new Error('Network Error')))++ expect(onClose).not.toHaveBeenCalled()+})diff --git a/web-v2/web/src/app/mcp/audit/page.js b/web-v2/web/src/app/mcp/audit/page.jsnew file mode 100644index 0000000000..ade99c8ce1--- /dev/null+++ b/web-v2/web/src/app/mcp/audit/page.js@@ -0,0 +1,293 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++'use client'++import { useCallback, useEffect, useState } from 'react'+import { useSearchParams } from 'next/navigation'+import { DownloadOutlined, ReloadOutlined } from '@ant-design/icons'+import { Button, Card, Flex, Input, Select, Spin, Statistic, Table, Tag, Tooltip, Typography } from 'antd'+import toast from 'react-hot-toast'+import SectionContainer from '@/components/SectionContainer'+import { gatewayErrorMessage } from '@/lib/api/mcpGateway'+import { formatToDateTime } from '@/lib/utils/date'+import { gatewayDate } from '@/lib/utils/mcpAccess'+import {+ AUDIT_PERIODS,+ DEFAULT_AUDIT_PERIOD,+ EXPORT_ROW_LIMIT,+ auditFilterParams,+ auditLogParams,+ auditSummaryParams+} from '@/lib/utils/mcpAudit'+import { useMcpGateway } from '../McpGatewayProvider'+import useLastPageWhenEmpty from '../useLastPageWhenEmpty'+import useLatestResult from '../useLatestResult'+import AuditDetail, { STATUS_COLORS } from './AuditDetail'++const { Title, Paragraph } = Typography++const STATUSES = ['success', 'error', 'unauthorized', 'cancelled']++// How long the browser has to start a download before its object URL is revoked.+const DOWNLOAD_URL_LIFETIME_MS = 60 * 1000++// Starts a download of `blob` as `name`; the gateway's file needs the user's token, so a plain link won't do.+const download = (blob, name) => {+ const url = URL.createObjectURL(blob)+ const link = Object.assign(document.createElement('a'), { href: url, download: name })+ document.body.appendChild(link)+ link.click()+ link.remove()+ setTimeout(() => URL.revokeObjectURL(url), DOWNLOAD_URL_LIFETIME_MS)+}++export default function AuditLogPage() {+ // A link to one account's audit log starts the page afresh.+ return <AuditLog key={useSearchParams().get('user') || ''} />+}++function AuditLog() {+ const { api, me } = useMcpGateway()+ const searchParams = useSearchParams()++ const [filters, setFilters] = useState(() => ({+ period: DEFAULT_AUDIT_PERIOD,+ userId: me.is_admin ? Number(searchParams.get('user')) || undefined : undefined,+ userName: searchParams.get('name') || undefined,+ asOf: new Date()+ }))+ const [page, setPage] = useState({ current: 1, pageSize: 25 })+ const [services, setServices] = useState([])+ const [detail, setDetail] = useState()+ const [isExporting, setIsExporting] = useState(false)++ // A change of filters, or a refresh, goes back to the first page of the calls up to now.+ const filter = changes => {+ setFilters(current => ({ ...current, ...changes, asOf: new Date() }))+ setPage(current => ({ ...current, current: 1 }))+ }++ // What the list shows; a refresh reloads the same view.+ const view = JSON.stringify({ ...filters, period: filters.period.key, asOf: undefined })++ const logs = useLatestResult(+ useCallback(+ () => api.getAuditLogs(auditLogParams(filters, page.current, page.pageSize, filters.asOf)),+ [api, filters, page]+ ),+ `${view}:${page.current}:${page.pageSize}`+ )+ useLastPageWhenEmpty(logs.loading, logs.result?.logs?.length ?? 0, logs.result?.total ?? 0, page, setPage)++ const summary = useLatestResult(+ useCallback(() => api.getAuditSummary(auditSummaryParams(filters, filters.asOf)), [api, filters]),+ view+ )+ const closeDetail = useCallback(() => setDetail(undefined), [])++ useEffect(() => {+ const listServers = me.is_admin ? api.getServers() : api.getCatalog()+ listServers+ .then(list => setServices(list.map(server => server.service_id)))+ .catch(error => toast.error(`Could not list the servers: ${gatewayErrorMessage(error)}`))+ }, [api, me.is_admin])++ const exportCsv = async () => {+ setIsExporting(true)+ try {+ download(await api.exportAuditLogs(auditFilterParams(filters, filters.asOf)), 'mcp-gateway-audit.csv')+ const total = logs.result?.total ?? 0+ if (total > EXPORT_ROW_LIMIT) {+ toast(`The file holds the latest ${EXPORT_ROW_LIMIT.toLocaleString()} of ${total.toLocaleString()} calls.`)+ }+ } catch (error) {+ toast.error(gatewayErrorMessage(error))+ } finally {+ setIsExporting(false)+ }+ }++ const figures = summary.result+ const hasCalls = Boolean(figures?.total_calls)++ // Failed calls, refused ones and ones whose client left.+ const unsuccessful = figures ? figures.total_calls - figures.successful_calls : '-'++ const columns = [+ {+ title: 'Time',+ key: 'time',+ width: 180,+ render: (_, log) => formatToDateTime(gatewayDate(log.created_at))+ },+ {+ title: 'Account',+ key: 'account',+ width: 200,+ ellipsis: true,+ render: (_, log) =>+ me.is_admin ? (+ <Button+ type='link'+ size='small'+ className='h-auto p-0'+ title='Show only this account'+ onClick={() => filter({ userId: log.user_id, userName: log.username })}+ >+ {log.username}+ </Button>+ ) : (+ log.username+ )+ },+ { title: 'Server', dataIndex: 'service', key: 'service', width: 160, ellipsis: true },+ { title: 'Tool', dataIndex: 'tool_name', key: 'tool', ellipsis: { showTitle: true } },+ {+ title: 'Status',+ key: 'status',+ width: 120,+ render: (_, log) => (+ <Tooltip title={log.error_message}>+ <Tag color={STATUS_COLORS[log.status]}>{log.status}</Tag>+ </Tooltip>+ )+ },+ {+ title: 'Duration',+ key: 'duration',+ width: 110,+ render: (_, log) => (log.duration_ms === null ? '-' : `${log.duration_ms} ms`)+ },+ {+ title: <span className='sr-only'>Details</span>,+ key: 'details',+ width: 90,+ fixed: 'right',+ render: (_, log) => (+ <Button type='link' size='small' className='h-auto p-0' onClick={() => setDetail(log.id)}>+ Details+ </Button>+ )+ }+ ]++ return (+ <SectionContainer classProps='block overflow-y-auto'>+ <Title level={2}>Audit Log</Title>+ <Paragraph type='secondary'>+ {me.is_admin+ ? "Calls through the MCP gateway by people and service accounts, including the ones it refused, and admins' changes."+ : 'Your calls through the MCP gateway, including the ones it refused.'}+ </Paragraph>+ <Flex gap='middle' wrap className='mb-4'>+ <Card size='small'>+ <Statistic+ title={`Calls, ${filters.period.label.toLowerCase()}`}+ value={figures?.total_calls ?? '-'}+ loading={summary.loading}+ />+ </Card>+ <Card size='small'>+ <Statistic+ title='Succeeded'+ value={hasCalls ? figures.success_rate : '-'}+ suffix={hasCalls && '%'}+ loading={summary.loading}+ />+ </Card>+ <Card size='small'>+ <Statistic+ title='Average time'+ value={hasCalls ? Math.round(figures.average_response_time_ms) : '-'}+ suffix={hasCalls && 'ms'}+ loading={summary.loading}+ />+ </Card>+ <Card size='small'>+ <Statistic title='Not succeeded' value={unsuccessful} loading={summary.loading} />+ </Card>+ </Flex>+ <Flex gap='small' wrap align='center' className='mb-4'>+ <Select+ aria-label='Period'+ value={filters.period.key}+ style={{ width: 160 }}+ options={AUDIT_PERIODS.map(period => ({ value: period.key, label: period.label }))}+ onChange={key => filter({ period: AUDIT_PERIODS.find(period => period.key === key) })}+ />+ <Select+ allowClear+ showSearch+ aria-label='Server'+ placeholder='All servers'+ value={filters.service}+ style={{ width: 180 }}+ options={services.map(service => ({ value: service, label: service }))}+ onChange={service => filter({ service })}+ />+ <Select+ allowClear+ aria-label='Status'+ placeholder='Any status'+ value={filters.status}+ style={{ width: 140 }}+ options={STATUSES.map(status => ({ value: status, label: status }))}+ onChange={status => filter({ status })}+ />+ <Input.Search+ allowClear+ aria-label='Tool'+ placeholder='Exact tool name'+ style={{ width: 200 }}+ onSearch={tool => filter({ tool })}+ />+ {filters.userId && (+ <Tag closable onClose={() => filter({ userId: undefined, userName: undefined })}>+ Account: {filters.userName || filters.userId}+ </Tag>+ )}+ <Flex gap='small' className='ml-auto'>+ <Button icon={<ReloadOutlined />} onClick={() => filter({})}>+ Refresh+ </Button>+ <Button icon={<DownloadOutlined />} loading={isExporting} onClick={exportCsv}>+ Export CSV+ </Button>+ </Flex>+ </Flex>+ <Spin spinning={logs.loading}>+ <Table+ dataSource={(logs.result?.logs ?? []).map(log => ({ ...log, key: log.id }))}+ columns={columns}+ tableLayout='fixed'+ scroll={{ x: 960 }}+ pagination={{+ ...page,+ total: logs.result?.total ?? 0,+ position: ['bottomCenter'],+ showSizeChanger: true,+ onChange: (current, pageSize) => setPage({ current, pageSize })+ }}+ />+ </Spin>+ {detail && <AuditDetail logId={detail} onClose={closeDetail} />}+ </SectionContainer>+ )+}diff --git a/web-v2/web/src/app/mcp/layout.js b/web-v2/web/src/app/mcp/layout.jsnew file mode 100644index 0000000000..32b62d67d2--- /dev/null+++ b/web-v2/web/src/app/mcp/layout.js@@ -0,0 +1,35 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++import SectionContainer from '@/components/SectionContainer'+import McpGatewayProvider from './McpGatewayProvider'+import McpNav from './McpNav'++export default function McpLayout({ children }) {+ return (+ <McpGatewayProvider>+ <SectionContainer classProps='flex'>+ <div className='h-full bg-white'>+ <McpNav />+ </div>+ <div className='relative grow bg-white'>{children}</div>+ </SectionContainer>+ </McpGatewayProvider>+ )+}diff --git a/web-v2/web/src/app/mcp/page.js b/web-v2/web/src/app/mcp/page.jsnew file mode 100644index 0000000000..d6ca711ea4--- /dev/null+++ b/web-v2/web/src/app/mcp/page.js@@ -0,0 +1,200 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++'use client'++import { useCallback, useState } from 'react'+import { Button, Flex, Input, Popconfirm, Spin, Table, Tag, Typography } from 'antd'+import toast from 'react-hot-toast'+import SectionContainer from '@/components/SectionContainer'+import { gatewayErrorMessage } from '@/lib/api/mcpGateway'+import { latestRequest, mcpAccessStatus } from '@/lib/utils/mcpAccess'+import { useMcpGateway } from './McpGatewayProvider'+import useLatestResult from './useLatestResult'+import RequestAccessDialog from './RequestAccessDialog'++const { Title, Paragraph, Text } = Typography++const ACCESS = {+ granted: { color: 'green', label: 'Granted' },+ open: { color: 'green', label: 'Open' },+ pending: { color: 'gold', label: 'Pending approval' },+ denied: { color: 'red', label: 'Denied' },+ expired: { color: 'default', label: 'Expired' },+ none: { color: 'default', label: 'No access' }+}++// Servers the gateway signs users in to by itself; users connect to the others once.+const signsInAutomatically = server => server.auto_sso_enabled || ['basic', 'passthrough'].includes(server.auth_type)++export default function McpServersPage() {+ const { api } = useMcpGateway()+ const [search, setSearch] = useState('')+ const [requesting, setRequesting] = useState()+ const [reloads, setReloads] = useState(0)+ const load = () => setReloads(count => count + 1)++ const { loading, result: servers = [] } = useLatestResult(+ useCallback(async () => {+ const [catalog, permissions, requests] = await Promise.all([+ api.getCatalog(),+ api.getMyPermissions(),+ api.getMyRequests()+ ])++ return catalog.map(server => ({+ ...server,+ access: mcpAccessStatus(server, permissions, requests),+ note: latestRequest(server, requests)?.admin_notes+ }))+ }, [api, reloads]),+ 'servers'+ )++ // The gateway runs the server's sign-in, then sends the browser back here.+ const connect = server => window.location.assign(api.connectUrl(server.service_id, window.location.href))++ const disconnect = async server => {+ try {+ await api.disconnect(server.service_id)+ toast.success(`Disconnected from ${server.name}`)+ load()+ } catch (error) {+ toast.error(gatewayErrorMessage(error))+ }+ }++ const columns = [+ {+ title: 'Server',+ key: 'name',+ sorter: (a, b) => a.name.localeCompare(b.name),+ render: (_, server) => (+ <>+ <div className='font-medium'>+ {server.icon} {server.name}+ </div>+ <Paragraph type='secondary' className='!mb-1' ellipsis={{ rows: 2, tooltip: server.description }}>+ {server.description}+ </Paragraph>+ <Text code copyable={{ tooltips: ['Copy the URL for MCP clients', 'Copied'] }}>+ {api.endpointUrl(server.service_id)}+ </Text>+ </>+ )+ },+ {+ title: 'Access',+ key: 'access',+ width: 240,+ render: (_, server) => (+ <>+ <Flex gap='small' align='center'>+ <Tag color={ACCESS[server.access].color}>{ACCESS[server.access].label}</Tag>+ {['none', 'denied', 'expired'].includes(server.access) && (+ <Button size='small' onClick={() => setRequesting(server)}>+ Request access+ </Button>+ )}+ </Flex>+ {server.access === 'denied' && server.note && <Text type='secondary'>{server.note}</Text>}+ </>+ )+ },+ {+ title: 'Sign-in',+ key: 'signIn',+ width: 220,+ render: (_, server) => {+ if (signsInAutomatically(server)) {+ return <Text type='secondary'>Automatic</Text>+ }+ if (!server.connected) {+ return (+ <Button size='small' onClick={() => connect(server)}>+ Connect+ </Button>+ )+ }+ if (server.token_expired) {+ return (+ <Flex gap='small' align='center'>+ <Tag>Expired</Tag>+ <Button size='small' onClick={() => connect(server)}>+ Reconnect+ </Button>+ </Flex>+ )+ }++ return (+ <Flex gap='small' align='center'>+ <Tag color='green'>Connected</Tag>+ <Popconfirm+ title={`Disconnect from ${server.name}?`}+ description='You will need to connect again to use it.'+ okText='Disconnect'+ okButtonProps={{ danger: true }}+ onConfirm={() => disconnect(server)}+ >+ <Button size='small' type='link' danger>+ Disconnect+ </Button>+ </Popconfirm>+ </Flex>+ )+ }+ }+ ]++ const visible = servers+ .filter(server => server.name.toLowerCase().includes(search.toLowerCase()))+ .map(server => ({ ...server, key: server.service_id }))++ return (+ <SectionContainer classProps='block overflow-y-auto'>+ <Title level={2}>My Servers</Title>+ <Paragraph type='secondary'>+ Point an MCP client, such as an IDE or an AI assistant, at a server's URL. The client signs you in with+ your Gravitino account, and the server acts as you.+ </Paragraph>+ <Flex justify='flex-end' className='mb-4'>+ <Input.Search+ className='w-1/3'+ placeholder='Search...'+ aria-label='Search the servers'+ onChange={e => setSearch(e.target.value)}+ />+ </Flex>+ <Spin spinning={loading}>+ <Table dataSource={visible} columns={columns} tableLayout='fixed' pagination={{ position: ['bottomCenter'] }} />+ </Spin>+ {requesting && (+ <RequestAccessDialog+ server={requesting}+ onClose={() => setRequesting(undefined)}+ onRequested={() => {+ setRequesting(undefined)+ load()+ }}+ />+ )}+ </SectionContainer>+ )+}diff --git a/web-v2/web/src/app/mcp/servers/ServerDialog.js b/web-v2/web/src/app/mcp/servers/ServerDialog.jsnew file mode 100644index 0000000000..aae1829cd5--- /dev/null+++ b/web-v2/web/src/app/mcp/servers/ServerDialog.js@@ -0,0 +1,248 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++'use client'++import { useState } from 'react'+import { Checkbox, Form, Input, Modal, Select, Switch } from 'antd'+import toast from 'react-hot-toast'+import { gatewayErrorMessage } from '@/lib/api/mcpGateway'+import { hasBasicAuth, serverFields } from '@/lib/utils/mcpServers'+import { useMcpGateway } from '../McpGatewayProvider'++const CATEGORIES = ['data', 'ai', 'analytics', 'communication', 'devops', 'other']++const AUTH_TYPES = [+ { value: 'oauth', label: 'OAuth' },+ { value: 'basic', label: "Basic, with the gateway's credentials" },+ { value: 'passthrough', label: 'A token from the gateway' }+]++const SERVICE_AUTH_TYPES = [+ { value: 'passthrough', label: 'A token from the gateway' },+ { value: 'basic', label: "Basic, with the gateway's credentials" },+ { value: 'credential_forward', label: "The service account's own credentials" }+]++const NEW_SERVER = {+ icon: '🔌',+ category: 'data',+ auth_type: 'oauth',+ auto_sso_enabled: true,+ service_auth_type: 'passthrough',+ requires_approval: true,+ admin_only: false,+ is_active: true+}++// An http(s) URL with a host, as the gateway checks it; service names such as+// http://mcp-server:8000/mcp count.+const httpUrl = (_, value) => {+ if (!value) return Promise.resolve()+ try {+ const url = new URL(value)+ if (['http:', 'https:'].includes(url.protocol) && url.hostname && !url.username && !url.password) {+ return Promise.resolve()+ }+ } catch {+ // Not a URL at all.+ }++ return Promise.reject(new Error('Enter an http or https URL'))+}++// Registers an MCP server with the gateway, or changes one (`server`).+export default function ServerDialog({ server, onClose, onSaved }) {+ const { api } = useMcpGateway()+ const [form] = Form.useForm()+ const [saving, setSaving] = useState(false)+ const authType = Form.useWatch('auth_type', form)+ const singleSignOn = Form.useWatch('auto_sso_enabled', form)+ const serviceAuthType = Form.useWatch('service_auth_type', form)+ const removeClientSecret = Form.useWatch('remove_oauth_client_secret', form)++ // The same credentials serve people's and service accounts' basic auth.+ const usesBasic = authType === 'basic' || serviceAuthType === 'basic'++ const submit = async () => {+ // The form shows what failed to validate.+ const values = await form.validateFields().catch(() => null)+ if (!values) return++ const fields = serverFields(values)+ setSaving(true)+ try {+ if (server) {+ const changes = Object.fromEntries(Object.entries(fields).filter(([key]) => key !== 'service_id'))+ await api.updateServer(server.service_id, changes)+ } else {+ await api.createServer(fields)+ }+ toast.success(`Saved ${values.name}`)+ onSaved()+ } catch (error) {+ toast.error(gatewayErrorMessage(error))+ } finally {+ setSaving(false)+ }+ }++ return (+ <Modal+ open+ width={640}+ title={server ? `Edit ${server.name}` : 'Add MCP Server'}+ okText='Save'+ confirmLoading={saving}+ onOk={submit}+ onCancel={onClose}+ >+ <Form form={form} layout='vertical' initialValues={server || NEW_SERVER}>+ <Form.Item+ name='service_id'+ label='Server ID'+ extra='Part of the URL that MCP clients use; it cannot change later.'+ rules={[+ { required: true, min: 3, max: 100 },+ {+ pattern: /^[a-z0-9][a-z0-9_.-]*$/,+ message: "Use lower-case letters, digits, '.', '_' and '-', starting with a letter or digit"+ }+ ]}+ >+ <Input disabled={!!server} />+ </Form.Item>+ <Form.Item name='name' label='Name' rules={[{ required: true, min: 3, max: 255 }]}>+ <Input />+ </Form.Item>+ <Form.Item name='description' label='Description'>+ <Input.TextArea rows={2} />+ </Form.Item>+ <div className='flex gap-4'>+ <Form.Item name='icon' label='Icon' className='w-1/3'>+ <Input maxLength={50} />+ </Form.Item>+ <Form.Item name='category' label='Category' className='grow'>+ <Select options={CATEGORIES.map(value => ({ value, label: value }))} />+ </Form.Item>+ </div>+ <Form.Item+ name='mcp_url'+ label='MCP server URL'+ rules={[{ required: true, message: 'Enter the MCP server URL' }, { validator: httpUrl }]}+ >+ <Input placeholder='http://mcp-server:8000/mcp' />+ </Form.Item>+ <Form.Item name='auth_type' label='How the gateway signs in for users'>+ <Select options={AUTH_TYPES} />+ </Form.Item>+ {authType === 'oauth' && (+ <Form.Item+ name='auto_sso_enabled'+ label='Single sign-on'+ valuePropName='checked'+ extra="On: the gateway forwards or exchanges the user's own token. Off: each user connects to the server's own sign-in."+ >+ <Switch />+ </Form.Item>+ )}+ {authType === 'oauth' && singleSignOn && (+ <>+ <Form.Item+ name='audience'+ preserve={false}+ label='Audience'+ extra="The audience of the tokens the server accepts. Users' tokens are forwarded for the gateway's own audience and exchanged for any other."+ rules={[{ required: true }]}+ >+ <Input />+ </Form.Item>+ </>+ )}+ {authType === 'oauth' && !singleSignOn && (+ <>+ <Form.Item+ name='oauth_metadata_url'+ label='Authorization server metadata URL'+ dependencies={['oauth_client_secret', 'remove_oauth_client_secret']}+ extra='Needed with a client secret, which is sent only to this authorization server.'+ rules={[+ ({ getFieldValue }) => ({+ required: Boolean(+ getFieldValue('oauth_client_secret') ||+ (server?.oauth_client_secret_configured && !getFieldValue('remove_oauth_client_secret'))+ ),+ message: 'A client secret needs the authorization server metadata URL'+ }),+ { validator: httpUrl }+ ]}+ >+ <Input placeholder='Found from the server URL when empty' />+ </Form.Item>+ <Form.Item name='oauth_client_id' label='Client ID' preserve={false}>+ <Input placeholder='Registered by the gateway when empty' />+ </Form.Item>+ <Form.Item name='oauth_client_secret' label='Client secret'>+ <Input.Password placeholder={server ? 'Unchanged' : 'Optional'} disabled={removeClientSecret} />+ </Form.Item>+ {server?.oauth_client_secret_configured && (+ <Form.Item name='remove_oauth_client_secret' valuePropName='checked' preserve={false}>+ <Checkbox>Remove the client secret, for a public client</Checkbox>+ </Form.Item>+ )}+ </>+ )}+ {authType === 'oauth' && (+ <Form.Item name='oauth_scopes' label='Scopes'>+ <Input placeholder='Optional' />+ </Form.Item>+ )}+ <Form.Item name='service_auth_type' label='How the gateway signs in for service accounts'>+ <Select options={SERVICE_AUTH_TYPES} />+ </Form.Item>+ {usesBasic && (+ <div className='flex gap-4'>+ <Form.Item name='basic_auth_username' label='User name' className='grow' rules={[{ required: true }]}>+ <Input />+ </Form.Item>+ <Form.Item+ name='basic_auth_password'+ label='Password'+ className='grow'+ rules={[{ required: !hasBasicAuth(server) }]}+ >+ <Input.Password placeholder={hasBasicAuth(server) ? 'Unchanged' : ''} />+ </Form.Item>+ </div>+ )}+ <div className='flex gap-8'>+ <Form.Item name='requires_approval' label='Requires approval' valuePropName='checked'>+ <Switch />+ </Form.Item>+ <Form.Item name='admin_only' label='Only admins see it' valuePropName='checked'>+ <Switch />+ </Form.Item>+ <Form.Item name='is_active' label='Active' valuePropName='checked'>+ <Switch />+ </Form.Item>+ </div>+ </Form>+ </Modal>+ )+}diff --git a/web-v2/web/src/app/mcp/servers/page.js b/web-v2/web/src/app/mcp/servers/page.jsnew file mode 100644index 0000000000..2d3ec65db0--- /dev/null+++ b/web-v2/web/src/app/mcp/servers/page.js@@ -0,0 +1,213 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++'use client'++import { useCallback, useState } from 'react'+import { ExclamationCircleFilled, PlusOutlined } from '@ant-design/icons'+import { Button, Flex, Modal, Spin, Table, Tag, Tooltip, Typography } from 'antd'+import toast from 'react-hot-toast'+import ConfirmInput from '@/components/ConfirmInput'+import Icons from '@/components/Icons'+import SectionContainer from '@/components/SectionContainer'+import { gatewayErrorMessage } from '@/lib/api/mcpGateway'+import { useMcpGateway, AdminOnly } from '../McpGatewayProvider'+import useLatestResult from '../useLatestResult'+import ServerDialog from './ServerDialog'++const { Title, Paragraph, Text } = Typography++const signIn = server => {+ if (server.auth_type === 'oauth') {+ return server.auto_sso_enabled ? 'Single sign-on' : 'Users connect'+ }++ return { basic: 'Basic', passthrough: 'Gateway token' }[server.auth_type] || server.auth_type+}++export default function ManageServersPage() {+ return (+ <AdminOnly>+ <ManageServers />+ </AdminOnly>+ )+}++function ManageServers() {+ const { api } = useMcpGateway()+ const [modal, contextHolder] = Modal.useModal()++ // The server being edited, or null while adding one.+ const [editing, setEditing] = useState()++ const [reloads, setReloads] = useState(0)+ const load = () => setReloads(count => count + 1)++ const { loading, result: servers = [] } = useLatestResult(+ useCallback(() => api.getServers(), [api, reloads]),+ 'servers'+ )++ const call = async (request, success) => {+ try {+ await request+ toast.success(success)+ load()+ } catch (error) {+ toast.error(gatewayErrorMessage(error))+ }+ }++ const confirmDelete = server => {+ let validate = () => false+ modal.confirm({+ title: `Delete ${server.name}?`,+ icon: <ExclamationCircleFilled />,+ content: (+ <>+ <Paragraph>Users lose access to it, and the gateway forgets their connections to it.</Paragraph>+ <ConfirmInput+ name={server.service_id}+ setConfirmInput={() => {}}+ registerValidate={fn => {+ validate = fn+ }}+ />+ </>+ ),+ okText: 'Delete',+ okType: 'danger',+ onOk(close) {+ if (!validate()) return+ close()+ call(api.deleteServer(server.service_id), `Deleted ${server.name}`)+ }+ })+ }++ const columns = [+ {+ title: 'Server',+ key: 'name',+ sorter: (a, b) => a.name.localeCompare(b.name),+ render: (_, server) => (+ <>+ <div className='font-medium'>+ {server.icon} {server.name} <Text type='secondary'>({server.service_id})</Text>+ </div>+ <Text type='secondary' ellipsis={{ tooltip: server.mcp_url }}>+ {server.mcp_url}+ </Text>+ </>+ )+ },+ { title: 'Sign-in', key: 'signIn', width: 140, render: (_, server) => signIn(server) },+ {+ title: 'Access',+ key: 'access',+ width: 200,+ render: (_, server) => (+ <>+ <Tag>{server.requires_approval ? 'Approval required' : 'Open'}</Tag>+ {server.admin_only && <Tag color='purple'>Admins only</Tag>}+ </>+ )+ },+ {+ title: 'Status',+ key: 'status',+ width: 100,+ render: (_, server) => (server.is_active ? <Tag color='green'>Active</Tag> : <Tag color='default'>Inactive</Tag>)+ },+ {+ title: 'Actions',+ key: 'actions',+ width: 120,+ render: (_, server) => {+ const activating = !server.is_active+ const action = activating ? 'Activate' : 'Deactivate'++ return (+ <Flex gap={4} align='center'>+ <Tooltip title='Edit'>+ <Button+ type='text'+ size='small'+ aria-label={`Edit ${server.name}`}+ icon={<Icons.Pencil className='size-4' />}+ onClick={() => setEditing(server)}+ />+ </Tooltip>+ <Tooltip title={action}>+ <Button+ type='text'+ size='small'+ aria-label={`${action} ${server.name}`}+ icon={activating ? <Icons.Power className='size-4' /> : <Icons.PowerOff className='size-4' />}+ onClick={() =>+ call(api.updateServer(server.service_id, { is_active: activating }), `${action}d ${server.name}`)+ }+ />+ </Tooltip>+ <Tooltip title='Delete'>+ <Button+ type='text'+ size='small'+ aria-label={`Delete ${server.name}`}+ icon={<Icons.Trash2Icon className='size-4' />}+ onClick={() => confirmDelete(server)}+ />+ </Tooltip>+ </Flex>+ )+ }+ }+ ]++ return (+ <SectionContainer classProps='block overflow-y-auto'>+ {contextHolder}+ <Title level={2}>Manage Servers</Title>+ <Paragraph type='secondary'>MCP servers that users reach through the MCP gateway.</Paragraph>+ <Flex justify='flex-end' className='mb-4'>+ <Button type='primary' icon={<PlusOutlined />} onClick={() => setEditing(null)}>+ Add Server+ </Button>+ </Flex>+ <Spin spinning={loading}>+ <Table+ dataSource={servers.map(server => ({ ...server, key: server.service_id }))}+ columns={columns}+ tableLayout='fixed'+ pagination={{ position: ['bottomCenter'] }}+ />+ </Spin>+ {editing !== undefined && (+ <ServerDialog+ server={editing}+ onClose={() => setEditing(undefined)}+ onSaved={() => {+ setEditing(undefined)+ load()+ }}+ />+ )}+ </SectionContainer>+ )+}diff --git a/web-v2/web/src/app/mcp/serviceAccounts/ServiceAccountDialog.js b/web-v2/web/src/app/mcp/serviceAccounts/ServiceAccountDialog.jsnew file mode 100644index 0000000000..b64bb91c30--- /dev/null+++ b/web-v2/web/src/app/mcp/serviceAccounts/ServiceAccountDialog.js@@ -0,0 +1,159 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++'use client'++import { useEffect, useState } from 'react'+import { Form, Input, Modal, Select } from 'antd'+import toast from 'react-hot-toast'+import { gatewayErrorMessage } from '@/lib/api/mcpGateway'+import { serviceAccountConfig, splitServiceAccountConfig } from '@/lib/utils/mcpServiceAccounts'+import { useMcpGateway } from '../McpGatewayProvider'++// Checks the config field holds a JSON object, so saving can't fail on it.+const jsonObjectRule = {+ validator: async (_, value) => {+ serviceAccountConfig('', value)+ }+}++export const PROVIDERS = [+ { value: 'google', label: 'Google Cloud (GKE, GCE)' },+ { value: 'aws', label: 'Amazon EKS' },+ { value: 'other', label: 'Other identity provider' }+]++// Registers a workload as a service account, or changes one (`account`).+export default function ServiceAccountDialog({ account, onClose, onSaved }) {+ const { api } = useMcpGateway()+ const [form] = Form.useForm()+ const [saving, setSaving] = useState(false)+ const [servers, setServers] = useState([])++ useEffect(() => {+ api+ .getServers()+ .then(list => setServers(list.map(server => ({ value: server.service_id, label: server.name }))))+ .catch(error => toast.error(gatewayErrorMessage(error)))+ }, [api])++ const { issuer, rest } = splitServiceAccountConfig(account?.additional_config)++ const submit = async () => {+ // The form shows what failed to validate.+ const values = await form.validateFields().catch(() => null)+ if (!values) return+ const config = serviceAccountConfig(values.issuer, values.config)+ setSaving(true)+ try {+ if (account) {+ await api.updateServiceAccount(account.id, {+ allowed_services: values.allowed_services,+ ...(config ? { additional_config: config } : { clear_additional_config: true })+ })+ } else {+ await api.createServiceAccount({+ name: values.name.trim(),+ team: values.team?.trim() || null,+ provider: values.provider,+ oauth_credentials: { service_account_name: values.identity.trim() },+ allowed_services: values.allowed_services,+ additional_config: config+ })+ }+ toast.success(`Saved ${account?.username || values.name.trim()}`)+ onSaved()+ } catch (error) {+ toast.error(gatewayErrorMessage(error))+ } finally {+ setSaving(false)+ }+ }++ return (+ <Modal+ open+ width={640}+ title={account ? `Edit ${account.username}` : 'Add Service Account'}+ okText='Save'+ confirmLoading={saving}+ onOk={submit}+ onCancel={onClose}+ >+ <Form+ form={form}+ layout='vertical'+ initialValues={{+ name: account?.username,+ team: account?.team,+ provider: account?.provider || 'google',+ identity: account?.service_account_name,+ allowed_services: account?.allowed_services || [],+ issuer,+ config: rest+ }}+ >+ <Form.Item+ name='name'+ label='Name'+ rules={[{ required: true, whitespace: true, min: 3, max: 100, transform: value => value?.trim() }]}+ extra='How the audit log names the account.'+ >+ <Input disabled={Boolean(account)} placeholder='svc-data-pipeline' />+ </Form.Item>+ <Form.Item name='team' label='Team'>+ <Input disabled={Boolean(account)} />+ </Form.Item>+ <Form.Item name='provider' label='Where the workload runs'>+ <Select disabled={Boolean(account)} options={PROVIDERS} />+ </Form.Item>+ <Form.Item+ name='identity'+ label='Workload identity'+ rules={[{ required: true, whitespace: true }]}+ extra='The email of the GCP service account, or on EKS namespace::serviceaccount::<cluster id>.'+ >+ <Input disabled={Boolean(account)} placeholder='[email protected]' />+ </Form.Item>+ <Form.Item+ name='allowed_services'+ label='Servers it may call'+ extra='Service accounts need no access requests; they reach only these servers.'+ >+ <Select mode='multiple' allowClear options={servers} />+ </Form.Item>+ <Form.Item+ name='issuer'+ label='Token issuer'+ extra='The issuer its tokens must come from. Needed for an EKS identity without a cluster id.'+ >+ <Input placeholder='https://oidc.eks.us-west-2.amazonaws.com/id/EXAMPLE' />+ </Form.Item>+ <Form.Item+ name='config'+ label='Other configuration (JSON)'+ rules={[jsonObjectRule]}+ extra='For example downstream_credentials, whose secret names must start with mcp-gateway-sa-.'+ >+ <Input.TextArea rows={4} className='font-mono' />+ </Form.Item>+ </Form>+ </Modal>+ )+}diff --git a/web-v2/web/src/app/mcp/serviceAccounts/page.js b/web-v2/web/src/app/mcp/serviceAccounts/page.jsnew file mode 100644index 0000000000..f45cfa9c94--- /dev/null+++ b/web-v2/web/src/app/mcp/serviceAccounts/page.js@@ -0,0 +1,214 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++'use client'++import { useCallback, useState } from 'react'+import Link from 'next/link'+import { useSearchParams } from 'next/navigation'+import { ExclamationCircleFilled, PlusOutlined } from '@ant-design/icons'+import { Button, Flex, Modal, Spin, Table, Tag, Tooltip, Typography } from 'antd'+import toast from 'react-hot-toast'+import ConfirmInput from '@/components/ConfirmInput'+import Icons from '@/components/Icons'+import SectionContainer from '@/components/SectionContainer'+import { ROUTES } from '@/config/routes'+import { gatewayErrorMessage } from '@/lib/api/mcpGateway'+import { formatToDateTime } from '@/lib/utils/date'+import { gatewayDate } from '@/lib/utils/mcpAccess'+import { useMcpGateway, AdminOnly } from '../McpGatewayProvider'+import useLatestResult from '../useLatestResult'+import ServiceAccountDialog, { PROVIDERS } from './ServiceAccountDialog'++const { Title, Paragraph, Text } = Typography++const providerLabel = provider => PROVIDERS.find(item => item.value === provider)?.label || provider++export default function ServiceAccountsPage() {+ return (+ <AdminOnly>+ <ServiceAccounts />+ </AdminOnly>+ )+}++function ServiceAccounts() {+ const { api } = useMcpGateway()+ const metalake = useSearchParams().get('metalake')+ const [modal, contextHolder] = Modal.useModal()++ // The account being edited, or null while adding one.+ const [editing, setEditing] = useState()++ const [reloads, setReloads] = useState(0)+ const load = () => setReloads(count => count + 1)++ const { loading, result: accounts = [] } = useLatestResult(+ useCallback(() => api.getServiceAccounts(), [api, reloads]),+ 'accounts'+ )++ const remove = async account => {+ try {+ await api.deleteServiceAccount(account.id)+ toast.success(`Deleted ${account.username}`)+ load()+ } catch (error) {+ toast.error(gatewayErrorMessage(error))+ }+ }++ // The audit log of one account, keeping the metalake the rest of the UI is on.+ const auditLogHref = account =>+ `${ROUTES.McpAudit}?${new URLSearchParams({ user: account.id, name: account.username, ...(metalake && { metalake }) })}`++ const confirmDelete = account => {+ let validate = () => false+ modal.confirm({+ title: `Delete ${account.username}?`,+ icon: <ExclamationCircleFilled />,+ content: (+ <>+ <Paragraph>Its workload can no longer call MCP servers. Its audit history is kept.</Paragraph>+ <ConfirmInput+ name={account.username}+ setConfirmInput={() => {}}+ registerValidate={fn => {+ validate = fn+ }}+ />+ </>+ ),+ okText: 'Delete',+ okType: 'danger',+ onOk(close) {+ if (!validate()) return+ close()+ remove(account)+ }+ })+ }++ const columns = [+ {+ title: 'Service account',+ key: 'name',+ sorter: (a, b) => a.username.localeCompare(b.username),+ render: (_, account) => (+ <>+ <div className='font-medium'>{account.username}</div>+ <Text type='secondary' ellipsis={{ tooltip: account.service_account_name }}>+ {account.service_account_name}+ </Text>+ </>+ )+ },+ { title: 'Team', dataIndex: 'team', key: 'team', width: 140, render: value => value || '-' },+ { title: 'Runs on', key: 'provider', width: 180, render: (_, account) => providerLabel(account.provider) },+ {+ title: 'Servers',+ key: 'servers',+ width: 220,+ render: (_, account) =>+ account.allowed_services.length ? (+ account.allowed_services.map(service => <Tag key={service}>{service}</Tag>)+ ) : (+ <Text type='secondary'>None</Text>+ )+ },+ {+ title: 'Added',+ key: 'created',+ width: 180,+ render: (_, account) => formatToDateTime(gatewayDate(account.created_at))+ },+ {+ title: 'Actions',+ key: 'actions',+ width: 120,+ fixed: 'right',+ render: (_, account) => (+ <Flex gap={4} align='center'>+ <Tooltip title='Edit'>+ <Button+ type='text'+ size='small'+ aria-label={`Edit ${account.username}`}+ icon={<Icons.Pencil className='size-4' />}+ onClick={() => setEditing(account)}+ />+ </Tooltip>+ <Tooltip title='Audit log'>+ <Link+ href={auditLogHref(account)}+ aria-label={`Audit log of ${account.username}`}+ className='inline-flex p-1'+ >+ <Icons.ScrollText className='size-4' />+ </Link>+ </Tooltip>+ <Tooltip title='Delete'>+ <Button+ type='text'+ size='small'+ aria-label={`Delete ${account.username}`}+ icon={<Icons.Trash2Icon className='size-4' />}+ onClick={() => confirmDelete(account)}+ />+ </Tooltip>+ </Flex>+ )+ }+ ]++ return (+ <SectionContainer classProps='block overflow-y-auto'>+ {contextHolder}+ <Title level={2}>Service Accounts</Title>+ <Paragraph type='secondary'>+ Workloads that call MCP servers through the gateway with their platform identity token, such as a GKE or EKS+ workload.+ </Paragraph>+ <Flex justify='flex-end' className='mb-4'>+ <Button type='primary' icon={<PlusOutlined />} onClick={() => setEditing(null)}>+ Add Service Account+ </Button>+ </Flex>+ <Spin spinning={loading}>+ <Table+ dataSource={accounts.map(account => ({ ...account, key: account.id }))}+ columns={columns}+ tableLayout='fixed'+ scroll={{ x: 960 }}+ pagination={{ position: ['bottomCenter'] }}+ />+ </Spin>+ {editing !== undefined && (+ <ServiceAccountDialog+ account={editing}+ onClose={() => setEditing(undefined)}+ onSaved={() => {+ setEditing(undefined)+ load()+ }}+ />+ )}+ </SectionContainer>+ )+}diff --git a/web-v2/web/src/app/mcp/useLastPageWhenEmpty.js b/web-v2/web/src/app/mcp/useLastPageWhenEmpty.jsnew file mode 100644index 0000000000..bab24e025a--- /dev/null+++ b/web-v2/web/src/app/mcp/useLastPageWhenEmpty.js@@ -0,0 +1,36 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++'use client'++import { useEffect } from 'react'++/**+ * Goes back to the page that is now the last, when the rows of the last page+ * are gone, as when its last request is approved or its last grant revoked.+ * `rowCount` is how many rows the page has, and `total` how many there are.+ */+export default function useLastPageWhenEmpty(loading, rowCount, total, page, setPage) {+ useEffect(() => {+ const lastPage = Math.max(1, Math.ceil(total / page.pageSize))+ if (!loading && rowCount === 0 && page.current > lastPage) {+ setPage(current => ({ ...current, current: lastPage }))+ }+ }, [loading, rowCount, total, page, setPage])+}diff --git a/web-v2/web/src/app/mcp/useLatestResult.js b/web-v2/web/src/app/mcp/useLatestResult.jsnew file mode 100644index 0000000000..9e42ba2ddc--- /dev/null+++ b/web-v2/web/src/app/mcp/useLatestResult.js@@ -0,0 +1,55 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++'use client'++import { useEffect, useState } from 'react'+import toast from 'react-hot-toast'+import { gatewayErrorMessage } from '@/lib/api/mcpGateway'++/**+ * What the latest call of `load` returned, as `{ loading, result }`.+ *+ * `key` names what `load` loads, such as a tab and a page. While the same key+ * reloads, its last result stays; a new key, or a failed call, has none, so a+ * page never shows one tab's rows, or acts on them, under another's. Answers to+ * earlier calls are dropped, so a slow one can't win.+ */+export default function useLatestResult(load, key) {+ const [answer, setAnswer] = useState({ load: undefined, key: undefined, result: undefined })++ useEffect(() => {+ let isStale = false+ load()+ .then(result => {+ if (!isStale) setAnswer({ load, key, result })+ })+ .catch(error => {+ if (isStale) return+ setAnswer({ load, key, result: undefined })+ toast.error(gatewayErrorMessage(error))+ })++ return () => {+ isStale = true+ }+ }, [load])++ return { loading: answer.load !== load, result: answer.key === key ? answer.result : undefined }+}diff --git a/web-v2/web/src/app/mcp/useLatestResult.test.js b/web-v2/web/src/app/mcp/useLatestResult.test.jsnew file mode 100644index 0000000000..430ebb29c8--- /dev/null+++ b/web-v2/web/src/app/mcp/useLatestResult.test.js@@ -0,0 +1,106 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++import { act, createElement, useEffect } from 'react'+import { createRoot } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import useLatestResult from './useLatestResult'++vi.mock('react-hot-toast', () => ({ default: { error: vi.fn() } }))++const deferred = () => {+ const handlers = {}+ const promise = new Promise((resolve, reject) => Object.assign(handlers, { resolve, reject }))++ return { promise, ...handlers }+}++let root++// What the hook returned at the latest render.+const latest = { current: undefined }++const Probe = ({ load, view }) => {+ const state = useLatestResult(load, view)+ useEffect(() => {+ latest.current = state+ })++ return null+}++const show = (load, view) =>+ act(async () => {+ root.render(createElement(Probe, { load, view }))+ })++beforeEach(() => {+ globalThis.IS_REACT_ACT_ENVIRONMENT = true+ root = createRoot(document.createElement('div'))+})++afterEach(() => act(() => root.unmount()))++describe('useLatestResult', () => {+ it('is the result of the latest load', async () => {+ await show(async () => ['row'], 'pending')++ expect(latest.current).toEqual({ loading: false, result: ['row'] })+ })++ it('keeps the result while the same view reloads', async () => {+ await show(async () => ['old'], 'servers')+ const reload = deferred()+ await show(() => reload.promise, 'servers')++ expect(latest.current).toEqual({ loading: true, result: ['old'] })++ await act(async () => reload.resolve(['new']))+ expect(latest.current).toEqual({ loading: false, result: ['new'] })+ })++ it("never shows one view's rows under another", async () => {+ await show(async () => ['a pending request'], 'pending')+ const granted = deferred()+ await show(() => granted.promise, 'granted')++ expect(latest.current).toEqual({ loading: true, result: undefined })++ await act(async () => granted.reject(new Error('down')))+ expect(latest.current).toEqual({ loading: false, result: undefined })+ })++ it('has no result after the same view fails to reload', async () => {+ await show(async () => ['old'], 'servers')+ await show(async () => {+ throw new Error('down')+ }, 'servers')++ expect(latest.current).toEqual({ loading: false, result: undefined })+ })++ it("drops an earlier load's late answer", async () => {+ const slow = deferred()+ await show(() => slow.promise, 'page 1')+ await show(async () => ['page 2'], 'page 2')++ await act(async () => slow.resolve(['page 1']))+ expect(latest.current).toEqual({ loading: false, result: ['page 2'] })+ })+})diff --git a/web-v2/web/src/app/rootLayout/MainNav.js b/web-v2/web/src/app/rootLayout/MainNav.jsindex 8294906669..139f384caf 100644--- a/web-v2/web/src/app/rootLayout/MainNav.js+++ b/web-v2/web/src/app/rootLayout/MainNav.js@@ -28,6 +28,7 @@ import { ROUTES } from '@/config/routes'import { usePathname, useSearchParams } from 'next/navigation'import { useAppSelector, useAppDispatch } from '@/lib/hooks/useStore'+import { MCP_GATEWAY_URI_KEY, isOidcSignIn } from '@/lib/api/mcpGateway'import { getCurrentEntityOwner } from '@/lib/store/metalakes'import { to } from '@/lib/utils'@@ -40,18 +41,26 @@ export function MainNav() {const currentMetalake = searchParams.get('metalake')const auth = useAppSelector(state => state.auth)const sys = useAppSelector(state => state.sys)- const { anthEnable, authUser } = auth+ const { anthEnable, authUser, systemConfig } = authconst dispatch = useAppDispatch()+ // The gateway takes the token of an OIDC sign-in, so other sign-ins can't use it.+ const hasMcpGateway = !!systemConfig?.[MCP_GATEWAY_URI_KEY] && isOidcSignIn(systemConfig, auth.authType)+useEffect(() => {const init = async () => {- if (pathname === '/metalakes' && !searchParams.get('metalake')) {+ const mcpItems = hasMcpGateway+ ? [{ key: ROUTES.Mcp, icon: <Icons.iconify icon='carbon:plug' className='my-icon' />, label: 'MCP' }]+ : []+ const onMcpPage = pathname.startsWith(ROUTES.Mcp)+ if ((pathname === '/metalakes' || onMcpPage) && !searchParams.get('metalake')) {setItems([{key: ROUTES.Metalakes,icon: <Icons.iconify icon='carbon:cloudy' className='my-icon' />,label: 'Metalakes'- }+ },+ ...mcpItems])} else {const items = [@@ -125,9 +134,11 @@ export function MainNav() {})}}- setItems(items)+ setItems([...items, ...mcpItems])}- if (currentMetalake) {+ if (onMcpPage) {+ setCurrent(ROUTES.Mcp)+ } else if (currentMetalake) {if (pathname.startsWith('/catalogs')) {setCurrent(ROUTES.Catalogs)} else {@@ -138,7 +149,7 @@ export function MainNav() {}}init()- }, [pathname, anthEnable, authUser, currentMetalake])+ }, [pathname, anthEnable, authUser, currentMetalake, hasMcpGateway])const onClick = menuItem => {setCurrent(menuItem.key)diff --git a/web-v2/web/src/app/rootLayout/SiteHeader.js b/web-v2/web/src/app/rootLayout/SiteHeader.jsindex a6133f23ca..7567075f0e 100644--- a/web-v2/web/src/app/rootLayout/SiteHeader.js+++ b/web-v2/web/src/app/rootLayout/SiteHeader.js@@ -67,8 +67,14 @@ export function SiteHeader() {return params.toString()}- // If we're not on the metalakes list page and metalake is missing, fill it- if (!['/', '/ui', '/metalakes', '/ui/metalakes', '/login', '/ui/login'].includes(pathname) && !metalakeParam) {+ // If we're not on the metalakes list page and metalake is missing, fill it.+ // The MCP pages belong to no metalake.+ const isMcpPage = /^(\/ui)?\/mcp(\/|$)/.test(pathname)+ if (+ !['/', '/ui', '/metalakes', '/ui/metalakes', '/login', '/ui/login'].includes(pathname) &&+ !isMcpPage &&+ !metalakeParam+ ) {const first = store.metalakes[0].name || ''if (first) {const qs = makeNewSearch({ metalake: first })diff --git a/web-v2/web/src/config/routes.js b/web-v2/web/src/config/routes.jsindex 4e221e34ec..41989851c4 100644--- a/web-v2/web/src/config/routes.js+++ b/web-v2/web/src/config/routes.js@@ -30,7 +30,12 @@ export const ROUTES = {Users: '/access/users',UserGroups: '/access/userGroups',Roles: '/access/roles',- Metalakes: '/metalakes'+ Metalakes: '/metalakes',+ Mcp: '/mcp',+ McpServers: '/mcp/servers',+ McpAccessRequests: '/mcp/accessRequests',+ McpAudit: '/mcp/audit',+ McpServiceAccounts: '/mcp/serviceAccounts'}export const routeValues = Object.values(ROUTES)diff --git a/web-v2/web/src/lib/api/mcpGateway/index.js b/web-v2/web/src/lib/api/mcpGateway/index.jsnew file mode 100644index 0000000000..bd9180e3ff--- /dev/null+++ b/web-v2/web/src/lib/api/mcpGateway/index.js@@ -0,0 +1,156 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++import axios from 'axios'+import { oauthProviderFactory } from '@/lib/auth/providers/factory'++// The server configuration key holding the MCP gateway's URL.+export const MCP_GATEWAY_URI_KEY = 'gravitino.mcpGateway.uri'++// The server configuration key naming the OAuth provider people sign in with.+const OAUTH_PROVIDER_KEY = 'gravitino.authenticator.oauth.provider'++const SIGNED_OUT = 'MCP_GATEWAY_SIGNED_OUT'++// A failed download's body arrives as a Blob; this reads it, so the gateway's own message shows.+const readBlobError = async error => {+ const body = error?.response?.data+ if (!(body instanceof Blob)) {+ return error+ }+ try {+ const data = JSON.parse(await body.text())++ return Object.assign(new Error(error.message), { response: { ...error.response, data } })+ } catch {+ return error+ }+}++// Whether people sign in to Gravitino with OIDC, whose token the gateway accepts.+export const isOidcSignIn = (systemConfig, authType) =>+ authType === 'oauth' && String(systemConfig?.[OAUTH_PROVIDER_KEY] ?? '').toLowerCase() === 'oidc'++/**+ * A client for the MCP gateway's API, which runs on its own origin and accepts+ * the access token of the user signed in to this UI. `onSignedOut` runs when a+ * call finds nobody signed in, as when renewing the sign-in failed.+ */+export const createMcpGatewayApi = (+ gatewayUri,+ getAccessToken = () => oauthProviderFactory.getAccessToken(),+ onSignedOut = () => {}+) => {+ // The browser is sent to the gateway to connect servers, so it must be a web address,+ // and the user's token goes there: over https, or plain http only on this machine.+ if (+ !/^https:\/\//i.test(gatewayUri) &&+ !/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?(\/|$)/i.test(gatewayUri)+ ) {+ throw new Error(`gravitino.mcpGateway.uri must be an https URL, or http on this machine: ${gatewayUri}`)+ }+ const baseUrl = gatewayUri.replace(/\/+$/, '')+ const http = axios.create({ baseURL: baseUrl, headers: { Accept: 'application/json' } })++ http.interceptors.request.use(async config => {+ const token = await getAccessToken()+ if (!token) {+ onSignedOut()+ throw Object.assign(new Error('Sign in to Gravitino again'), { code: SIGNED_OUT })+ }+ config.headers.Authorization = `Bearer ${token}`++ return config+ })++ const data = request => request.then(res => res.data)+ const server = serviceId => `/api/v1/admin/mcp/${encodeURIComponent(serviceId)}`++ return {+ // Where MCP clients connect to a server.+ endpointUrl: serviceId => `${baseUrl}/mcp/${encodeURIComponent(serviceId)}`,++ // Where the browser connects to a server that has its own sign-in. The gateway+ // signs the user in if needed and sends the browser back to `returnTo`.+ connectUrl: (serviceId, returnTo) =>+ `${baseUrl}/portal/connect/${encodeURIComponent(serviceId)}?${new URLSearchParams({ return_to: returnTo })}`,+ disconnect: serviceId => data(http.post(`/portal/disconnect/${encodeURIComponent(serviceId)}`)),+ getMe: () => data(http.get('/api/v1/users/me')),+ getCatalog: () => data(http.get('/api/v1/catalog/mcps')),+ getMyPermissions: () => data(http.get('/api/v1/mcp-access/my-permissions')),+ getMyRequests: () => data(http.get('/api/v1/mcp-access/my-requests')),+ requestAccess: (mcpId, justification) =>+ data(http.post('/api/v1/mcp-access/request', { mcp_id: mcpId, justification })),+ getServers: () => data(http.get('/api/v1/admin/mcp/', { params: { include_inactive: true } })),+ createServer: fields => data(http.post('/api/v1/admin/mcp/', fields)),+ updateServer: (serviceId, changes) => data(http.patch(server(serviceId), changes)),+ deleteServer: serviceId => data(http.delete(server(serviceId))),+ getPendingRequests: (page, pageSize) =>+ data(http.get('/api/v1/mcp-access/admin/pending', { params: { page, page_size: pageSize } })),+ getAllRequests: (page, pageSize) =>+ data(http.get('/api/v1/mcp-access/admin/all', { params: { page, page_size: pageSize } })),+ reviewRequest: (requestId, review) =>+ data(http.post(`/api/v1/mcp-access/admin/review/${encodeURIComponent(requestId)}`, review)),+ getPermissions: (page, pageSize) =>+ data(http.get('/api/v1/mcp-access/admin/permissions', { params: { page, page_size: pageSize } })),+ revokePermission: permissionId =>+ data(http.delete(`/api/v1/mcp-access/admin/permissions/${encodeURIComponent(permissionId)}`)),++ // The audit log: everyone's calls for admins, and their own for everyone else.+ getAuditLogs: params => data(http.get('/api/v1/audit/logs', { params })),+ getAuditLog: logId => data(http.get(`/api/v1/audit/logs/${encodeURIComponent(logId)}`)),+ getAuditSummary: params => data(http.get('/api/v1/audit/analytics/summary', { params })),+ exportAuditLogs: params =>+ data(http.get('/api/v1/audit/logs/export/csv', { params, responseType: 'blob' })).catch(async error => {+ throw await readBlobError(error)+ }),++ getServiceAccounts: () => data(http.get('/api/v1/admin/service-accounts')),+ createServiceAccount: fields => data(http.post('/api/v1/admin/service-accounts', fields)),+ updateServiceAccount: (accountId, changes) =>+ data(http.patch(`/api/v1/admin/service-accounts/${encodeURIComponent(accountId)}`, changes)),+ deleteServiceAccount: accountId =>+ data(http.delete(`/api/v1/admin/service-accounts/${encodeURIComponent(accountId)}`))+ }+}++// Whether a gateway call was not sent because no one is signed in to this UI.+export const isSignedOut = error => error?.code === SIGNED_OUT++// A readable message from a failed gateway call.+export const gatewayErrorMessage = error => {+ const detail = error?.response?.data?.detail+ if (typeof detail === 'string') {+ return detail+ }+ if (Array.isArray(detail)) {+ // The gateway's own checks come back as pydantic's "Value error, <message>",+ // under the name of the field they are about.+ return detail+ .map(item => {+ const message = String(item.msg ?? '').replace(/^Value error, /, '')+ const field = Array.isArray(item.loc) ? item.loc.at(-1) : undefined++ return field && field !== 'body' ? `${field}: ${message}` : message+ })+ .join('; ')+ }++ return error?.message || 'The MCP gateway did not respond'+}diff --git a/web-v2/web/src/lib/api/mcpGateway/index.test.js b/web-v2/web/src/lib/api/mcpGateway/index.test.jsnew file mode 100644index 0000000000..2ed3225c38--- /dev/null+++ b/web-v2/web/src/lib/api/mcpGateway/index.test.js@@ -0,0 +1,275 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++import axios from 'axios'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { createMcpGatewayApi, gatewayErrorMessage, isOidcSignIn, isSignedOut } from './index'++vi.mock('@/lib/auth/providers/factory', () => ({+ oauthProviderFactory: { getAccessToken: vi.fn() }+}))++describe('createMcpGatewayApi', () => {+ const originalAdapter = axios.defaults.adapter+ const signedIn = async () => 'user-token'+ let requests++ beforeEach(() => {+ requests = []+ axios.defaults.adapter = async config => {+ requests.push(config)++ return { data: { ok: true }, status: 200, statusText: 'OK', headers: {}, config }+ }+ })++ afterEach(() => {+ axios.defaults.adapter = originalAdapter+ })++ it("sends the signed-in user's token to the gateway", async () => {+ const onSignedOut = vi.fn()+ const api = createMcpGatewayApi('https://gateway.example.com', signedIn, onSignedOut)++ await expect(api.getCatalog()).resolves.toEqual({ ok: true })++ expect(onSignedOut).not.toHaveBeenCalled()++ const [request] = requests+ expect(request.baseURL).toBe('https://gateway.example.com')+ expect(request.url).toBe('/api/v1/catalog/mcps')+ expect(request.headers.Authorization).toBe('Bearer user-token')+ })++ it('does not call the gateway when no one is signed in', async () => {+ const onSignedOut = vi.fn()+ const api = createMcpGatewayApi('https://gateway.example.com', async () => null, onSignedOut)++ const error = await api.getMe().catch(err => err)++ expect(onSignedOut).toHaveBeenCalledTimes(1)+ expect(isSignedOut(error)).toBe(true)+ expect(gatewayErrorMessage(error)).toBe('Sign in to Gravitino again')+ expect(requests).toEqual([])+ expect(isSignedOut({ response: { status: 401 } })).toBe(false)+ })++ it('builds MCP endpoint URLs from the configured URL', () => {+ const api = createMcpGatewayApi('https://gateway.example.com/', async () => null)++ expect(api.endpointUrl('gravitino')).toBe('https://gateway.example.com/mcp/gravitino')+ })++ it('escapes server ids in paths', async () => {+ const api = createMcpGatewayApi('https://gateway.example.com', signedIn)++ await api.updateServer('a/b', { is_active: false })++ expect(requests[0].url).toBe('/api/v1/admin/mcp/a%2Fb')+ expect(requests[0].method).toBe('patch')+ })++ it('asks for access with the server id and a justification', async () => {+ const api = createMcpGatewayApi('https://gateway.example.com', signedIn)++ await api.requestAccess(7, 'Investigating a data issue')++ expect(JSON.parse(requests[0].data)).toEqual({ mcp_id: 7, justification: 'Investigating a data issue' })+ })++ it('pages through pending access requests', async () => {+ const api = createMcpGatewayApi('https://gateway.example.com', signedIn)++ await api.getPendingRequests(2, 20)++ expect(requests[0].url).toBe('/api/v1/mcp-access/admin/pending')+ expect(requests[0].params).toEqual({ page: 2, page_size: 20 })+ })++ it('connects in the browser and comes back to the page that asked', () => {+ const api = createMcpGatewayApi('https://gateway.example.com/', async () => null)++ const url = new URL(api.connectUrl('a/b', 'http://ui:3000/mcp?tab=1'))++ expect(url.origin + url.pathname).toBe('https://gateway.example.com/portal/connect/a%2Fb')+ expect(url.searchParams.get('return_to')).toBe('http://ui:3000/mcp?tab=1')+ })++ it("disconnects with the signed-in user's token", async () => {+ const api = createMcpGatewayApi('https://gateway.example.com', signedIn)++ await api.disconnect('docs')++ expect(requests[0].method).toBe('post')+ expect(requests[0].url).toBe('/portal/disconnect/docs')+ expect(requests[0].headers.Authorization).toBe('Bearer user-token')+ })++ it('pages through granted access and revokes it', async () => {+ const api = createMcpGatewayApi('https://gateway.example.com', signedIn)++ await api.getPermissions(3, 25)+ await api.revokePermission(12)++ expect(requests[0].url).toBe('/api/v1/mcp-access/admin/permissions')+ expect(requests[0].params).toEqual({ page: 3, page_size: 25 })+ expect(requests[1].method).toBe('delete')+ expect(requests[1].url).toBe('/api/v1/mcp-access/admin/permissions/12')+ })++ it('reads the audit log, one entry, and its summary', async () => {+ const api = createMcpGatewayApi('https://gateway.example.com', signedIn)++ await api.getAuditLogs({ service: 'gravitino', limit: 25, offset: 50 })+ await api.getAuditLog(9)+ await api.getAuditSummary({ days: 7 })++ expect(requests[0].url).toBe('/api/v1/audit/logs')+ expect(requests[0].params).toEqual({ service: 'gravitino', limit: 25, offset: 50 })+ expect(requests[1].url).toBe('/api/v1/audit/logs/9')+ expect(requests[2].url).toBe('/api/v1/audit/analytics/summary')+ expect(requests[2].params).toEqual({ days: 7 })+ })++ it('downloads the audit log as a file', async () => {+ const api = createMcpGatewayApi('https://gateway.example.com', signedIn)++ await api.exportAuditLogs({ days: 30 })++ expect(requests[0].url).toBe('/api/v1/audit/logs/export/csv')+ expect(requests[0].params).toEqual({ days: 30 })+ expect(requests[0].responseType).toBe('blob')+ expect(requests[0].headers.Authorization).toBe('Bearer user-token')+ })++ it("reports the gateway's message when a download fails", async () => {+ axios.defaults.adapter = async () => {+ // jsdom's Blob lacks text(), which browsers have.+ const json = JSON.stringify({ detail: 'Access denied' })+ const body = Object.assign(new Blob([json], { type: 'application/json' }), { text: async () => json })+ throw Object.assign(new Error('Request failed with status code 403'), { response: { status: 403, data: body } })+ }+ const api = createMcpGatewayApi('https://gateway.example.com', signedIn)++ const error = await api.exportAuditLogs({ days: 30 }).catch(failure => failure)++ expect(gatewayErrorMessage(error)).toBe('Access denied')+ expect(error.response.status).toBe(403)+ })++ it('manages service accounts', async () => {+ const api = createMcpGatewayApi('https://gateway.example.com', signedIn)+ const account = { name: 'svc-etl', oauth_credentials: { service_account_name: '[email protected]' } }++ await api.getServiceAccounts()+ await api.createServiceAccount(account)+ await api.updateServiceAccount(4, { allowed_services: ['gravitino'] })+ await api.deleteServiceAccount(4)++ expect(requests.map(request => [request.method, request.url])).toEqual([+ ['get', '/api/v1/admin/service-accounts'],+ ['post', '/api/v1/admin/service-accounts'],+ ['patch', '/api/v1/admin/service-accounts/4'],+ ['delete', '/api/v1/admin/service-accounts/4']+ ])+ expect(JSON.parse(requests[1].data)).toEqual(account)+ expect(JSON.parse(requests[2].data)).toEqual({ allowed_services: ['gravitino'] })+ })+})++describe('gatewayErrorMessage', () => {+ it.each([+ [+ 'a message from the gateway',+ { response: { data: { detail: 'Admin privileges required' } } },+ 'Admin privileges required'+ ],+ [+ 'validation errors',+ { response: { data: { detail: [{ msg: 'name is too short' }, { msg: 'mcp_url is required' }] } } },+ 'name is too short; mcp_url is required'+ ],+ [+ 'a validator error, without its prefix',+ { response: { data: { detail: [{ msg: 'Value error, Secrets must be named with a prefix' }] } } },+ 'Secrets must be named with a prefix'+ ],+ [+ 'a field error, under the field it is about',+ {+ response: {+ data: { detail: [{ loc: ['body', 'oauth_metadata_url'], msg: 'Value error, must be an http or https URL' }] }+ }+ },+ 'oauth_metadata_url: must be an http or https URL'+ ],+ [+ 'an error about the whole request, without a field',+ {+ response: {+ data: { detail: [{ loc: ['body'], msg: 'Value error, A client secret needs oauth_metadata_url' }] }+ }+ },+ 'A client secret needs oauth_metadata_url'+ ],+ ['a network failure', { message: 'Network Error' }, 'Network Error'],+ ['nothing at all', undefined, 'The MCP gateway did not respond']+ ])('describes %s', (_, error, expected) => {+ expect(gatewayErrorMessage(error)).toBe(expected)+ })+})++describe('createMcpGatewayApi', () => {+ it.each([+ 'javascript:alert(1)',+ 'gateway.example.com',+ 'ftp://gateway.example.com',++ // Over plain http elsewhere, the user's token would cross the network in clear.+ 'http://gateway.example.com',+ 'http://localhost.example.com'+ ])('refuses %s', uri => {+ expect(() => createMcpGatewayApi(uri, async () => 'token')).toThrow('https URL, or http on this machine')+ })++ it.each(['https://gateway.example.com', 'http://localhost:8000', 'http://127.0.0.1:8000/', 'http://[::1]'])(+ 'accepts %s',+ uri => {+ expect(() => createMcpGatewayApi(uri, async () => 'token')).not.toThrow()+ }+ )+})++describe('isOidcSignIn', () => {+ const provider = name => ({ 'gravitino.authenticator.oauth.provider': name })++ it('is true for an OAuth sign-in with the OIDC provider', () => {+ expect(isOidcSignIn(provider('oidc'), 'oauth')).toBe(true)+ expect(isOidcSignIn(provider('OIDC'), 'oauth')).toBe(true)+ })++ it.each([+ ['the default OAuth provider', provider('default'), 'oauth'],+ ['no OAuth provider', {}, 'oauth'],+ ['no configuration yet', null, 'oauth'],+ ['a simple sign-in', provider('oidc'), 'simple']+ ])('is false for %s', (_, systemConfig, authType) => {+ expect(isOidcSignIn(systemConfig, authType)).toBe(false)+ })+})diff --git a/web-v2/web/src/lib/utils/mcpAccess.js b/web-v2/web/src/lib/utils/mcpAccess.jsnew file mode 100644index 0000000000..4c6b0b4b65--- /dev/null+++ b/web-v2/web/src/lib/utils/mcpAccess.js@@ -0,0 +1,62 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++// The MCP gateway sends UTC timestamps without a time zone.+export const gatewayDate = value => {+ if (!value) {+ return null+ }++ return new Date(/(?:[zZ]|[+-]\d{2}:?\d{2})$/.test(value) ? value : `${value}Z`)+}++// The user's latest request for access to an MCP server, or undefined.+export const latestRequest = (server, requests = []) =>+ requests+ .filter(item => item.mcp_id === server.id)+ .sort((a, b) => gatewayDate(b.requested_at) - gatewayDate(a.requested_at))[0]++/**+ * How the signed-in user stands with an MCP server: 'open' (anyone may use it),+ * 'granted', 'pending', 'expired', 'denied' or 'none', as the gateway decides it.+ */+export const mcpAccessStatus = (server, permissions = [], requests = [], now = new Date()) => {+ // An open server takes no requests, and the gateway ignores old grants' expiry.+ if (!server.requires_approval) {+ return 'open'+ }++ const permission = permissions.find(item => item.mcp_id === server.id)+ const expiresAt = gatewayDate(permission?.expires_at)+ if (permission && !(expiresAt && expiresAt < now)) {+ return 'granted'+ }++ const latest = latestRequest(server, requests)++ // A renewal already asked for is pending, and can't be asked for again.+ if (latest?.status === 'pending') {+ return 'pending'+ }+ if (permission) {+ return 'expired'+ }++ return latest?.status === 'denied' ? 'denied' : 'none'+}diff --git a/web-v2/web/src/lib/utils/mcpAccess.test.js b/web-v2/web/src/lib/utils/mcpAccess.test.jsnew file mode 100644index 0000000000..2c4a7fd554--- /dev/null+++ b/web-v2/web/src/lib/utils/mcpAccess.test.js@@ -0,0 +1,92 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++import { describe, expect, it } from 'vitest'+import { gatewayDate, latestRequest, mcpAccessStatus } from './mcpAccess'++const gated = { id: 1, requires_approval: true }+const now = new Date('2026-10-12T12:00:00Z')++const request = (status, requestedAt, mcpId = 1) => ({ mcp_id: mcpId, status, requested_at: requestedAt })++describe('mcpAccessStatus', () => {+ it('is granted with a permission', () => {+ expect(mcpAccessStatus(gated, [{ mcp_id: 1, expires_at: null }], [], now)).toBe('granted')+ })++ it('is expired once the permission expires', () => {+ expect(mcpAccessStatus(gated, [{ mcp_id: 1, expires_at: '2026-10-12T11:59:00' }], [], now)).toBe('expired')+ })++ it('is open when the server needs no approval, whatever an old grant says', () => {+ const open = { id: 1, requires_approval: false }++ expect(mcpAccessStatus(open, [], [], now)).toBe('open')+ expect(mcpAccessStatus(open, [{ mcp_id: 1, expires_at: '2026-10-01T00:00:00' }], [], now)).toBe('open')+ })++ it('is pending, not expired, while a renewal waits for approval', () => {+ const expired = [{ mcp_id: 1, expires_at: '2026-10-01T00:00:00' }]++ expect(mcpAccessStatus(gated, expired, [request('pending', '2026-10-11T09:00:00')], now)).toBe('pending')+ })++ it('follows the latest request', () => {+ const requests = [request('denied', '2026-10-01T09:00:00'), request('pending', '2026-10-11T09:00:00')]++ expect(mcpAccessStatus(gated, [], requests, now)).toBe('pending')+ })++ it('is denied when the latest request was denied', () => {+ expect(mcpAccessStatus(gated, [], [request('denied', '2026-10-11T09:00:00')], now)).toBe('denied')+ })++ it('ignores requests for other servers and approvals that were revoked', () => {+ const requests = [request('pending', '2026-10-11T09:00:00', 2), request('approved', '2026-10-10T09:00:00')]++ expect(mcpAccessStatus(gated, [], requests, now)).toBe('none')+ })+})++describe('gatewayDate', () => {+ it('reads a timestamp without a zone as UTC', () => {+ expect(gatewayDate('2026-10-12T08:30:00').toISOString()).toBe('2026-10-12T08:30:00.000Z')+ })++ it('keeps an explicit zone', () => {+ expect(gatewayDate('2026-10-12T08:30:00+02:00').toISOString()).toBe('2026-10-12T06:30:00.000Z')+ })++ it('has no date for no value', () => {+ expect(gatewayDate(null)).toBeNull()+ })+})++describe('latestRequest', () => {+ it("is the user's latest request for the server, where the admin's note is", () => {+ const requests = [+ { mcp_id: 1, status: 'denied', requested_at: '2026-10-01T10:00:00', admin_notes: 'Old' },+ { mcp_id: 1, status: 'denied', requested_at: '2026-10-02T10:00:00', admin_notes: 'Ask your lead' },+ { mcp_id: 2, status: 'pending', requested_at: '2026-10-03T10:00:00' }+ ]++ expect(latestRequest({ id: 1 }, requests).admin_notes).toBe('Ask your lead')+ expect(latestRequest({ id: 3 }, requests)).toBeUndefined()+ })+})diff --git a/web-v2/web/src/lib/utils/mcpAudit.js b/web-v2/web/src/lib/utils/mcpAudit.jsnew file mode 100644index 0000000000..4c89b6a885--- /dev/null+++ b/web-v2/web/src/lib/utils/mcpAudit.js@@ -0,0 +1,76 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++// Periods the audit log shows, as the gateway's analytics summary takes them.+export const AUDIT_PERIODS = [+ { key: '1h', label: 'Last hour', params: { hours: 1 } },+ { key: '24h', label: 'Last 24 hours', params: { hours: 24 } },+ { key: '7d', label: 'Last 7 days', params: { days: 7 } },+ { key: '30d', label: 'Last 30 days', params: { days: 30 } }+]++export const DEFAULT_AUDIT_PERIOD = AUDIT_PERIODS.find(period => period.key === '24h')++// The most calls the gateway puts in one CSV export, the latest first.+export const EXPORT_ROW_LIMIT = 10000++const HOUR_MS = 60 * 60 * 1000++// `date` as the UTC timestamp without a time zone that the gateway stores.+const gatewayTime = date => date.toISOString().replace(/Z$/, '')++// The start of `period`, in the gateway's time.+export const periodStart = (period, now = new Date()) => {+ const { hours = 0, days = 0 } = period.params++ return gatewayTime(new Date(now.getTime() - (hours + days * 24) * HOUR_MS))+}++// The filters that narrow the summary as well as the list: every one but status.+const narrowingParams = ({ service, tool, userId }) => ({+ ...(service && { service }),+ ...(tool?.trim() && { tool_name: tool.trim() }),+ ...(userId && { user_id: userId })+})++/**+ * The gateway's audit log filters, leaving out the ones that aren't set; the CSV+ * export takes them too. The period ends at `now`, so that later calls don't+ * shift the pages.+ */+export const auditFilterParams = (filters, now = new Date()) => ({+ start_date: periodStart(filters.period, now),+ end_date: gatewayTime(now),+ ...narrowingParams(filters),+ ...(filters.status && { status: filters.status })+})++// One page of the gateway's audit log.+export const auditLogParams = (filters, page, pageSize, now = new Date()) => ({+ ...auditFilterParams(filters, now),+ limit: pageSize,+ offset: (page - 1) * pageSize+})++// The analytics summary of the calls the list shows, whatever their status, over the same window.+export const auditSummaryParams = (filters, now = new Date()) => {+ const { status, ...params } = auditFilterParams(filters, now)++ return params+}diff --git a/web-v2/web/src/lib/utils/mcpAudit.test.js b/web-v2/web/src/lib/utils/mcpAudit.test.jsnew file mode 100644index 0000000000..25ba373d13--- /dev/null+++ b/web-v2/web/src/lib/utils/mcpAudit.test.js@@ -0,0 +1,103 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++import { describe, expect, it } from 'vitest'+import {+ AUDIT_PERIODS,+ auditFilterParams,+ auditLogParams,+ auditSummaryParams,+ DEFAULT_AUDIT_PERIOD,+ periodStart+} from './mcpAudit'++const NOW = new Date('2026-10-22T12:00:00Z')+const period = key => AUDIT_PERIODS.find(item => item.key === key)++describe('periodStart', () => {+ it("is the gateway's UTC time, without a time zone, a period ago", () => {+ expect(periodStart(period('1h'), NOW)).toBe('2026-10-22T11:00:00.000')+ expect(periodStart(period('7d'), NOW)).toBe('2026-10-15T12:00:00.000')+ })+})++describe('auditLogParams', () => {+ it('leaves out filters that are not set', () => {+ expect(auditLogParams({ period: period('24h') }, 1, 25, NOW)).toEqual({+ start_date: '2026-10-21T12:00:00.000',+ end_date: '2026-10-22T12:00:00.000',+ limit: 25,+ offset: 0+ })+ })++ it('passes every filter that is set, and pages by offset', () => {+ const filters = { period: period('30d'), service: 'gravitino', status: 'error', tool: ' get_table ', userId: 4 }++ expect(auditLogParams(filters, 3, 50, NOW)).toEqual({+ start_date: '2026-09-22T12:00:00.000',+ end_date: '2026-10-22T12:00:00.000',+ service: 'gravitino',+ status: 'error',+ tool_name: 'get_table',+ user_id: 4,+ limit: 50,+ offset: 100+ })+ })+})++describe('auditFilterParams', () => {+ it('is the log query without paging, for the CSV export', () => {+ const filters = { period: period('1h'), status: 'success', userId: 7 }++ expect(auditFilterParams(filters, NOW)).toEqual({+ start_date: '2026-10-22T11:00:00.000',+ end_date: '2026-10-22T12:00:00.000',+ status: 'success',+ user_id: 7+ })+ })+})++describe('auditSummaryParams', () => {+ it("narrows the summary like the list, except by status, so its figures count the list's calls", () => {+ const filters = { period: period('7d'), service: 'gravitino', status: 'error', tool: ' get_table ', userId: 4 }++ const now = new Date('2026-10-22T12:00:00Z')++ expect(auditSummaryParams(filters, now)).toEqual({+ start_date: '2026-10-15T12:00:00.000',+ end_date: '2026-10-22T12:00:00.000',+ service: 'gravitino',+ tool_name: 'get_table',+ user_id: 4+ })+ })++ it('takes the window of the list', () => {+ const filters = { period: DEFAULT_AUDIT_PERIOD }+ const now = new Date('2026-10-22T12:00:00Z')++ expect(auditSummaryParams(filters, now)).toEqual({+ start_date: auditFilterParams(filters, now).start_date,+ end_date: auditFilterParams(filters, now).end_date+ })+ })+})diff --git a/web-v2/web/src/lib/utils/mcpServers.js b/web-v2/web/src/lib/utils/mcpServers.jsnew file mode 100644index 0000000000..32b664cd73--- /dev/null+++ b/web-v2/web/src/lib/utils/mcpServers.js@@ -0,0 +1,41 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++const SECRETS = ['oauth_client_secret', 'basic_auth_password']++// Optional fields that the gateway takes as null, not as an empty string.+const OPTIONAL_URLS = ['oauth_metadata_url']++/**+ * The fields to send for a server from its form. An empty secret keeps the current+ * one; `remove_oauth_client_secret` removes the client secret, which the gateway+ * does when sent an empty one. An empty optional URL is none.+ */+export const serverFields = ({ remove_oauth_client_secret: removeClientSecret, ...values }) => {+ const fields = Object.fromEntries(+ Object.entries(values)+ .filter(([key, value]) => !SECRETS.includes(key) || value)+ .map(([key, value]) => [key, OPTIONAL_URLS.includes(key) && !value ? null : value])+ )++ return removeClientSecret ? { ...fields, oauth_client_secret: '' } : fields+}++// Whether a server has basic auth credentials already, for people or for service accounts.+export const hasBasicAuth = server => server?.auth_type === 'basic' || server?.service_auth_type === 'basic'diff --git a/web-v2/web/src/lib/utils/mcpServers.test.js b/web-v2/web/src/lib/utils/mcpServers.test.jsnew file mode 100644index 0000000000..32f66e1fbd--- /dev/null+++ b/web-v2/web/src/lib/utils/mcpServers.test.js@@ -0,0 +1,60 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++import { describe, expect, it } from 'vitest'+import { hasBasicAuth, serverFields } from './mcpServers'++describe('serverFields', () => {+ it('keeps the current secrets when their fields are empty', () => {+ expect(serverFields({ name: 'Trino', oauth_client_secret: '', basic_auth_password: undefined })).toEqual({+ name: 'Trino'+ })+ expect(serverFields({ oauth_client_secret: 's3cret', basic_auth_password: 'pw' })).toEqual({+ oauth_client_secret: 's3cret',+ basic_auth_password: 'pw'+ })+ })++ it('sends an empty optional URL as none', () => {+ expect(serverFields({ oauth_metadata_url: '' })).toEqual({ oauth_metadata_url: null })+ })++ it('removes the client secret when asked to, by sending an empty one', () => {+ expect(serverFields({ name: 'Trino', remove_oauth_client_secret: true })).toEqual({+ name: 'Trino',+ oauth_client_secret: ''+ })+ expect(serverFields({ oauth_client_secret: 'typed', remove_oauth_client_secret: true })).toEqual({+ oauth_client_secret: ''+ })+ expect(serverFields({ name: 'Trino', remove_oauth_client_secret: false })).toEqual({ name: 'Trino' })+ })+})++describe('hasBasicAuth', () => {+ it('is true when people or service accounts already use basic auth', () => {+ expect(hasBasicAuth({ auth_type: 'basic', service_auth_type: 'passthrough' })).toBe(true)+ expect(hasBasicAuth({ auth_type: 'oauth', service_auth_type: 'basic' })).toBe(true)+ })++ it('is false for a new server, or one without basic auth', () => {+ expect(hasBasicAuth(undefined)).toBe(false)+ expect(hasBasicAuth({ auth_type: 'oauth', service_auth_type: 'passthrough' })).toBe(false)+ })+})diff --git a/web-v2/web/src/lib/utils/mcpServiceAccounts.js b/web-v2/web/src/lib/utils/mcpServiceAccounts.jsnew file mode 100644index 0000000000..c2f346d18c--- /dev/null+++ b/web-v2/web/src/lib/utils/mcpServiceAccounts.js@@ -0,0 +1,46 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++/**+ * A service account's config as a form shows it: the issuer its tokens must come+ * from, and the rest of the config as JSON.+ */+export const splitServiceAccountConfig = config => {+ const { iss, ...rest } = config || {}++ return { issuer: iss || '', rest: Object.keys(rest).length ? JSON.stringify(rest, null, 2) : '' }+}++// The config to save from the form's issuer and JSON, or null for none; the issuer field wins over an `iss` in the JSON.+export const serviceAccountConfig = (issuer, json) => {+ let rest = {}+ if (json?.trim()) {+ try {+ rest = JSON.parse(json)+ } catch {+ rest = null+ }+ if (!rest || typeof rest !== 'object' || Array.isArray(rest)) {+ throw new Error('The configuration must be a JSON object')+ }+ }+ const config = issuer?.trim() ? { ...rest, iss: issuer.trim() } : rest++ return Object.keys(config).length ? config : null+}diff --git a/web-v2/web/src/lib/utils/mcpServiceAccounts.test.js b/web-v2/web/src/lib/utils/mcpServiceAccounts.test.jsnew file mode 100644index 0000000000..1f2aa2c919--- /dev/null+++ b/web-v2/web/src/lib/utils/mcpServiceAccounts.test.js@@ -0,0 +1,59 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++import { describe, expect, it } from 'vitest'+import { serviceAccountConfig, splitServiceAccountConfig } from './mcpServiceAccounts'++describe('service account config', () => {+ it('keeps the pinned issuer apart from the rest of the config', () => {+ const config = {+ iss: 'https://oidc.example.com',+ downstream_credentials: { trino: { secret_ref: 'mcp-gateway-sa-x' } }+ }++ expect(splitServiceAccountConfig(config)).toEqual({+ issuer: 'https://oidc.example.com',+ rest: '{\n "downstream_credentials": {\n "trino": {\n "secret_ref": "mcp-gateway-sa-x"\n }\n }\n}'+ })+ expect(splitServiceAccountConfig(null)).toEqual({ issuer: '', rest: '' })+ })++ it('puts the issuer and the rest back together', () => {+ expect(serviceAccountConfig(' https://oidc.example.com ', '{"a": 1}')).toEqual({+ iss: 'https://oidc.example.com',+ a: 1+ })+ expect(serviceAccountConfig('', '')).toBeNull()+ expect(serviceAccountConfig('', '{}')).toBeNull()+ })++ it('lets the issuer field win over an issuer in the JSON', () => {+ expect(serviceAccountConfig('https://field.example.com', '{"iss": "https://json.example.com"}')).toEqual({+ iss: 'https://field.example.com'+ })+ expect(serviceAccountConfig('', '{"iss": "https://json.example.com"}')).toEqual({+ iss: 'https://json.example.com'+ })+ })++ it('refuses config that is not a JSON object', () => {+ expect(() => serviceAccountConfig('', '[1]')).toThrow('a JSON object')+ expect(() => serviceAccountConfig('', '{oops')).toThrow('a JSON object')+ })+})