Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions docs/development/plugin-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
76 changes: 76 additions & 0 deletions docs/development/plugin-proxy-credentials.md
Original file line number Diff line number Diff line change
@@ -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 <secret value>`. 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.
10 changes: 10 additions & 0 deletions hack/generate-proxy-crd.sh
Original file line number Diff line number Diff line change
@@ -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/
3 changes: 3 additions & 0 deletions internal/iam/doc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// +groupName=iam.theriseunion.io
// +versionName=v1alpha1
package iam
35 changes: 35 additions & 0 deletions internal/iam/reverseproxy_schema_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
19 changes: 19 additions & 0 deletions internal/pluginregistry/routes_contract_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
}
48 changes: 48 additions & 0 deletions internal/server/plugin_session_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
}
}
5 changes: 5 additions & 0 deletions web/src/extensions/data.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import type { ResourceDataExtension } from "./types";

export interface LoadedResourceData {
extensions: readonly Pick<ResourceDataExtension, "plugin" | "id">[];
values: readonly unknown[];
}

/**
* Plugin-local data map for one extension callback.
*
Expand Down
45 changes: 45 additions & 0 deletions web/src/extensions/queries.test.tsx
Original file line number Diff line number Diff line change
@@ -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 <span>{evaluate("ns/name", resource, "slo") || "editable"}</span>;
}

function renderPolicy(client: QueryClient, resource: unknown = original) {
return renderToStaticMarkup(<QueryClientProvider client={client}><Policy resource={resource} /></QueryClientProvider>);
}

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();
});
});
43 changes: 43 additions & 0 deletions web/src/extensions/queries.ts
Original file line number Diff line number Diff line change
@@ -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<ResourceDataExtension, "plugin" | "id">, 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<string, LoadedResourceData> {
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));
}
27 changes: 27 additions & 0 deletions web/src/extensions/registry.test.ts
Original file line number Diff line number Diff line change
@@ -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");
});
});
7 changes: 5 additions & 2 deletions web/src/extensions/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type {
ResourcePresentationExtension,
ResourceVisibilityExtension,
} from "./types";
import { dataForPlugin, type LoadedResourceData } from "./data";

export const extensions: ConsoleExtensions = {
modules: [],
Expand Down Expand Up @@ -43,12 +44,14 @@ export function evaluateResourceAction<T>(
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);
Expand Down
Loading
Loading