bharos commented on code in PR #15108: URL: https://github.com/apache/gravitino/pull/15108#discussion_r4637178340
########## web-v2/web/src/app/mcp/McpGatewayProvider.js: ########## @@ -0,0 +1,126 @@ +/* + * 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, 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 [api, uriError] = useMemo(() => { + try { + return [gatewayUri ? createMcpGatewayApi(gatewayUri) : null, undefined] + } catch (err) { + return [null, err.message] + } + }, [gatewayUri]) + const [me, setMe] = useState() + const [error, setError] = useState() + const [attempt, setAttempt] = useState(0) + const value = useMemo(() => ({ api, me }), [api, me]) + + useEffect(() => { + if (!api || authType !== 'oauth') { Review Comment: Fixed in 5a4a3fa29: the pages and the nav item now also need `gravitino.authenticator.oauth.provider=oidc`, through one `isOidcSignIn` check. ########## web-v2/web/src/app/mcp/audit/AuditDetail.js: ########## @@ -0,0 +1,98 @@ +/* + * 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(() => { + api + .getAuditLog(logId) + .then(setLog) + .catch(error => { + toast.error(gatewayErrorMessage(error)) + onClose() + }) + }, [api, logId, onClose]) Review Comment: Fixed in 5a4a3fa29: an answer that comes after the drawer closed is ignored. ########## web-v2/web/src/app/mcp/servers/ServerDialog.js: ########## @@ -0,0 +1,241 @@ +/* + * 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, Select, Switch } from 'antd' +import toast from 'react-hot-toast' +import { gatewayErrorMessage } from '@/lib/api/mcpGateway' +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 +} + +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'] + +// 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) + + // 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 + + // Empty secret fields keep the current secrets; an empty optional URL is none. + const fields = Object.fromEntries( + Object.entries(values) + .filter(([key, value]) => !SECRETS.includes(key) || value) Review Comment: Fixed in 5a4a3fa29: editing a server that has a client secret offers to remove it, which sends `oauth_client_secret: ''`. The metadata URL is then no longer required. ########## web-v2/web/src/app/mcp/servers/ServerDialog.js: ########## @@ -0,0 +1,241 @@ +/* + * 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, Select, Switch } from 'antd' +import toast from 'react-hot-toast' +import { gatewayErrorMessage } from '@/lib/api/mcpGateway' +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 +} + +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'] + +// 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) + + // 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 + + // Empty secret fields keep the current secrets; an empty optional URL is none. + 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]) + ) + 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> + <Form.Item name='oauth_scopes' label='Scopes'> + <Input placeholder='Optional' /> + </Form.Item> + </> + )} Review Comment: Fixed in 5a4a3fa29: the scopes field shows for both OAuth modes. ########## web-v2/web/src/app/mcp/servers/ServerDialog.js: ########## @@ -0,0 +1,241 @@ +/* + * 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, Select, Switch } from 'antd' +import toast from 'react-hot-toast' +import { gatewayErrorMessage } from '@/lib/api/mcpGateway' +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 +} + +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'] + +// 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) + + // 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 + + // Empty secret fields keep the current secrets; an empty optional URL is none. + 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]) + ) + 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> + <Form.Item name='oauth_scopes' label='Scopes'> + <Input placeholder='Optional' /> + </Form.Item> + </> + )} + {authType === 'oauth' && !singleSignOn && ( + <> + <Form.Item + name='oauth_metadata_url' + label='Authorization server metadata URL' + dependencies={['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), + 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'} /> + </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: !server }]}> + <Input.Password placeholder={server ? 'Unchanged' : ''} /> + </Form.Item> Review Comment: Fixed in 5a4a3fa29: the password is required unless the server already uses basic auth, for people or for service accounts. ########## 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)) Review Comment: Fixed in 5a4a3fa29: the client calls back whenever a call finds nobody signed in, and the provider sends the user to the login page from any page, not only on the first call. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
