From 78e37add3d51e5089b10975633de021efa77e06c Mon Sep 17 00:00:00 2001 From: imneov Date: Tue, 24 Nov 2026 10:57:44 +0800 Subject: [PATCH 1/3] feat(server): inject shared credentials for plugin proxy routes Resolve release-scoped Secret references after session and IAM checks. Fail closed on unavailable credentials, observe rotation on each request, and preserve backend identity validation. Fixes #148 --- docs/console-design.md | 15 ++ docs/development/plugin-architecture.md | 36 +++++ docs/development/plugin-proxy-credentials.md | 69 ++++++++ docs/development/plugins.md | 9 ++ hack/generate-proxy-crd.sh | 10 ++ .../iam.theriseunion.io_reverseproxies.yaml | 23 +++ internal/iam/doc.go | 3 + internal/iam/reverseproxy_schema_test.go | 39 +++++ internal/iam/reverseproxy_types.go | 17 ++ internal/pluginregistry/credentials_test.go | 50 ++++++ internal/pluginregistry/release.go | 5 + internal/pluginregistry/routes.go | 9 ++ internal/server/plugin_credentials.go | 47 ++++++ internal/server/plugin_credentials_test.go | 148 ++++++++++++++++++ internal/server/plugin_registry.go | 9 +- 15 files changed, 487 insertions(+), 2 deletions(-) create mode 100644 docs/development/plugin-proxy-credentials.md create mode 100644 hack/generate-proxy-crd.sh create mode 100644 internal/iam/doc.go create mode 100644 internal/iam/reverseproxy_schema_test.go create mode 100644 internal/pluginregistry/credentials_test.go create mode 100644 internal/server/plugin_credentials.go create mode 100644 internal/server/plugin_credentials_test.go diff --git a/docs/console-design.md b/docs/console-design.md index b31cd86e..d5f10e40 100644 --- a/docs/console-design.md +++ b/docs/console-design.md @@ -779,6 +779,21 @@ in [#145](https://github.com/modelsphere/console/issues/145) and the | Navigation | Build the active composition directly from the shared registry; retain route guards and all three appearance layouts | | Dashboard status | Original Charts install and original resource lists/details work through current-cluster context, business-entry composition and existing-authorized backend proxies | +## Plugin proxy credentials + +The shared-credential contract is recorded in [design #148](https://github.com/modelsphere/console/issues/148) +and [the implementation design](development/plugin-proxy-credentials.md). + +| Owner | Responsibility | +| --- | --- | +| Console | Authenticate users, enforce backend IAM, read the release-scoped Secret and inject the shared credential | +| Plugin chart | Declare `authProxySecretRef` and configure the backend with the same Secret/key | +| Backend team | Validate the credential and user identity; frontend integration must not disable those checks | +| Frontend | Use the same-origin SDK without handling backend credentials | + +Existing routes remain compatible. Secret lookup fails closed and runs per +authorized request so rotation and revocation do not depend on a cached key. + ## Known debt - **The token preset is Tailwind 3-style**, loaded through `@config`. A Tailwind 4 diff --git a/docs/development/plugin-architecture.md b/docs/development/plugin-architecture.md index 62495d78..afe90600 100644 --- a/docs/development/plugin-architecture.md +++ b/docs/development/plugin-architecture.md @@ -307,6 +307,42 @@ 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. +Plugins that validate a shared proxy credential declare a Secret reference: + +```yaml +spec: + directives: + authProxy: true + authProxySecretRef: + name: example-proxy + key: proxyKey +``` + +| Boundary | Contract | +| --- | --- | +| Frontend | Uses the SDK and the user's session; never holds the proxy key | +| Console | Authenticates and authorizes first, then reads the release-namespace Secret and overwrites `Authorization: Bearer ` | +| Backend | Validates the shared credential and requires Console's `X-Remote-User`; backend owners implement this contract | +| Installation | Configures the same Secret/key for Console's route and the backend; no inline credentials or automatic permission grants | + +- The reference is optional for existing routes, but requires `authProxy: true` + and forbids `skipAuthentication`. No namespace override is supported. +- Secret data is a raw RFC 6750 bearer token (no `Bearer ` prefix or whitespace). +- Missing/unreadable Secrets, missing/empty/invalid keys and unavailable clients + return 502 without contacting the upstream or falling back to a user token. +- Secrets are read on every authorized request. Rotation/deletion takes effect + on the next request; backend environment variables still require its rollout. +- The release namespace is the lookup boundary. An explicitly different route + namespace is rejected. Existing Secret read RBAC is reused, not expanded. +- Only trusted operators may install packages: their charts choose upstream + destinations and Secret references. NetworkPolicy remains defense in depth. +- Upgrade Console and its ReverseProxy CRD before installing consumers. Helm + does not update CRDs on upgrade. This optional field is a Console extension; + other Global-compatible hosts must implement it before using these packages. + +Regenerate the schema with `bash hack/generate-proxy-crd.sh`. See +[the credential design](plugin-proxy-credentials.md) for rollout and alternatives. + 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 diff --git a/docs/development/plugin-proxy-credentials.md b/docs/development/plugin-proxy-credentials.md new file mode 100644 index 00000000..ddd2fa2b --- /dev/null +++ b/docs/development/plugin-proxy-credentials.md @@ -0,0 +1,69 @@ +## 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/docs/development/plugins.md b/docs/development/plugins.md index 606114fd..60cfd74b 100644 --- a/docs/development/plugins.md +++ b/docs/development/plugins.md @@ -307,6 +307,15 @@ Registration requires every `ReverseProxy` in the release to satisfy: - `directives.authProxy: true`; - `upstream.scheme` is `http` or `https`, `host` is non-empty, `port` is 1–65535. +If the backend requires a shared proxy key, add +`directives.authProxySecretRef: {name: my-plugin-proxy, key: proxyKey}` and +configure the backend with the same release-namespace Secret. Console reads it +after IAM authorization and overwrites the upstream Bearer credential; the +frontend never receives it. Missing or invalid credentials fail closed with 502. +This requires a host and ReverseProxy CRD implementing the +[shared-credential contract](plugin-architecture.md#backend-contract); upgrading a +Helm release alone does not upgrade its CRDs. + Add an IAM role pair so users can reach the backend. Console authorizes each request on resource `backends` with resource name equal to the plugin name: 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/helm/console/crds/iam.theriseunion.io_reverseproxies.yaml b/helm/console/crds/iam.theriseunion.io_reverseproxies.yaml index 73e78b69..547f8a74 100644 --- a/helm/console/crds/iam.theriseunion.io_reverseproxies.yaml +++ b/helm/console/crds/iam.theriseunion.io_reverseproxies.yaml @@ -61,6 +61,25 @@ spec: authProxy: description: Enable authentication proxy type: boolean + authProxySecretRef: + description: Shared proxy credential in the installed plugin release + namespace. Requires authProxy. + properties: + key: + description: Key containing the raw bearer token, without + the Bearer prefix. + maxLength: 253 + minLength: 1 + type: string + name: + description: Secret name in the installed plugin release namespace. + maxLength: 253 + minLength: 1 + type: string + required: + - key + - name + type: object headerDown: description: Response header modifications items: @@ -123,6 +142,10 @@ spec: description: Wrap transport for additional processing type: boolean type: object + x-kubernetes-validations: + - message: authProxySecretRef requires authProxy without skipAuthentication + rule: '!has(self.authProxySecretRef) || (has(self.authProxy) && + self.authProxy && (!has(self.skipAuthentication) || !self.skipAuthentication))' matcher: description: Request matching rules properties: 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..8f552a7f --- /dev/null +++ b/internal/iam/reverseproxy_schema_test.go @@ -0,0 +1,39 @@ +package iam + +import ( + "os" + "testing" + + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "sigs.k8s.io/yaml" +) + +func TestReverseProxySchemaPreservesSecretReference(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) + } + required, found, err := unstructured.NestedStringSlice(directives, "properties", "authProxySecretRef", "required") + if err != nil || !found || len(required) != 2 || required[0] != "key" || required[1] != "name" { + t.Fatalf("Secret reference required fields=%v err=%v", required, err) + } + validations, found, err := unstructured.NestedSlice(directives, "x-kubernetes-validations") + if err != nil || !found || len(validations) != 1 { + t.Fatalf("credential authentication validation: found=%t err=%v", found, err) + } + if validations[0].(map[string]any)["rule"] != "!has(self.authProxySecretRef) || (has(self.authProxy) && self.authProxy && (!has(self.skipAuthentication) || !self.skipAuthentication))" { + t.Fatal("Secret references must require authentication and reject public routes") + } +} diff --git a/internal/iam/reverseproxy_types.go b/internal/iam/reverseproxy_types.go index b8b05093..b3c4e917 100644 --- a/internal/iam/reverseproxy_types.go +++ b/internal/iam/reverseproxy_types.go @@ -58,11 +58,16 @@ func (u *ReverseProxyUpstream) RawURL() string { } // ReverseProxyDirectives defines proxy behavior and transformation rules +// +kubebuilder:validation:XValidation:rule="!has(self.authProxySecretRef) || (has(self.authProxy) && self.authProxy && (!has(self.skipAuthentication) || !self.skipAuthentication))",message="authProxySecretRef requires authProxy without skipAuthentication" type ReverseProxyDirectives struct { // Enable authentication proxy // +optional AuthProxy bool `json:"authProxy,omitempty"` + // Shared proxy credential in the installed plugin release namespace. Requires authProxy. + // +optional + AuthProxySecretRef *ProxySecretReference `json:"authProxySecretRef,omitempty"` + // Skip host authentication and authorization for matching requests; upstream must authenticate. // Mutually exclusive with authProxy. // +optional @@ -101,6 +106,18 @@ type ReverseProxyDirectives struct { Replace []ReverseProxyReplaceRule `json:"replace,omitempty"` } +// ProxySecretReference selects a required bearer credential without exposing its value. +type ProxySecretReference struct { + // Secret name in the installed plugin release namespace. + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=253 + Name string `json:"name"` + // Key containing the raw bearer token, without the Bearer prefix. + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=253 + Key string `json:"key"` +} + // ReverseProxyRewriteRule defines path rewriting rules type ReverseProxyRewriteRule struct { // Source pattern (regex) diff --git a/internal/pluginregistry/credentials_test.go b/internal/pluginregistry/credentials_test.go new file mode 100644 index 00000000..075c911b --- /dev/null +++ b/internal/pluginregistry/credentials_test.go @@ -0,0 +1,50 @@ +package pluginregistry + +import ( + "context" + "strings" + "testing" + + pluginapi "github.com/modelsphere/console/api/plugin/v1alpha1" + "helm.sh/helm/v3/pkg/release" +) + +func TestReadRoutesValidatesProxySecretReference(t *testing.T) { + manifest := reverseProxyManifest("/api/example/*") + " authProxySecretRef:\n name: example-proxy\n key: proxyKey\n" + meta := &pluginapi.PluginMeta{Group: "rise.io", APIVersion: "v1", Name: "example"} + routes, err := readRoutes(manifest, meta) + if err != nil || len(routes) != 1 { + t.Fatalf("valid reference: routes=%v err=%v", routes, err) + } + for _, invalid := range []string{ + strings.Replace(manifest, "name: example-proxy", "name: ''", 1), + strings.Replace(manifest, "name: example-proxy", "name: ../other", 1), + strings.Replace(manifest, "key: proxyKey", "key: ''", 1), + strings.Replace(manifest, "key: proxyKey", "key: bad/key", 1), + strings.Replace(manifest, "key: proxyKey", "key: proxyKey\n namespace: other", 1), + strings.Replace(manifest, "authProxy: true", "authProxy: false", 1), + strings.Replace(strings.Replace(manifest, "authProxy: true", "skipAuthentication: true", 1), "path: /api/example/*", "method: GET\n path: /oapis/rise.io/v1/example/*", 1), + } { + if _, err := readRoutes(invalid, meta); err == nil { + t.Fatalf("accepted invalid credential reference: %s", invalid) + } + } +} + +func TestCredentialRouteNamespaceMatchesRelease(t *testing.T) { + for _, namespace := range []string{"", "console-system", "other"} { + t.Run(namespace, func(t *testing.T) { + registry, _, plugin := registryFixture(t) + installed := installedRelease() + installed.Manifest = reverseProxyManifest("/api/example/*") + " authProxySecretRef:\n name: example-proxy\n key: proxyKey\n" + if namespace != "" { + installed.Manifest = strings.Replace(installed.Manifest, " name: example\n", " name: example\n namespace: "+namespace+"\n", 1) + } + registry.read = func(context.Context, string, string) (*release.Release, error) { return installed, nil } + _, err := registry.load(t.Context(), plugin) + if (err != nil) != (namespace == "other") { + t.Fatalf("namespace %q: %v", namespace, err) + } + }) + } +} diff --git a/internal/pluginregistry/release.go b/internal/pluginregistry/release.go index f5abbbad..db01688e 100644 --- a/internal/pluginregistry/release.go +++ b/internal/pluginregistry/release.go @@ -95,6 +95,11 @@ func (r *Registry) load(ctx context.Context, plugin *pluginapi.Plugin) (*Entry, if err != nil { return nil, err } + for _, route := range entry.Routes { + if route.Spec.Directives.AuthProxySecretRef != nil && route.Namespace != "" && route.Namespace != plugin.Spec.Chart.Namespace { + return nil, fmt.Errorf("plugin proxy credential route must be in the installed release namespace") + } + } entry.Plugin.Status = pluginapi.PluginStatus{Phase: pluginapi.PluginPhaseInstalled, ObservedGeneration: plugin.Generation, ReleaseName: installed.Name, ReleaseVersion: installed.Version, PluginMeta: meta, FrontendStatus: &pluginapi.FrontendStatus{Distributed: true, EntryURL: "/plugins/" + plugin.Name + "/" + meta.Frontend.Entry}} return entry, nil } diff --git a/internal/pluginregistry/routes.go b/internal/pluginregistry/routes.go index 21b2d1a4..ed887d3c 100644 --- a/internal/pluginregistry/routes.go +++ b/internal/pluginregistry/routes.go @@ -10,6 +10,7 @@ import ( pluginapi "github.com/modelsphere/console/api/plugin/v1alpha1" "github.com/modelsphere/console/internal/config" "github.com/modelsphere/console/internal/iam" + "k8s.io/apimachinery/pkg/util/validation" "k8s.io/apimachinery/pkg/util/yaml" sigyaml "sigs.k8s.io/yaml" ) @@ -51,6 +52,14 @@ func validateRoute(route Route, meta *pluginapi.PluginMeta) error { return fmt.Errorf("plugin ReverseProxy prefix %q is reserved by console", prefix) } directives := route.Spec.Directives + if reference := directives.AuthProxySecretRef; reference != nil { + if !directives.AuthProxy || directives.SkipAuthentication { + return fmt.Errorf("plugin proxy credential requires authProxy without skipAuthentication") + } + if len(validation.IsDNS1123Subdomain(reference.Name)) != 0 || reference.Key == "" || len(validation.IsConfigMapKey(reference.Key)) != 0 { + return fmt.Errorf("plugin proxy credential requires a valid Secret name and key") + } + } if directives.SkipAuthentication { owned := "/oapis/" + meta.Group + "/" + meta.APIVersion + "/" + meta.Name if prefix != owned || route.Spec.Matcher.Method != "GET" || directives.AuthProxy { diff --git a/internal/server/plugin_credentials.go b/internal/server/plugin_credentials.go new file mode 100644 index 00000000..a4168cb9 --- /dev/null +++ b/internal/server/plugin_credentials.go @@ -0,0 +1,47 @@ +package server + +import ( + "context" + "fmt" + "regexp" + + "github.com/modelsphere/console/internal/pluginregistry" + apierrors "k8s.io/apimachinery/pkg/api/errors" +) + +var proxyBearerToken = regexp.MustCompile(`^[A-Za-z0-9._~+/-]+=*$`) + +func (s *Server) setPluginCredential(ctx context.Context, namespace string, route pluginregistry.Route, target *backendTarget) error { + reference := route.Spec.Directives.AuthProxySecretRef + if reference == nil { + return nil + } + if !route.Spec.Directives.AuthProxy || route.Spec.Directives.SkipAuthentication { + return fmt.Errorf("credential requires an authenticated proxy route") + } + if namespace == "" || (route.Namespace != "" && route.Namespace != namespace) { + return fmt.Errorf("credential route must use the installed release namespace") + } + if s.kube == nil { + return fmt.Errorf("Kubernetes client is unavailable") + } + // Read after IAM on every request so revocation never falls back to a stale key. + secret, err := s.kube.Secret(ctx, namespace, reference.Name) + if err != nil { + // Kubernetes errors may contain response bodies; log only a bounded category. + switch { + case apierrors.IsNotFound(err): + return fmt.Errorf("proxy Secret not found") + case apierrors.IsForbidden(err): + return fmt.Errorf("proxy Secret access forbidden") + default: + return fmt.Errorf("proxy Secret read failed") + } + } + credential := secret[reference.Key] + if !proxyBearerToken.Match(credential) { + return fmt.Errorf("proxy Secret key is missing, empty, or not a valid bearer token") + } + target.header, target.key = "Authorization", "Bearer "+string(credential) + return nil +} diff --git a/internal/server/plugin_credentials_test.go b/internal/server/plugin_credentials_test.go new file mode 100644 index 00000000..86b0b8e5 --- /dev/null +++ b/internal/server/plugin_credentials_test.go @@ -0,0 +1,148 @@ +package server + +import ( + "bytes" + "context" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + + pluginapi "github.com/modelsphere/console/api/plugin/v1alpha1" + "github.com/modelsphere/console/internal/iam" + "github.com/modelsphere/console/internal/pluginregistry" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + dynamicfake "k8s.io/client-go/dynamic/fake" + k8stesting "k8s.io/client-go/testing" +) + +func credentialProxyServer(t *testing.T, upstream http.HandlerFunc) (*Server, http.Handler, string, string, *pluginregistry.Entry) { + t.Helper() + backend := httptest.NewServer(upstream) + t.Cleanup(backend.Close) + target, err := url.Parse(backend.URL) + if err != nil { + t.Fatal(err) + } + entry := registeredEntry(t, target) + entry.Plugin.Spec.Chart = pluginapi.ChartConfig{Namespace: "plugins"} + entry.Routes[0].Spec.Directives.AuthProxySecretRef = &iam.ProxySecretReference{Name: "example-proxy", Key: "proxyKey"} + srv, handler, admin, bob := pluginRegistryServer(t, entry) + return srv, handler, admin, bob, entry +} + +func setProxyCredential(t *testing.T, srv *Server, value string, create bool) { + t.Helper() + if err := srv.kube.WriteSecret(context.Background(), "plugins", "example-proxy", map[string][]byte{"proxyKey": []byte(value)}, create, ""); err != nil { + t.Fatal(err) + } +} + +func TestPluginProxyInjectsCredentialAndObservesRotation(t *testing.T) { + var received http.Header + srv, handler, admin, _, _ := credentialProxyServer(t, func(writer http.ResponseWriter, request *http.Request) { + received = request.Header.Clone() + writer.WriteHeader(http.StatusNoContent) + }) + for index, credential := range []string{"first-key", "rotated-key"} { + setProxyCredential(t, srv, credential, index == 0) + request := httptest.NewRequest("GET", "/api/example/ping", nil) + if index == 0 { + request.AddCookie(&http.Cookie{Name: "token", Value: admin}) + } else { + request.Header.Set("Authorization", "Bearer "+admin) + } + request.Header.Set("X-Remote-User", "forged") + request.Header.Set("X-Remote-Group", "forged") + request.Header.Set("X-Remote-Extra-Scope", "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 "+credential || received.Get("X-Remote-User") != "admin" { + t.Fatal("proxy did not replace caller credential and identity") + } + if received.Get("Cookie") != "" || received.Get("X-Remote-Extra-Scope") != "" || strings.Contains(strings.Join(received.Values("X-Remote-Group"), ","), "forged") { + t.Fatal("client identity or cookies leaked upstream") + } + } + if err := srv.kube.Dynamic().Resource(schema.GroupVersionResource{Version: "v1", Resource: "secrets"}).Namespace("plugins").Delete(context.Background(), "example-proxy", metav1.DeleteOptions{}); err != nil { + t.Fatal(err) + } + received = nil + if response := do(handler, "GET", "/api/example/ping", admin, ""); response.Code != http.StatusBadGateway || received != nil { + t.Fatal("deleted credential did not fail closed") + } +} + +func TestPluginCredentialFailuresNeverReachUpstream(t *testing.T) { + for _, scenario := range []string{"missing", "empty", "missing key", "newline", "spaces", "forbidden", "no client", "wrong namespace", "missing namespace"} { + t.Run(scenario, func(t *testing.T) { + calls := 0 + srv, handler, admin, _, entry := credentialProxyServer(t, func(http.ResponseWriter, *http.Request) { calls++ }) + var logs bytes.Buffer + srv.log = slog.New(slog.NewTextHandler(&logs, nil)) + configureCredentialFailure(t, srv, entry, scenario) + response := do(handler, "GET", "/api/example/ping", admin, "") + if response.Code != http.StatusBadGateway || calls != 0 { + t.Fatalf("status=%d upstream calls=%d", response.Code, calls) + } + for _, output := range []string{response.Body.String(), logs.String()} { + if strings.Contains(output, "sensitive-value") || strings.Contains(output, admin) { + t.Fatal("credentials leaked in error or log") + } + } + }) + } +} + +func configureCredentialFailure(t *testing.T, srv *Server, entry *pluginregistry.Entry, scenario string) { + t.Helper() + switch scenario { + case "missing": + case "empty", "missing key", "newline", "spaces": + values := map[string]string{"empty": "", "missing key": "sensitive-value", "newline": "sensitive-value\r\nInjected: yes", "spaces": "sensitive-value extra"} + setProxyCredential(t, srv, values[scenario], true) + if scenario == "missing key" { + entry.Routes[0].Spec.Directives.AuthProxySecretRef.Key = "absent" + } + case "forbidden": + srv.kube.Dynamic().(*dynamicfake.FakeDynamicClient).PrependReactor("get", "secrets", func(k8stesting.Action) (bool, runtime.Object, error) { + return true, nil, apierrors.NewForbidden(schema.GroupResource{Resource: "secrets"}, "example-proxy", fmt.Errorf("sensitive-value")) + }) + case "no client": + srv.kube = nil + case "wrong namespace": + setProxyCredential(t, srv, "sensitive-value", true) + entry.Routes[0].Namespace = "other" + case "missing namespace": + entry.Plugin.Spec.Chart.Namespace = "" + } +} + +func TestPluginAuthorizationPrecedesSecretRead(t *testing.T) { + srv, handler, _, bob, _ := credentialProxyServer(t, func(http.ResponseWriter, *http.Request) { t.Error("unauthorized upstream request") }) + reads := 0 + srv.kube.Dynamic().(*dynamicfake.FakeDynamicClient).PrependReactor("get", "secrets", func(k8stesting.Action) (bool, runtime.Object, error) { + reads++ + return true, nil, fmt.Errorf("unexpected secret read") + }) + for _, caller := range []struct { + token string + code int + }{{"", http.StatusUnauthorized}, {bob, http.StatusForbidden}} { + if response := do(handler, "GET", "/api/example/ping", caller.token, ""); response.Code != caller.code { + t.Fatalf("authorization: status=%d want=%d", response.Code, caller.code) + } + } + if reads != 0 { + t.Fatalf("unauthorized secret reads=%d", reads) + } +} diff --git a/internal/server/plugin_registry.go b/internal/server/plugin_registry.go index 1731a51b..2c3e480e 100644 --- a/internal/server/plugin_registry.go +++ b/internal/server/plugin_registry.go @@ -48,7 +48,7 @@ func (s *Server) pluginBackends(next http.Handler) http.Handler { if !route.Spec.Directives.SkipAuthentication && !s.allowPluginRequest(w, request, name) { return } - s.servePluginRoute(w, request, name, route) + s.servePluginRoute(w, request, name, entry.Plugin.Spec.Chart.Namespace, route) return } } @@ -57,7 +57,7 @@ func (s *Server) pluginBackends(next http.Handler) http.Handler { }) } -func (s *Server) servePluginRoute(w http.ResponseWriter, r *http.Request, name string, route pluginregistry.Route) { +func (s *Server) servePluginRoute(w http.ResponseWriter, r *http.Request, name, namespace string, route pluginregistry.Route) { upstream := route.Spec.Upstream backend := config.Backend{Name: name, Prefix: route.Spec.Directives.StripPathPrefix, URL: fmt.Sprintf("%s://%s:%d", upstream.Scheme, upstream.Host, upstream.Port)} if backend.Prefix == "" { @@ -75,6 +75,11 @@ func (s *Server) servePluginRoute(w http.ResponseWriter, r *http.Request, name s writeError(w, http.StatusBadGateway, "plugin upstream unavailable") return } + if err := s.setPluginCredential(r.Context(), namespace, route, target); err != nil { + s.log.Warn("plugin proxy credential unavailable", "plugin", name, "error", err) + writeError(w, http.StatusBadGateway, "plugin proxy credential unavailable") + return + } proxy := s.backendProxy(backend) if route.Spec.Directives.SkipAuthentication { rewrite := proxy.Rewrite From 691b29b05aa29042ab1c51c8666bb79e92556a93 Mon Sep 17 00:00:00 2001 From: imneov Date: Tue, 24 Nov 2026 14:54:49 +0800 Subject: [PATCH 2/3] fix(web): supply plugin policy data to resource actions Share plugin-local data queries with action callbacks and preserve independent SLO edit policy instead of inheriting the uninstall lock. Keep open SLO drafts mounted during policy refresh while writes remain disabled. Add isolation, changed-resource, stale-error and rendered-action regression tests. --- docs/development/plugin-architecture.md | 20 +++++++ web/src/extensions/data.ts | 5 ++ web/src/extensions/queries.test.tsx | 45 ++++++++++++++++ web/src/extensions/queries.ts | 43 +++++++++++++++ web/src/extensions/registry.test.ts | 27 ++++++++++ web/src/extensions/registry.ts | 7 ++- web/src/extensions/surface.tsx | 13 ++--- .../modules/inferences/InferenceDetail.tsx | 18 ++++--- web/src/modules/inferences/InferenceList.tsx | 5 +- .../modules/inferences/uninstalling.test.tsx | 54 +++++++++++++++++-- 10 files changed, 211 insertions(+), 26 deletions(-) create mode 100644 web/src/extensions/queries.test.tsx create mode 100644 web/src/extensions/queries.ts create mode 100644 web/src/extensions/registry.test.ts diff --git a/docs/development/plugin-architecture.md b/docs/development/plugin-architecture.md index afe90600..70e6819a 100644 --- a/docs/development/plugin-architecture.md +++ b/docs/development/plugin-architecture.md @@ -348,6 +348,26 @@ 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/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 }), From 9c659a3878e44ccae1c181c02bde93a256ffa7a7 Mon Sep 17 00:00:00 2001 From: imneov Date: Tue, 24 Nov 2026 19:35:25 +0800 Subject: [PATCH 3/3] refactor(server): defer plugin proxy Secret extension Keep the existing authProxy session and identity contract. Remove the unshared Secret-reference schema, lookup and validation while retaining the proposal as deferred. Add regressions for existing routes and session forwarding without Secret reads. Refs #148 --- docs/console-design.md | 15 -- docs/development/plugin-architecture.md | 43 +---- docs/development/plugin-proxy-credentials.md | 7 + docs/development/plugins.md | 9 -- .../iam.theriseunion.io_reverseproxies.yaml | 23 --- internal/iam/reverseproxy_schema_test.go | 16 +- internal/iam/reverseproxy_types.go | 17 -- internal/pluginregistry/credentials_test.go | 50 ------ internal/pluginregistry/release.go | 5 - internal/pluginregistry/routes.go | 9 -- .../pluginregistry/routes_contract_test.go | 19 +++ internal/server/plugin_credentials.go | 47 ------ internal/server/plugin_credentials_test.go | 148 ------------------ internal/server/plugin_registry.go | 9 +- internal/server/plugin_session_test.go | 48 ++++++ 15 files changed, 90 insertions(+), 375 deletions(-) delete mode 100644 internal/pluginregistry/credentials_test.go create mode 100644 internal/pluginregistry/routes_contract_test.go delete mode 100644 internal/server/plugin_credentials.go delete mode 100644 internal/server/plugin_credentials_test.go create mode 100644 internal/server/plugin_session_test.go diff --git a/docs/console-design.md b/docs/console-design.md index d5f10e40..b31cd86e 100644 --- a/docs/console-design.md +++ b/docs/console-design.md @@ -779,21 +779,6 @@ in [#145](https://github.com/modelsphere/console/issues/145) and the | Navigation | Build the active composition directly from the shared registry; retain route guards and all three appearance layouts | | Dashboard status | Original Charts install and original resource lists/details work through current-cluster context, business-entry composition and existing-authorized backend proxies | -## Plugin proxy credentials - -The shared-credential contract is recorded in [design #148](https://github.com/modelsphere/console/issues/148) -and [the implementation design](development/plugin-proxy-credentials.md). - -| Owner | Responsibility | -| --- | --- | -| Console | Authenticate users, enforce backend IAM, read the release-scoped Secret and inject the shared credential | -| Plugin chart | Declare `authProxySecretRef` and configure the backend with the same Secret/key | -| Backend team | Validate the credential and user identity; frontend integration must not disable those checks | -| Frontend | Use the same-origin SDK without handling backend credentials | - -Existing routes remain compatible. Secret lookup fails closed and runs per -authorized request so rotation and revocation do not depend on a cached key. - ## Known debt - **The token preset is Tailwind 3-style**, loaded through `@config`. A Tailwind 4 diff --git a/docs/development/plugin-architecture.md b/docs/development/plugin-architecture.md index 70e6819a..e7a1b5e8 100644 --- a/docs/development/plugin-architecture.md +++ b/docs/development/plugin-architecture.md @@ -307,41 +307,14 @@ 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. -Plugins that validate a shared proxy credential declare a Secret reference: - -```yaml -spec: - directives: - authProxy: true - authProxySecretRef: - name: example-proxy - key: proxyKey -``` - -| Boundary | Contract | -| --- | --- | -| Frontend | Uses the SDK and the user's session; never holds the proxy key | -| Console | Authenticates and authorizes first, then reads the release-namespace Secret and overwrites `Authorization: Bearer ` | -| Backend | Validates the shared credential and requires Console's `X-Remote-User`; backend owners implement this contract | -| Installation | Configures the same Secret/key for Console's route and the backend; no inline credentials or automatic permission grants | - -- The reference is optional for existing routes, but requires `authProxy: true` - and forbids `skipAuthentication`. No namespace override is supported. -- Secret data is a raw RFC 6750 bearer token (no `Bearer ` prefix or whitespace). -- Missing/unreadable Secrets, missing/empty/invalid keys and unavailable clients - return 502 without contacting the upstream or falling back to a user token. -- Secrets are read on every authorized request. Rotation/deletion takes effect - on the next request; backend environment variables still require its rollout. -- The release namespace is the lookup boundary. An explicitly different route - namespace is rejected. Existing Secret read RBAC is reused, not expanded. -- Only trusted operators may install packages: their charts choose upstream - destinations and Secret references. NetworkPolicy remains defense in depth. -- Upgrade Console and its ReverseProxy CRD before installing consumers. Helm - does not update CRDs on upgrade. This optional field is a Console extension; - other Global-compatible hosts must implement it before using these packages. - -Regenerate the schema with `bash hack/generate-proxy-crd.sh`. See -[the credential design](plugin-proxy-credentials.md) for rollout and alternatives. +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)` diff --git a/docs/development/plugin-proxy-credentials.md b/docs/development/plugin-proxy-credentials.md index ddd2fa2b..bf4f1979 100644 --- a/docs/development/plugin-proxy-credentials.md +++ b/docs/development/plugin-proxy-credentials.md @@ -1,3 +1,10 @@ +## 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. diff --git a/docs/development/plugins.md b/docs/development/plugins.md index 60cfd74b..606114fd 100644 --- a/docs/development/plugins.md +++ b/docs/development/plugins.md @@ -307,15 +307,6 @@ Registration requires every `ReverseProxy` in the release to satisfy: - `directives.authProxy: true`; - `upstream.scheme` is `http` or `https`, `host` is non-empty, `port` is 1–65535. -If the backend requires a shared proxy key, add -`directives.authProxySecretRef: {name: my-plugin-proxy, key: proxyKey}` and -configure the backend with the same release-namespace Secret. Console reads it -after IAM authorization and overwrites the upstream Bearer credential; the -frontend never receives it. Missing or invalid credentials fail closed with 502. -This requires a host and ReverseProxy CRD implementing the -[shared-credential contract](plugin-architecture.md#backend-contract); upgrading a -Helm release alone does not upgrade its CRDs. - Add an IAM role pair so users can reach the backend. Console authorizes each request on resource `backends` with resource name equal to the plugin name: diff --git a/helm/console/crds/iam.theriseunion.io_reverseproxies.yaml b/helm/console/crds/iam.theriseunion.io_reverseproxies.yaml index 547f8a74..73e78b69 100644 --- a/helm/console/crds/iam.theriseunion.io_reverseproxies.yaml +++ b/helm/console/crds/iam.theriseunion.io_reverseproxies.yaml @@ -61,25 +61,6 @@ spec: authProxy: description: Enable authentication proxy type: boolean - authProxySecretRef: - description: Shared proxy credential in the installed plugin release - namespace. Requires authProxy. - properties: - key: - description: Key containing the raw bearer token, without - the Bearer prefix. - maxLength: 253 - minLength: 1 - type: string - name: - description: Secret name in the installed plugin release namespace. - maxLength: 253 - minLength: 1 - type: string - required: - - key - - name - type: object headerDown: description: Response header modifications items: @@ -142,10 +123,6 @@ spec: description: Wrap transport for additional processing type: boolean type: object - x-kubernetes-validations: - - message: authProxySecretRef requires authProxy without skipAuthentication - rule: '!has(self.authProxySecretRef) || (has(self.authProxy) && - self.authProxy && (!has(self.skipAuthentication) || !self.skipAuthentication))' matcher: description: Request matching rules properties: diff --git a/internal/iam/reverseproxy_schema_test.go b/internal/iam/reverseproxy_schema_test.go index 8f552a7f..26689940 100644 --- a/internal/iam/reverseproxy_schema_test.go +++ b/internal/iam/reverseproxy_schema_test.go @@ -8,7 +8,7 @@ import ( "sigs.k8s.io/yaml" ) -func TestReverseProxySchemaPreservesSecretReference(t *testing.T) { +func TestReverseProxySchemaUsesExistingAuthProxyContract(t *testing.T) { data, err := os.ReadFile("../../helm/console/crds/iam.theriseunion.io_reverseproxies.yaml") if err != nil { t.Fatal(err) @@ -25,15 +25,11 @@ func TestReverseProxySchemaPreservesSecretReference(t *testing.T) { if err != nil || !found { t.Fatalf("schema directives: found=%t err=%v", found, err) } - required, found, err := unstructured.NestedStringSlice(directives, "properties", "authProxySecretRef", "required") - if err != nil || !found || len(required) != 2 || required[0] != "key" || required[1] != "name" { - t.Fatalf("Secret reference required fields=%v err=%v", required, err) + if _, found, err := unstructured.NestedFieldNoCopy(directives, "properties", "authProxySecretRef"); err != nil || found { + t.Fatalf("unsupported Secret reference: found=%t err=%v", found, err) } - validations, found, err := unstructured.NestedSlice(directives, "x-kubernetes-validations") - if err != nil || !found || len(validations) != 1 { - t.Fatalf("credential authentication validation: found=%t err=%v", found, err) - } - if validations[0].(map[string]any)["rule"] != "!has(self.authProxySecretRef) || (has(self.authProxy) && self.authProxy && (!has(self.skipAuthentication) || !self.skipAuthentication))" { - t.Fatal("Secret references must require authentication and reject public routes") + 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/iam/reverseproxy_types.go b/internal/iam/reverseproxy_types.go index b3c4e917..b8b05093 100644 --- a/internal/iam/reverseproxy_types.go +++ b/internal/iam/reverseproxy_types.go @@ -58,16 +58,11 @@ func (u *ReverseProxyUpstream) RawURL() string { } // ReverseProxyDirectives defines proxy behavior and transformation rules -// +kubebuilder:validation:XValidation:rule="!has(self.authProxySecretRef) || (has(self.authProxy) && self.authProxy && (!has(self.skipAuthentication) || !self.skipAuthentication))",message="authProxySecretRef requires authProxy without skipAuthentication" type ReverseProxyDirectives struct { // Enable authentication proxy // +optional AuthProxy bool `json:"authProxy,omitempty"` - // Shared proxy credential in the installed plugin release namespace. Requires authProxy. - // +optional - AuthProxySecretRef *ProxySecretReference `json:"authProxySecretRef,omitempty"` - // Skip host authentication and authorization for matching requests; upstream must authenticate. // Mutually exclusive with authProxy. // +optional @@ -106,18 +101,6 @@ type ReverseProxyDirectives struct { Replace []ReverseProxyReplaceRule `json:"replace,omitempty"` } -// ProxySecretReference selects a required bearer credential without exposing its value. -type ProxySecretReference struct { - // Secret name in the installed plugin release namespace. - // +kubebuilder:validation:MinLength=1 - // +kubebuilder:validation:MaxLength=253 - Name string `json:"name"` - // Key containing the raw bearer token, without the Bearer prefix. - // +kubebuilder:validation:MinLength=1 - // +kubebuilder:validation:MaxLength=253 - Key string `json:"key"` -} - // ReverseProxyRewriteRule defines path rewriting rules type ReverseProxyRewriteRule struct { // Source pattern (regex) diff --git a/internal/pluginregistry/credentials_test.go b/internal/pluginregistry/credentials_test.go deleted file mode 100644 index 075c911b..00000000 --- a/internal/pluginregistry/credentials_test.go +++ /dev/null @@ -1,50 +0,0 @@ -package pluginregistry - -import ( - "context" - "strings" - "testing" - - pluginapi "github.com/modelsphere/console/api/plugin/v1alpha1" - "helm.sh/helm/v3/pkg/release" -) - -func TestReadRoutesValidatesProxySecretReference(t *testing.T) { - manifest := reverseProxyManifest("/api/example/*") + " authProxySecretRef:\n name: example-proxy\n key: proxyKey\n" - meta := &pluginapi.PluginMeta{Group: "rise.io", APIVersion: "v1", Name: "example"} - routes, err := readRoutes(manifest, meta) - if err != nil || len(routes) != 1 { - t.Fatalf("valid reference: routes=%v err=%v", routes, err) - } - for _, invalid := range []string{ - strings.Replace(manifest, "name: example-proxy", "name: ''", 1), - strings.Replace(manifest, "name: example-proxy", "name: ../other", 1), - strings.Replace(manifest, "key: proxyKey", "key: ''", 1), - strings.Replace(manifest, "key: proxyKey", "key: bad/key", 1), - strings.Replace(manifest, "key: proxyKey", "key: proxyKey\n namespace: other", 1), - strings.Replace(manifest, "authProxy: true", "authProxy: false", 1), - strings.Replace(strings.Replace(manifest, "authProxy: true", "skipAuthentication: true", 1), "path: /api/example/*", "method: GET\n path: /oapis/rise.io/v1/example/*", 1), - } { - if _, err := readRoutes(invalid, meta); err == nil { - t.Fatalf("accepted invalid credential reference: %s", invalid) - } - } -} - -func TestCredentialRouteNamespaceMatchesRelease(t *testing.T) { - for _, namespace := range []string{"", "console-system", "other"} { - t.Run(namespace, func(t *testing.T) { - registry, _, plugin := registryFixture(t) - installed := installedRelease() - installed.Manifest = reverseProxyManifest("/api/example/*") + " authProxySecretRef:\n name: example-proxy\n key: proxyKey\n" - if namespace != "" { - installed.Manifest = strings.Replace(installed.Manifest, " name: example\n", " name: example\n namespace: "+namespace+"\n", 1) - } - registry.read = func(context.Context, string, string) (*release.Release, error) { return installed, nil } - _, err := registry.load(t.Context(), plugin) - if (err != nil) != (namespace == "other") { - t.Fatalf("namespace %q: %v", namespace, err) - } - }) - } -} diff --git a/internal/pluginregistry/release.go b/internal/pluginregistry/release.go index db01688e..f5abbbad 100644 --- a/internal/pluginregistry/release.go +++ b/internal/pluginregistry/release.go @@ -95,11 +95,6 @@ func (r *Registry) load(ctx context.Context, plugin *pluginapi.Plugin) (*Entry, if err != nil { return nil, err } - for _, route := range entry.Routes { - if route.Spec.Directives.AuthProxySecretRef != nil && route.Namespace != "" && route.Namespace != plugin.Spec.Chart.Namespace { - return nil, fmt.Errorf("plugin proxy credential route must be in the installed release namespace") - } - } entry.Plugin.Status = pluginapi.PluginStatus{Phase: pluginapi.PluginPhaseInstalled, ObservedGeneration: plugin.Generation, ReleaseName: installed.Name, ReleaseVersion: installed.Version, PluginMeta: meta, FrontendStatus: &pluginapi.FrontendStatus{Distributed: true, EntryURL: "/plugins/" + plugin.Name + "/" + meta.Frontend.Entry}} return entry, nil } diff --git a/internal/pluginregistry/routes.go b/internal/pluginregistry/routes.go index ed887d3c..21b2d1a4 100644 --- a/internal/pluginregistry/routes.go +++ b/internal/pluginregistry/routes.go @@ -10,7 +10,6 @@ import ( pluginapi "github.com/modelsphere/console/api/plugin/v1alpha1" "github.com/modelsphere/console/internal/config" "github.com/modelsphere/console/internal/iam" - "k8s.io/apimachinery/pkg/util/validation" "k8s.io/apimachinery/pkg/util/yaml" sigyaml "sigs.k8s.io/yaml" ) @@ -52,14 +51,6 @@ func validateRoute(route Route, meta *pluginapi.PluginMeta) error { return fmt.Errorf("plugin ReverseProxy prefix %q is reserved by console", prefix) } directives := route.Spec.Directives - if reference := directives.AuthProxySecretRef; reference != nil { - if !directives.AuthProxy || directives.SkipAuthentication { - return fmt.Errorf("plugin proxy credential requires authProxy without skipAuthentication") - } - if len(validation.IsDNS1123Subdomain(reference.Name)) != 0 || reference.Key == "" || len(validation.IsConfigMapKey(reference.Key)) != 0 { - return fmt.Errorf("plugin proxy credential requires a valid Secret name and key") - } - } if directives.SkipAuthentication { owned := "/oapis/" + meta.Group + "/" + meta.APIVersion + "/" + meta.Name if prefix != owned || route.Spec.Matcher.Method != "GET" || directives.AuthProxy { 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_credentials.go b/internal/server/plugin_credentials.go deleted file mode 100644 index a4168cb9..00000000 --- a/internal/server/plugin_credentials.go +++ /dev/null @@ -1,47 +0,0 @@ -package server - -import ( - "context" - "fmt" - "regexp" - - "github.com/modelsphere/console/internal/pluginregistry" - apierrors "k8s.io/apimachinery/pkg/api/errors" -) - -var proxyBearerToken = regexp.MustCompile(`^[A-Za-z0-9._~+/-]+=*$`) - -func (s *Server) setPluginCredential(ctx context.Context, namespace string, route pluginregistry.Route, target *backendTarget) error { - reference := route.Spec.Directives.AuthProxySecretRef - if reference == nil { - return nil - } - if !route.Spec.Directives.AuthProxy || route.Spec.Directives.SkipAuthentication { - return fmt.Errorf("credential requires an authenticated proxy route") - } - if namespace == "" || (route.Namespace != "" && route.Namespace != namespace) { - return fmt.Errorf("credential route must use the installed release namespace") - } - if s.kube == nil { - return fmt.Errorf("Kubernetes client is unavailable") - } - // Read after IAM on every request so revocation never falls back to a stale key. - secret, err := s.kube.Secret(ctx, namespace, reference.Name) - if err != nil { - // Kubernetes errors may contain response bodies; log only a bounded category. - switch { - case apierrors.IsNotFound(err): - return fmt.Errorf("proxy Secret not found") - case apierrors.IsForbidden(err): - return fmt.Errorf("proxy Secret access forbidden") - default: - return fmt.Errorf("proxy Secret read failed") - } - } - credential := secret[reference.Key] - if !proxyBearerToken.Match(credential) { - return fmt.Errorf("proxy Secret key is missing, empty, or not a valid bearer token") - } - target.header, target.key = "Authorization", "Bearer "+string(credential) - return nil -} diff --git a/internal/server/plugin_credentials_test.go b/internal/server/plugin_credentials_test.go deleted file mode 100644 index 86b0b8e5..00000000 --- a/internal/server/plugin_credentials_test.go +++ /dev/null @@ -1,148 +0,0 @@ -package server - -import ( - "bytes" - "context" - "fmt" - "log/slog" - "net/http" - "net/http/httptest" - "net/url" - "strings" - "testing" - - pluginapi "github.com/modelsphere/console/api/plugin/v1alpha1" - "github.com/modelsphere/console/internal/iam" - "github.com/modelsphere/console/internal/pluginregistry" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - dynamicfake "k8s.io/client-go/dynamic/fake" - k8stesting "k8s.io/client-go/testing" -) - -func credentialProxyServer(t *testing.T, upstream http.HandlerFunc) (*Server, http.Handler, string, string, *pluginregistry.Entry) { - t.Helper() - backend := httptest.NewServer(upstream) - t.Cleanup(backend.Close) - target, err := url.Parse(backend.URL) - if err != nil { - t.Fatal(err) - } - entry := registeredEntry(t, target) - entry.Plugin.Spec.Chart = pluginapi.ChartConfig{Namespace: "plugins"} - entry.Routes[0].Spec.Directives.AuthProxySecretRef = &iam.ProxySecretReference{Name: "example-proxy", Key: "proxyKey"} - srv, handler, admin, bob := pluginRegistryServer(t, entry) - return srv, handler, admin, bob, entry -} - -func setProxyCredential(t *testing.T, srv *Server, value string, create bool) { - t.Helper() - if err := srv.kube.WriteSecret(context.Background(), "plugins", "example-proxy", map[string][]byte{"proxyKey": []byte(value)}, create, ""); err != nil { - t.Fatal(err) - } -} - -func TestPluginProxyInjectsCredentialAndObservesRotation(t *testing.T) { - var received http.Header - srv, handler, admin, _, _ := credentialProxyServer(t, func(writer http.ResponseWriter, request *http.Request) { - received = request.Header.Clone() - writer.WriteHeader(http.StatusNoContent) - }) - for index, credential := range []string{"first-key", "rotated-key"} { - setProxyCredential(t, srv, credential, index == 0) - request := httptest.NewRequest("GET", "/api/example/ping", nil) - if index == 0 { - request.AddCookie(&http.Cookie{Name: "token", Value: admin}) - } else { - request.Header.Set("Authorization", "Bearer "+admin) - } - request.Header.Set("X-Remote-User", "forged") - request.Header.Set("X-Remote-Group", "forged") - request.Header.Set("X-Remote-Extra-Scope", "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 "+credential || received.Get("X-Remote-User") != "admin" { - t.Fatal("proxy did not replace caller credential and identity") - } - if received.Get("Cookie") != "" || received.Get("X-Remote-Extra-Scope") != "" || strings.Contains(strings.Join(received.Values("X-Remote-Group"), ","), "forged") { - t.Fatal("client identity or cookies leaked upstream") - } - } - if err := srv.kube.Dynamic().Resource(schema.GroupVersionResource{Version: "v1", Resource: "secrets"}).Namespace("plugins").Delete(context.Background(), "example-proxy", metav1.DeleteOptions{}); err != nil { - t.Fatal(err) - } - received = nil - if response := do(handler, "GET", "/api/example/ping", admin, ""); response.Code != http.StatusBadGateway || received != nil { - t.Fatal("deleted credential did not fail closed") - } -} - -func TestPluginCredentialFailuresNeverReachUpstream(t *testing.T) { - for _, scenario := range []string{"missing", "empty", "missing key", "newline", "spaces", "forbidden", "no client", "wrong namespace", "missing namespace"} { - t.Run(scenario, func(t *testing.T) { - calls := 0 - srv, handler, admin, _, entry := credentialProxyServer(t, func(http.ResponseWriter, *http.Request) { calls++ }) - var logs bytes.Buffer - srv.log = slog.New(slog.NewTextHandler(&logs, nil)) - configureCredentialFailure(t, srv, entry, scenario) - response := do(handler, "GET", "/api/example/ping", admin, "") - if response.Code != http.StatusBadGateway || calls != 0 { - t.Fatalf("status=%d upstream calls=%d", response.Code, calls) - } - for _, output := range []string{response.Body.String(), logs.String()} { - if strings.Contains(output, "sensitive-value") || strings.Contains(output, admin) { - t.Fatal("credentials leaked in error or log") - } - } - }) - } -} - -func configureCredentialFailure(t *testing.T, srv *Server, entry *pluginregistry.Entry, scenario string) { - t.Helper() - switch scenario { - case "missing": - case "empty", "missing key", "newline", "spaces": - values := map[string]string{"empty": "", "missing key": "sensitive-value", "newline": "sensitive-value\r\nInjected: yes", "spaces": "sensitive-value extra"} - setProxyCredential(t, srv, values[scenario], true) - if scenario == "missing key" { - entry.Routes[0].Spec.Directives.AuthProxySecretRef.Key = "absent" - } - case "forbidden": - srv.kube.Dynamic().(*dynamicfake.FakeDynamicClient).PrependReactor("get", "secrets", func(k8stesting.Action) (bool, runtime.Object, error) { - return true, nil, apierrors.NewForbidden(schema.GroupResource{Resource: "secrets"}, "example-proxy", fmt.Errorf("sensitive-value")) - }) - case "no client": - srv.kube = nil - case "wrong namespace": - setProxyCredential(t, srv, "sensitive-value", true) - entry.Routes[0].Namespace = "other" - case "missing namespace": - entry.Plugin.Spec.Chart.Namespace = "" - } -} - -func TestPluginAuthorizationPrecedesSecretRead(t *testing.T) { - srv, handler, _, bob, _ := credentialProxyServer(t, func(http.ResponseWriter, *http.Request) { t.Error("unauthorized upstream request") }) - reads := 0 - srv.kube.Dynamic().(*dynamicfake.FakeDynamicClient).PrependReactor("get", "secrets", func(k8stesting.Action) (bool, runtime.Object, error) { - reads++ - return true, nil, fmt.Errorf("unexpected secret read") - }) - for _, caller := range []struct { - token string - code int - }{{"", http.StatusUnauthorized}, {bob, http.StatusForbidden}} { - if response := do(handler, "GET", "/api/example/ping", caller.token, ""); response.Code != caller.code { - t.Fatalf("authorization: status=%d want=%d", response.Code, caller.code) - } - } - if reads != 0 { - t.Fatalf("unauthorized secret reads=%d", reads) - } -} diff --git a/internal/server/plugin_registry.go b/internal/server/plugin_registry.go index 2c3e480e..1731a51b 100644 --- a/internal/server/plugin_registry.go +++ b/internal/server/plugin_registry.go @@ -48,7 +48,7 @@ func (s *Server) pluginBackends(next http.Handler) http.Handler { if !route.Spec.Directives.SkipAuthentication && !s.allowPluginRequest(w, request, name) { return } - s.servePluginRoute(w, request, name, entry.Plugin.Spec.Chart.Namespace, route) + s.servePluginRoute(w, request, name, route) return } } @@ -57,7 +57,7 @@ func (s *Server) pluginBackends(next http.Handler) http.Handler { }) } -func (s *Server) servePluginRoute(w http.ResponseWriter, r *http.Request, name, namespace string, route pluginregistry.Route) { +func (s *Server) servePluginRoute(w http.ResponseWriter, r *http.Request, name string, route pluginregistry.Route) { upstream := route.Spec.Upstream backend := config.Backend{Name: name, Prefix: route.Spec.Directives.StripPathPrefix, URL: fmt.Sprintf("%s://%s:%d", upstream.Scheme, upstream.Host, upstream.Port)} if backend.Prefix == "" { @@ -75,11 +75,6 @@ func (s *Server) servePluginRoute(w http.ResponseWriter, r *http.Request, name, writeError(w, http.StatusBadGateway, "plugin upstream unavailable") return } - if err := s.setPluginCredential(r.Context(), namespace, route, target); err != nil { - s.log.Warn("plugin proxy credential unavailable", "plugin", name, "error", err) - writeError(w, http.StatusBadGateway, "plugin proxy credential unavailable") - return - } proxy := s.backendProxy(backend) if route.Spec.Directives.SkipAuthentication { rewrite := proxy.Rewrite 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") + } + } +}