diff --git a/docs/development/plugin-architecture.md b/docs/development/plugin-architecture.md index 62495d78..e7a1b5e8 100644 --- a/docs/development/plugin-architecture.md +++ b/docs/development/plugin-architecture.md @@ -307,11 +307,40 @@ when the browser only had a cookie. An unreachable upstream answers 502 and leaves the rest of Console working. SSE and chunked responses stream as they arrive. +The generic proxy does not read plugin Secrets or replace the session with a +backend shared key. A backend requiring another credential needs an agreed +authentication contract before integration can be accepted; do not put keys in +frontend code, inline route headers or an authentication bypass. + +The [shared-credential proposal](plugin-proxy-credentials.md) is deferred; it is +not part of the current Console or Global contract. Regenerate the ReverseProxy +schema with `bash hack/generate-proxy-crd.sh` after changing its Go types. + The plugin's frontend uses the SDK `ApiClient`, which accepts same-origin absolute paths only, attaches the session and throws `ApiError(status, detail)` on a non-2xx response. A 401 is not redirected to the login page; the plugin shows the error. +## Resource action data + +```text +resource snapshot -> plugin data loaders -> plugin-local data -> action policy + +---> presentation / visibility +``` + +- Collection and detail actions receive the same data-extension results as + presentation callbacks, scoped to the owning plugin and resource. +- Data queries include the resource snapshot in their key; a changed assignment + cannot reuse the previous owner's policy. Failed queries withhold stale data. +- Action callbacks stay synchronous. Plugins must explicitly block actions that + require data while that data is loading or unavailable. +- Each action uses its own policy. A denied uninstall does not implicitly deny + SLO editing; read-only and uninstalling resource state still deny writes. +- An open SLO editor stays mounted during policy refresh to retain the draft; + writes remain disabled until the new policy permits them. +- Backend-specific policy resolution belongs in the plugin's data loader, not + in the Console host or a new backend exception. + ## Capabilities `provides` and `consumes` move host-owned values into a plugin without copying diff --git a/docs/development/plugin-proxy-credentials.md b/docs/development/plugin-proxy-credentials.md new file mode 100644 index 00000000..bf4f1979 --- /dev/null +++ b/docs/development/plugin-proxy-credentials.md @@ -0,0 +1,76 @@ +## Status + +Deferred at the user's request. The Secret-reference field and its proxy +implementation are not shipped by Console or Global, and plugin charts must not +declare it. Any future implementation requires a shared cross-host contract. +The sections below retain the proposal, not an installation requirement. + +## Background + +Installed plugins currently receive Console identity headers and the user's session token, but cannot declare the shared backend credential that configured backends already support. Plugin backends should implement a platform contract, not disable credential verification to accommodate the frontend. Canary PR modelsphere/console-canary-plugin#11 is the first consumer. + +## Proposal + +Add optional `spec.directives.authProxySecretRef: {name, key}` to plugin ReverseProxy routes. Console reads the named Secret in the installed plugin release namespace after user authentication and backend IAM authorization, then replaces upstream Authorization with `Bearer `. Existing routes without the field retain their session-forwarding behavior. + +## User experience + +1. A plugin chart creates or references its backend proxy Secret and mounts the same key in the backend. +2. Its ReverseProxy declares only the Secret name/key, never the value. +3. Plugin frontends continue using the SDK; backend teams retain credential and identity validation. + +## Design + +```text +SDK request -> Console session + IAM -> release-scoped Secret lookup + -> overwrite credential + identity -> backend validates both +``` + +### API and configuration + +```yaml +spec: + directives: + authProxy: true + authProxySecretRef: + name: example-proxy + key: proxyKey +``` + +- Reference requires authProxy=true and cannot coexist with skipAuthentication. +- No namespace override or inline credential; name/key syntax is validated. +- An explicit ReverseProxy namespace must match the release namespace when it references credentials. +- Lookup on each authorized request observes Secret rotation/deletion without restart or stale credential fallback. +- Missing/unreadable Secret, missing/empty key, malformed bearer token, or unavailable Kubernetes client fails closed with 502; no upstream request is sent. +- Secret lookup errors expose only an operational error category, not Kubernetes error payloads or Secret values. + +### Security + +- Existing per-backend IAM checks run before Secret access. +- Console strips client-supplied identity headers/Cookie and overwrites Authorization. +- Existing release-namespace Secret read permissions are reused; no automatic RBAC grants, cross-namespace lookup, or cluster-wide Secret permission. +- Plugin installation is a privileged boundary: chart authors already select upstream destinations and release resources. Operators must trust installed packages and review Secret references. +- NetworkPolicy remains defense in depth, not a replacement for backend credential validation. + +### Compatibility and upgrade + +- Additive opt-in field; existing routes unchanged. +- Upgrade Console and apply its updated ReverseProxy CRD before installing a plugin using this field (Helm does not upgrade CRDs automatically). +- This field is a Console extension to Global's ReverseProxy schema; other hosts must implement it before consuming such packages. + +## Alternatives considered + +- Skip backend shared-key checks: changes the trust model and couples frontend integration to backend internals. +- Inline headerUp credential: exposes secrets in release manifests and is not supported by the plugin route validator. +- Canary-specific proxy code: violates the reusable platform boundary. +- Cached credentials: adds stale-key/revocation semantics not needed for the first implementation; measure request volume before adding a bounded cache. + +## Out of scope + +Backend business logic, backend credential-validation changes, live cluster operations, automatic permissions, and PR merging. + +## Rollout + +1. Console contract, schema generator, validation, forwarding tests and documentation. +2. Rework Canary PR #11 to retain existing backend authentication and declare its existing Secret in the chart route. +3. Backend team verifies conformance; installed-environment acceptance follows a host/CRD upgrade. diff --git a/hack/generate-proxy-crd.sh b/hack/generate-proxy-crd.sh new file mode 100644 index 00000000..6a55fca4 --- /dev/null +++ b/hack/generate-proxy-crd.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd "$(dirname "$0")/.." +output=$(mktemp -d) +trap 'rm -rf "$output"' EXIT + +go run sigs.k8s.io/controller-tools/cmd/controller-gen@v0.19.0 \ + crd paths=./internal/iam "output:crd:dir=$output" +cp "$output/iam.theriseunion.io_reverseproxies.yaml" helm/console/crds/ diff --git a/internal/iam/doc.go b/internal/iam/doc.go new file mode 100644 index 00000000..457d7b41 --- /dev/null +++ b/internal/iam/doc.go @@ -0,0 +1,3 @@ +// +groupName=iam.theriseunion.io +// +versionName=v1alpha1 +package iam diff --git a/internal/iam/reverseproxy_schema_test.go b/internal/iam/reverseproxy_schema_test.go new file mode 100644 index 00000000..26689940 --- /dev/null +++ b/internal/iam/reverseproxy_schema_test.go @@ -0,0 +1,35 @@ +package iam + +import ( + "os" + "testing" + + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "sigs.k8s.io/yaml" +) + +func TestReverseProxySchemaUsesExistingAuthProxyContract(t *testing.T) { + data, err := os.ReadFile("../../helm/console/crds/iam.theriseunion.io_reverseproxies.yaml") + if err != nil { + t.Fatal(err) + } + var schema map[string]any + if err := yaml.Unmarshal(data, &schema); err != nil { + t.Fatal(err) + } + versions, found, err := unstructured.NestedSlice(schema, "spec", "versions") + if err != nil || !found || len(versions) != 1 { + t.Fatalf("schema versions: found=%t err=%v", found, err) + } + directives, found, err := unstructured.NestedMap(versions[0].(map[string]any), "schema", "openAPIV3Schema", "properties", "spec", "properties", "directives") + if err != nil || !found { + t.Fatalf("schema directives: found=%t err=%v", found, err) + } + if _, found, err := unstructured.NestedFieldNoCopy(directives, "properties", "authProxySecretRef"); err != nil || found { + t.Fatalf("unsupported Secret reference: found=%t err=%v", found, err) + } + fieldType, found, err := unstructured.NestedString(directives, "properties", "authProxy", "type") + if err != nil || !found || fieldType != "boolean" { + t.Fatalf("authProxy type=%q found=%t err=%v", fieldType, found, err) + } +} diff --git a/internal/pluginregistry/routes_contract_test.go b/internal/pluginregistry/routes_contract_test.go new file mode 100644 index 00000000..02bc4e8d --- /dev/null +++ b/internal/pluginregistry/routes_contract_test.go @@ -0,0 +1,19 @@ +package pluginregistry + +import ( + "testing" + + pluginapi "github.com/modelsphere/console/api/plugin/v1alpha1" +) + +func TestReadRoutesRejectsUnsupportedSecretExtension(t *testing.T) { + meta := &pluginapi.PluginMeta{Group: "rise.io", APIVersion: "v1", Name: "example"} + manifest := reverseProxyManifest("/api/example/*") + if _, err := readRoutes(manifest, meta); err != nil { + t.Fatalf("existing authProxy contract: %v", err) + } + manifest += " authProxySecretRef:\n name: example-proxy\n key: proxyKey\n" + if _, err := readRoutes(manifest, meta); err == nil { + t.Fatal("accepted unsupported Secret extension") + } +} diff --git a/internal/server/plugin_session_test.go b/internal/server/plugin_session_test.go new file mode 100644 index 00000000..31780a79 --- /dev/null +++ b/internal/server/plugin_session_test.go @@ -0,0 +1,48 @@ +package server + +import ( + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "testing" + + "k8s.io/apimachinery/pkg/runtime" + dynamicfake "k8s.io/client-go/dynamic/fake" + k8stesting "k8s.io/client-go/testing" +) + +func TestPluginProxyForwardsSessionWithoutSecretReads(t *testing.T) { + var received http.Header + upstream := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + received = request.Header.Clone() + writer.WriteHeader(http.StatusNoContent) + })) + t.Cleanup(upstream.Close) + target, err := url.Parse(upstream.URL) + if err != nil { + t.Fatal(err) + } + srv, handler, admin, _ := pluginRegistryServer(t, registeredEntry(t, target)) + srv.kube.Dynamic().(*dynamicfake.FakeDynamicClient).PrependReactor("get", "secrets", func(k8stesting.Action) (bool, runtime.Object, error) { + t.Error("plugin authProxy must not read backend Secrets") + return true, nil, fmt.Errorf("unexpected Secret read") + }) + for _, cookie := range []bool{false, true} { + request := httptest.NewRequest(http.MethodGet, "/api/example/ping", nil) + if cookie { + request.AddCookie(&http.Cookie{Name: "token", Value: admin}) + } else { + request.Header.Set("Authorization", "Bearer "+admin) + } + request.Header.Set("X-Remote-User", "forged") + response := httptest.NewRecorder() + handler.ServeHTTP(response, request) + if response.Code != http.StatusNoContent { + t.Fatalf("proxy status=%d body=%s", response.Code, response.Body.String()) + } + if received.Get("Authorization") != "Bearer "+admin || received.Get("X-Remote-User") != "admin" || received.Get("Cookie") != "" { + t.Fatal("proxy must preserve the session and verified identity without forwarding cookies") + } + } +} diff --git a/web/src/extensions/data.ts b/web/src/extensions/data.ts index f77ed9aa..c014e0fa 100644 --- a/web/src/extensions/data.ts +++ b/web/src/extensions/data.ts @@ -1,5 +1,10 @@ import type { ResourceDataExtension } from "./types"; +export interface LoadedResourceData { + extensions: readonly Pick[]; + values: readonly unknown[]; +} + /** * Plugin-local data map for one extension callback. * diff --git a/web/src/extensions/queries.test.tsx b/web/src/extensions/queries.test.tsx new file mode 100644 index 00000000..e96828ea --- /dev/null +++ b/web/src/extensions/queries.test.tsx @@ -0,0 +1,45 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { renderToStaticMarkup } from "react-dom/server"; +import { afterEach, describe, expect, it } from "vitest"; +import { extensions } from "./registry"; +import { resourceDataQueryKey, useResourceActions } from "./queries"; + +const extension = { plugin: "example", id: "policy", resourceType: "service", load: () => ({ canEdit: true }) }; +const original = { assignedTo: "first" }; + +function Policy({ resource = original }: { resource?: unknown }) { + const evaluate = useResourceActions("service", [{ resourceKey: "ns/name", resource }]); + return {evaluate("ns/name", resource, "slo") || "editable"}; +} + +function renderPolicy(client: QueryClient, resource: unknown = original) { + return renderToStaticMarkup(); +} + +afterEach(() => { + extensions.data.length = 0; + extensions.actions.length = 0; +}); + +describe("resource action queries", () => { + it("does not reuse policy data after the resource's assignment changes", () => { + extensions.data.push(extension); + extensions.actions.push({ plugin: "example", id: "slo", resourceType: "service", action: "slo", evaluate: ({ data }) => (data.policy as { canEdit?: boolean })?.canEdit ? false : "unavailable" }); + const client = new QueryClient(); + client.setQueryData(resourceDataQueryKey(extension, "service", "ns/name", original), { canEdit: true }); + expect(renderPolicy(client)).toContain("editable"); + expect(renderPolicy(client, { assignedTo: "second" })).toContain("unavailable"); + client.clear(); + }); + + it("withholds stale successful data when the refresh has failed", () => { + extensions.data.push(extension); + extensions.actions.push({ plugin: "example", id: "slo", resourceType: "service", action: "slo", evaluate: ({ data }) => data.policy ? false : "unavailable" }); + const client = new QueryClient({ defaultOptions: { queries: { retryOnMount: false } } }); + const queryKey = resourceDataQueryKey(extension, "service", "ns/name", original); + client.setQueryData(queryKey, { canEdit: true }); + client.getQueryCache().find({ queryKey })!.setState({ status: "error", error: new Error("offline") }); + expect(renderPolicy(client)).toContain("unavailable"); + client.clear(); + }); +}); diff --git a/web/src/extensions/queries.ts b/web/src/extensions/queries.ts new file mode 100644 index 00000000..f0758cf5 --- /dev/null +++ b/web/src/extensions/queries.ts @@ -0,0 +1,43 @@ +import { useQueries } from "@tanstack/react-query"; +import type { LoadedResourceData } from "./data"; +import { evaluateResourceAction, extensions } from "./registry"; +import type { ResourceDataExtension } from "./types"; + +interface ExtensionResource { + resourceKey: string; + resource: unknown; +} + +export function resourceDataQueryKey(extension: Pick, resourceType: string, resourceKey: string, resource: unknown) { + return ["extension-data", extension.plugin, extension.id, resourceType, resourceKey, resource]; +} + +export function useResourceExtensionData(resourceType: string, resources: readonly ExtensionResource[]): Map { + const dataExtensions = extensions.data.filter((extension) => extension.resourceType === resourceType); + const queries = useQueries({ + queries: resources.flatMap(({ resourceKey, resource }) => dataExtensions.map((extension) => ({ + queryKey: resourceDataQueryKey(extension, resourceType, resourceKey, resource), + queryFn: async () => { + try { + return (await extension.load({ resourceType, resourceKey, resource })) ?? null; + } catch (error) { + console.error(`[console] resource data failed: ${extension.plugin}/${extension.id}`, error); + throw error; + } + }, + staleTime: 30_000, + retry: false, + }))), + }); + return new Map(resources.map(({ resourceKey }, index) => [resourceKey, { + extensions: dataExtensions, + values: queries.slice(index * dataExtensions.length, (index + 1) * dataExtensions.length) + .map((query) => query.isError ? undefined : query.data), + }])); +} + +export function useResourceActions(resourceType: string, resources: readonly ExtensionResource[]) { + const loaded = useResourceExtensionData(resourceType, resources); + return (resourceKey: string, resource: unknown, action: string) => + evaluateResourceAction(resourceType, resourceKey, resource, action, loaded.get(resourceKey)); +} diff --git a/web/src/extensions/registry.test.ts b/web/src/extensions/registry.test.ts new file mode 100644 index 00000000..1a46b278 --- /dev/null +++ b/web/src/extensions/registry.test.ts @@ -0,0 +1,27 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { evaluateResourceAction, extensions } from "./registry"; + +afterEach(() => { extensions.actions.length = 0; }); + +describe("resource action data", () => { + it("supplies only the owning plugin's loaded data to its action", () => { + const evaluate = vi.fn(({ data }) => data.policy?.canEdit ? false : "locked"); + extensions.actions.push({ plugin: "alpha", id: "slo", resourceType: "service", action: "slo", evaluate }); + const loaded = { + extensions: [{ plugin: "beta", id: "policy" }, { plugin: "alpha", id: "policy" }], + values: [{ canEdit: false }, { canEdit: true }], + }; + expect(evaluateResourceAction("service", "ns/name", {}, "slo", loaded)).toBe(false); + expect(evaluate.mock.calls[0][0].data).toEqual({ policy: { canEdit: true } }); + }); + + it("keeps an unresolved policy unavailable rather than borrowing another plugin's result", () => { + extensions.actions.push({ + plugin: "alpha", id: "slo", resourceType: "service", action: "slo", + evaluate: ({ data }) => data.policy ? false : "unavailable", + }); + expect(evaluateResourceAction("service", "ns/name", {}, "slo", { + extensions: [{ plugin: "beta", id: "policy" }], values: [{ canEdit: true }], + })).toBe("unavailable"); + }); +}); diff --git a/web/src/extensions/registry.ts b/web/src/extensions/registry.ts index e85c2334..d7910ce1 100644 --- a/web/src/extensions/registry.ts +++ b/web/src/extensions/registry.ts @@ -5,6 +5,7 @@ import type { ResourcePresentationExtension, ResourceVisibilityExtension, } from "./types"; +import { dataForPlugin, type LoadedResourceData } from "./data"; export const extensions: ConsoleExtensions = { modules: [], @@ -43,12 +44,14 @@ export function evaluateResourceAction( resourceKey: string, resource: T, action: string, + loaded: LoadedResourceData = { extensions: [], values: [] }, ): false | string { - const context = { resourceType, resourceKey, resource, data: {}, action }; + const context = { resourceType, resourceKey, resource, action }; for (const extension of extensions.actions) { if (extension.resourceType !== resourceType || extension.action !== action) continue; try { - const blocked = extension.evaluate(context); + const data = dataForPlugin(loaded.extensions, loaded.values, extension.plugin); + const blocked = extension.evaluate({ ...context, data }); if (blocked) return blocked; } catch (error) { console.error(`[console] resource action policy failed: ${extension.plugin}/${extension.id}`, error); diff --git a/web/src/extensions/surface.tsx b/web/src/extensions/surface.tsx index 03883e02..716b8709 100644 --- a/web/src/extensions/surface.tsx +++ b/web/src/extensions/surface.tsx @@ -1,7 +1,7 @@ -import { useQueries } from "@tanstack/react-query"; import type { ReactNode } from "react"; import { dataForPlugin } from "./data"; import { extensions } from "./registry"; +import { useResourceExtensionData } from "./queries"; interface ResourceExtensionSurfaceProps { resourceType: string; @@ -18,20 +18,13 @@ export function ResourceExtensionSurface({ placement, fallback = null, }: ResourceExtensionSurfaceProps) { - const dataExtensions = extensions.data.filter((extension) => extension.resourceType === resourceType); + const loaded = useResourceExtensionData(resourceType, [{ resourceKey, resource }]).get(resourceKey)!; const presentations = extensions.presentations.filter( (extension) => extension.resourceType === resourceType && extension.placement === placement, ); - const queries = useQueries({ - queries: dataExtensions.map((extension) => ({ - queryKey: ["extension-data", extension.plugin, extension.id, resourceType, resourceKey], - queryFn: () => extension.load({ resourceType, resourceKey, resource }), - staleTime: 30_000, - })), - }); if (presentations.length === 0) return fallback; - const values = queries.map((query) => query.data); + const { extensions: dataExtensions, values } = loaded; const context = { resourceType, resourceKey, resource }; return ( <> diff --git a/web/src/modules/inferences/InferenceDetail.tsx b/web/src/modules/inferences/InferenceDetail.tsx index 967343d2..61771c59 100644 --- a/web/src/modules/inferences/InferenceDetail.tsx +++ b/web/src/modules/inferences/InferenceDetail.tsx @@ -13,7 +13,7 @@ import { Endpoint } from "@swiss/components/Endpoint"; import { Provenance } from "@swiss/components/Provenance"; import { useT } from "@/modules/inferences/i18n"; import { modelLine, parseTab, releaseState, sloBlocked, visibleTabs, type Tab } from "@/modules/inferences/lib"; -import { evaluateResourceAction } from "@/extensions/registry"; +import { useResourceActions } from "@/extensions/queries"; import { ResourceExtensionSurface } from "@/extensions/surface"; import { statusOf } from "@/modules/inferences/components/StatusDot"; import { DeploySheet } from "@/modules/inferences/components/DeploySheet"; @@ -66,6 +66,8 @@ export function InferenceDetail() { }); const s = status.data; + const resourceKey = `${namespace}/${release}`; + const evaluateAction = useResourceActions("inference-service", s ? [{ resourceKey, resource: s }] : []); const visible = visibleTabs({ plan: !!plan.data }); const tab = parseTab(search.get("tab"), visible); const setTab = (next: Tab, pod?: string) => @@ -108,18 +110,18 @@ export function InferenceDetail() { const readOnly = cluster.data ? !cluster.data.allowDeploy : false; const removing = isUninstalling(s); - const resourceKey = `${namespace}/${release}`; - const actionBlocked = (action: string) => evaluateResourceAction("inference-service", resourceKey, s, action); - const blockedWrite = actionBlocked("uninstall") || (readOnly ? t("disabled.readOnly") : removing ? t("disabled.uninstalling") : false); - const upgradeBlocked = actionBlocked("upgrade") || (readOnly ? t("disabled.readOnly") : removing ? t("disabled.uninstalling") : false); - const sloBlockedByExtension = actionBlocked("slo"); + const actionBlocked = (action: string) => evaluateAction(resourceKey, s, action); + const writeUnavailable = readOnly ? t("disabled.readOnly") : removing ? t("disabled.uninstalling") : false; + const blockedWrite = actionBlocked("uninstall") || writeUnavailable; + const upgradeBlocked = actionBlocked("upgrade") || writeUnavailable; + const sloBlockedByExtension = actionBlocked("slo") || writeUnavailable; const external = s.external; const untracked = !plan.data && plan.isError; const source = plan.data?.source; const model = modelLine(source ?? {}) || s.model; const pods = s.pods.map((p) => p.name); const blocked = sloBlocked(s, plan.data); - const sloOpen = !sloBlockedByExtension && !removing && (editingSLO || (sloSetup && blocked !== "off" && s.planStatus?.phase !== "failed")); + const sloOpen = !removing && (editingSLO || (sloSetup && blocked !== "off" && s.planStatus?.phase !== "failed")); const closeSLO = () => { setEditingSLO(false); if (!sloSetup) return; @@ -142,7 +144,7 @@ export function InferenceDetail() { { key: "slo", label: t("actions.slo"), - disabled: sloBlockedByExtension || blockedWrite || (external ? t("disabled.external") : blocked === "off" ? t("disabled.sloOff") : blocked === "pending" ? t("disabled.sloPending") : false), + disabled: sloBlockedByExtension || (external ? t("disabled.external") : blocked === "off" ? t("disabled.sloOff") : blocked === "pending" ? t("disabled.sloPending") : false), onClick: () => setEditingSLO(true), }, { diff --git a/web/src/modules/inferences/InferenceList.tsx b/web/src/modules/inferences/InferenceList.tsx index 9a122fbc..449de7f8 100644 --- a/web/src/modules/inferences/InferenceList.tsx +++ b/web/src/modules/inferences/InferenceList.tsx @@ -19,7 +19,7 @@ import { isUninstalling } from "@swiss/lib/phase"; import { pollOptions, usePollingPaused } from "@swiss/lib/polling"; import { useT } from "@/modules/inferences/i18n"; import { detailPath, modelLine, rowState } from "@/modules/inferences/lib"; -import { evaluateResourceAction } from "@/extensions/registry"; +import { useResourceActions } from "@/extensions/queries"; import { ResourceExtensionSurface } from "@/extensions/surface"; import { StatusDot } from "@/modules/inferences/components/StatusDot"; import { DeploySheet, type DeployTarget } from "@/modules/inferences/components/DeploySheet"; @@ -52,6 +52,7 @@ export function InferenceList() { const readOnly = cluster.data ? !cluster.data.allowDeploy : false; const rows: Row[] = (list.data?.deployments ?? []).map((d) => ({ ...d, key: `${d.namespace}/${d.release}` })); + const evaluateAction = useResourceActions("inference-service", rows.map((resource) => ({ resourceKey: resource.key, resource }))); const open = (d: Deployment) => navigate(p(detailPath(d.release, d.namespace))); const columns: ResourceColumn[] = [ @@ -107,7 +108,7 @@ export function InferenceList() { const writeBlocked = (d: Deployment, untracked = false, adaptive = false): boolean | string => { const action = adaptive ? "upgrade" : "uninstall"; - const extensionBlocked = evaluateResourceAction("inference-service", `${d.namespace}/${d.release}`, d, action); + const extensionBlocked = evaluateAction(`${d.namespace}/${d.release}`, d, action); if (extensionBlocked) return extensionBlocked; return readOnly ? t("disabled.readOnly") : isUninstalling(d) ? t("disabled.uninstalling") : untracked && d.external ? t("disabled.external") : untracked && !d.model ? t("disabled.untracked") : false; }; diff --git a/web/src/modules/inferences/uninstalling.test.tsx b/web/src/modules/inferences/uninstalling.test.tsx index 2df23e8c..1e805c6a 100644 --- a/web/src/modules/inferences/uninstalling.test.tsx +++ b/web/src/modules/inferences/uninstalling.test.tsx @@ -1,4 +1,4 @@ -import { describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { renderToStaticMarkup } from "react-dom/server"; import { MemoryRouter, Route, Routes } from "react-router"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; @@ -6,6 +6,13 @@ import type { Deployment, Plan, ReleaseStatus } from "@swiss/lib/api"; import { ModuleProvider } from "@/shell/module"; import { InferenceDetail } from "@/modules/inferences/InferenceDetail"; import { InferenceList } from "@/modules/inferences/InferenceList"; +import { extensions } from "@/extensions/registry"; +import { resourceDataQueryKey } from "@/extensions/queries"; + +vi.mock("@/modules/inferences/components/SLOSheet", () => ({ + SLOSheet: ({ target, canEdit }: { target: { release: string } | null; canEdit: boolean }) => + target ?
: null, +})); const module = { id: "inferences", title: "模型服务", basePath: "/inferences", pages: [] }; const cluster = { name: "c", profile: "p", catalog: "u", version: "0", allowDeploy: true }; @@ -72,8 +79,7 @@ function renderList(rows: Deployment[]) { ); } -function renderDetail(status: ReleaseStatus) { - const c = client(); +function renderDetail(status: ReleaseStatus, c = client(), sloSetup = false) { c.setQueryData(["cluster"], cluster); c.setQueryData(["status", "models", "qwen"], status); c.setQueryData(["releasePlan", "models", "qwen"], plan); @@ -84,7 +90,7 @@ function renderDetail(status: ReleaseStatus) { return renderToStaticMarkup( - + } /> @@ -94,6 +100,46 @@ function renderDetail(status: ReleaseStatus) { ); } +afterEach(() => { + extensions.actions.length = 0; + extensions.data.length = 0; +}); + +describe("independent action policies", () => { + it("uses loaded SLO policy without inheriting the uninstall lock", () => { + const status = release(); + const c = client(); + const dataExtension = { plugin: "example", id: "policy", resourceType: "inference-service", load: () => ({ canEdit: true }) }; + extensions.data.push(dataExtension); + extensions.actions.push( + { plugin: "example", id: "uninstall", resourceType: "inference-service", action: "uninstall", evaluate: () => "assigned" }, + { plugin: "example", id: "slo", resourceType: "inference-service", action: "slo", evaluate: ({ data }) => (data.policy as { canEdit?: boolean })?.canEdit ? false : "unavailable" }, + ); + c.setQueryData(resourceDataQueryKey(dataExtension, "inference-service", "models/qwen", status), { canEdit: true }); + const html = renderDetail(status, c); + expect(button(html, "编辑 SLO")?.disabled).toBe(false); + expect(button(html, "卸载")?.disabled).toBe(true); + c.clear(); + }); + + it("keeps an open SLO editor mounted but read-only while refreshed policy is unavailable", () => { + const status = release(); + const c = client(); + const dataExtension = { plugin: "example", id: "policy", resourceType: "inference-service", load: () => ({ canEdit: true }) }; + extensions.data.push(dataExtension); + extensions.actions.push({ plugin: "example", id: "slo", resourceType: "inference-service", action: "slo", evaluate: ({ data }) => (data.policy as { canEdit?: boolean })?.canEdit ? false : "unavailable" }); + c.setQueryData(resourceDataQueryKey(dataExtension, "inference-service", "models/qwen", status), { canEdit: true }); + expect(renderDetail(status, c, true)).toContain('data-slo-editor="qwen" data-can-edit="true"'); + const refreshed = release({ ready: 0 }); + const pending = renderDetail(refreshed, c, true); + expect(pending).toContain('data-slo-editor="qwen" data-can-edit="false"'); + expect(button(pending, "编辑 SLO")?.disabled).toBe(true); + c.setQueryData(resourceDataQueryKey(dataExtension, "inference-service", "models/qwen", refreshed), { canEdit: true }); + expect(renderDetail(refreshed, c, true)).toContain('data-slo-editor="qwen" data-can-edit="true"'); + c.clear(); + }); +}); + describe("inference list while a deployment is uninstalling", () => { const html = renderList([ deployment({ release: "going", phase: "uninstalling", status: undefined, revision: undefined, chart: undefined }),