Skip to content
Merged
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
110 changes: 109 additions & 1 deletion docs/development/plugins.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,8 @@ Providers own functionality; compositions own navigation. Installing a plugin do
| `menus` | Legacy default placement inside Console, including `parent/group/order/children` |
| `entries` | Reusable business pages registered by stable provider/name identity; no automatic menu placement |
| provider `scopes` | Context/title/icon metadata; not an application declaration |
| `registerNavigationComposition` | Ordered groups of provider/entry references; supplies a named application's navigation |
| `createPlugin({ navigationComposition })` | Named application owned by the same plugin as its business pages |
| `registerNavigationComposition` | A separate navigation-only plugin with ordered groups of provider/entry references |
| host composition | `web/src/shell/console-navigation.ts`; the same group/reference model orders Console's built-in and plugin entries |

```tsx
Expand All @@ -199,6 +200,15 @@ groups: [{
}],
```

A plugin that includes both Console pages and an application can place its
Console pages in `menus` and its application pages in `entries`. Declare the
application scopes and groups in `navigationComposition`, and reference the
entries by their provider and name. An application is identified as
`<plugin-name>/<scope>`. Set `launcher: false` inside the composition to keep
the application available through an account menu link or its routes while
hiding its launcher card. Shared route namespaces use the ordinary menus for
their default landing page.

- Change group/reference array order to reorder menus without changing plugin bundles or module load order.
- Unreferenced legacy menus keep their default Console placement. North Star/Canary therefore integrates into Console, not a separate application.
- References never override page components, permissions, backend checks or translation ownership. Missing providers and denied/hidden ancestors produce no menu.
Expand All @@ -214,6 +224,34 @@ Authenticated `/clusters/{value}/oapis/` aliases do not select another cluster.
not authorization aggregation. See the [single-cluster design](single-cluster-applications-design.md)
for the unchanged original Dashboard Charts and browser verification.

### Account menu links

Set `userMenu` on `createPlugin()` to add links to the account dropdown. Use
an entry name from your plugin or an application ID from a registered
navigation composition.

```ts
userMenu: [
{ id: "overview", title: "My Plugin", target: { kind: "entry", name: "my-plugin" } },
{ id: "settings", title: "Settings", target: { kind: "application", id: "my-settings/platform" } },
],
```

- Each `id` is unique within the plugin and uses kebab-case. Translate the
label at `userMenu.<id>` in the plugin's namespace. The declared `title`
serves as the fallback.
- Set `order` to place the link among other plugin links. It defaults to
`999`, with ties sorted by plugin ID and link ID.
- An entry target resolves to a static page owned by this plugin. Console
checks the same visibility and permission rules it uses for navigation.
- An application target opens its default page if the user can access it
and the first accessible landing page otherwise. Console hides the link
if the application has no accessible landing page.

Console resolves these links from the currently available plugins and pages.
Page guards and backend authorization still apply. An older Console with the
same SDK major version ignores account menu declarations.

### Routes

Menu paths and route keys are normalized before matching; a matching route
Expand All @@ -230,6 +268,52 @@ Hidden or denied ancestors hide their navigation subtree, while child routes
remain registered with their own guards. Detail routes inherit their nearest
menu's `authKey`; backend authorization remains independent.

### Model details tabs

Register a presentation with `resourceType: "catalog-model"` and
`placement: "resource.tabs"` to add a tab to the model details page.
Register the tab's component in the same plugin.

```tsx
components: { ModelHistory },
presentationExtensions: [{
id: "model-history",
key: "history",
resourceType: "catalog-model",
placement: "resource.tabs",
component: "ModelHistory",
authKey: "my-plugin.history.view",
tab: { title: "History", order: 20 },
}],
```

The component receives `resourceType`, `resourceKey`, `resource`, and `data`.
The SDK's `CatalogModelResource` describes `resource`, including the selected
catalog, model, variant references, and the resolved serving name and weights
path when available. The tab key is unique within the plugin for this surface.
Ordering defaults to `999`. If the plugin registers a backend, the tab also
requires read access to that backend.

### Model catalog actions

Register a presentation for the action's location. Its component can render a
button or a link using the catalog and model it receives.

| Location | `resourceType` | `placement` | SDK resource type |
| --- | --- | --- | --- |
| Model library card footer | `catalog-model` | `collection.card.actions` | `CatalogModelResource` |
| Model details toolbar | `catalog-model` | `resource.header.actions` | `CatalogModelResource` |
| Recipe card footer on model details | `catalog-variant` | `collection.card.actions` | `CatalogVariantResource` |

The model library card receives the catalog's model summary. Detail actions
also receive the resolved weights path and serving name when available. Recipe
actions receive the selected variant's ID, version, and digest. Use those
fields together when resolving a recipe in the plugin.

The host checks the contribution's optional `authKey` and read access to the
registered plugin backend. The destination and its backend still enforce their
own permissions.

### Data and permissions

```tsx
Expand Down Expand Up @@ -354,6 +438,30 @@ spec:
A frontend-only plugin needs no `ReverseProxy` and no IAM role. It appears in
the sidebar for every authenticated user who can load Console.

### Authorization for configured backends

For integrations listed under `backends` in the Console server configuration,
`accessRules` can assign a separate `backends` resource name and verb to an
endpoint. For example, approve reports with a dedicated role that grants
`update` on `report-approvals`.

```yaml
backends:
- name: reports
prefix: /api/reports
url: https://reports.example.com
accessRules:
- pathPrefix: /approvals
methods: [POST]
resourceName: report-approvals
verb: update
```

Console matches the longest backend-relative path prefix on a path segment
boundary for the incoming method. An unmatched request uses the backend's name
and the standard method-to-verb mapping. Use a `/` rule with a separate resource
name when access to unmatched endpoints must have its own grant.

## 7. Capabilities

`provides` publishes values other packages can consume; `consumes` declares
Expand Down
54 changes: 53 additions & 1 deletion internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,12 @@ import (
"fmt"
"net/url"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"time"
"unicode"

"gopkg.in/yaml.v3"
)
Expand Down Expand Up @@ -114,7 +116,16 @@ type Backend struct {
// namespace can still take a copied key through a Secret volume.
APIKeyEnv string `yaml:"apiKeyEnv,omitempty"`
// WritePermission is an optional permission required in addition to backend update access.
WritePermission string `yaml:"writePermission,omitempty"`
WritePermission string `yaml:"writePermission,omitempty"`
AccessRules []BackendAccessRule `yaml:"accessRules,omitempty"`
}

// BackendAccessRule overrides authorization for a backend-relative path and HTTP methods.
type BackendAccessRule struct {
PathPrefix string `yaml:"pathPrefix"`
Methods []string `yaml:"methods"`
ResourceName string `yaml:"resourceName"`
Verb string `yaml:"verb"`
}

// Gateway is an inference entrypoint resolved from the cluster at startup and
Expand Down Expand Up @@ -311,9 +322,50 @@ func validateBackend(b Backend) error {
if b.APIKeyEnv != "" && !envNameRE.MatchString(b.APIKeyEnv) {
return fmt.Errorf("apiKeyEnv %q is not an environment variable name", b.APIKeyEnv)
}
if err := validateBackendAccessRules(b.AccessRules); err != nil {
return err
}
return nil
}

func validateBackendAccessRules(rules []BackendAccessRule) error {
seen := make(map[string]bool)
for i, rule := range rules {
prefix := rule.PathPrefix
if !CanonicalBackendPath(prefix) || (prefix != "/" && strings.HasSuffix(prefix, "/")) {
return fmt.Errorf("accessRules[%d]: pathPrefix must be a clean backend-relative path", i)
}
if len(rule.Methods) == 0 || strings.TrimSpace(rule.ResourceName) != rule.ResourceName || rule.ResourceName == "" {
return fmt.Errorf("accessRules[%d]: methods and resourceName are required", i)
}
switch rule.Verb {
case "get", "create", "update", "delete":
default:
return fmt.Errorf("accessRules[%d]: verb must be get, create, update or delete", i)
}
for _, method := range rule.Methods {
switch method {
case "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH", "DELETE":
default:
return fmt.Errorf("accessRules[%d]: unsupported HTTP method %q", i, method)
}
key := method + " " + prefix
if seen[key] {
return fmt.Errorf("accessRules[%d]: duplicate rule for %s", i, key)
}
seen[key] = true
}
}
return nil
}

// CanonicalBackendPath permits a trailing slash but rejects ambiguous decoded paths.
func CanonicalBackendPath(p string) bool {
return strings.HasPrefix(p, "/") &&
(p == "/" || path.Clean(p) == strings.TrimSuffix(p, "/")) &&
!strings.ContainsAny(p, "%?#\\") && !strings.ContainsFunc(p, unicode.IsControl)
}

// validateGateway checks only what can be known without the cluster. Whether the
// profile names a Service, whether the route ConfigMap has an aggregate route --
// those are answered at startup where the answer can be logged with the reason.
Expand Down
28 changes: 28 additions & 0 deletions internal/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,34 @@ func TestBackendAPIKey(t *testing.T) {
}
}

func TestValidateBackendAccessRules(t *testing.T) {
base := BackendAccessRule{PathPrefix: "/policies", Methods: []string{"POST"}, ResourceName: "autotune-settings", Verb: "create"}
testCases := []struct {
name string
rules []BackendAccessRule
wantErr string
}{
{"separate methods", []BackendAccessRule{base, {PathPrefix: "/policies", Methods: []string{"PUT"}, ResourceName: "autotune-settings", Verb: "update"}}, ""},
{"catch-all", []BackendAccessRule{base, {PathPrefix: "/", Methods: []string{"POST"}, ResourceName: "autotune-unmapped", Verb: "create"}}, ""},
{"duplicate method", []BackendAccessRule{base, base}, "duplicate rule"},
{"trailing slash", []BackendAccessRule{{PathPrefix: "/policies/", Methods: base.Methods, ResourceName: base.ResourceName, Verb: base.Verb}}, "clean backend-relative path"},
{"missing resource name", []BackendAccessRule{{PathPrefix: "/policies", Methods: base.Methods, Verb: base.Verb}}, "methods and resourceName"},
{"unsupported method", []BackendAccessRule{{PathPrefix: "/policies", Methods: []string{"post"}, ResourceName: base.ResourceName, Verb: base.Verb}}, "unsupported HTTP method"},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
backend := Backend{Name: "autotune", Prefix: "/api/autotune", URL: "http://autotune:8000/api", AccessRules: tc.rules}
err := validateBackend(backend)
if tc.wantErr == "" && err != nil {
t.Fatalf("unexpected error: %v", err)
}
if tc.wantErr != "" && (err == nil || !strings.Contains(err.Error(), tc.wantErr)) {
t.Fatalf("want error containing %q, got %v", tc.wantErr, err)
}
})
}
}

// document is what a config file says, and the YAML key names are part of the
// contract: KnownFields turns a typo into a startup failure instead of a setting
// that quietly does nothing.
Expand Down
25 changes: 23 additions & 2 deletions internal/server/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"net/http"
"net/http/httputil"
"net/url"
"slices"
"strings"

"github.com/modelsphere/console/internal/config"
Expand Down Expand Up @@ -72,8 +73,14 @@ func (s *Server) mountBackends(mux *http.ServeMux) {
mux.HandleFunc(prefix+"/route-options", func(w http.ResponseWriter, r *http.Request) {
s.handleRouteOptions(w, r, b, catalogResolve)
})
mux.HandleFunc(strings.TrimSuffix(b.Prefix, "/")+"/", func(w http.ResponseWriter, r *http.Request) {
if !s.authorize(w, r, backendVerb(r.Method), backendResource, b.Name) {
mux.HandleFunc(prefix+"/", func(w http.ResponseWriter, r *http.Request) {
relative := strings.TrimPrefix(r.URL.Path, prefix)
if len(b.AccessRules) > 0 && !config.CanonicalBackendPath(relative) {
writeError(w, http.StatusBadRequest, "invalid backend path")
return
}
verb, name := backendAccess(b, r.Method, relative)
if !s.authorize(w, r, verb, backendResource, name) {
return
}
target, err := resolve(r.Context())
Expand Down Expand Up @@ -104,6 +111,20 @@ func (s *Server) mountBackends(mux *http.ServeMux) {
}
}

func backendAccess(b config.Backend, method, relative string) (verb, resourceName string) {
verb, resourceName = backendVerb(method), b.Name
longest := 0
for _, rule := range b.AccessRules {
prefix := rule.PathPrefix
if len(prefix) > longest && (prefix == "/" || relative == prefix || strings.HasPrefix(relative, prefix+"/")) &&
slices.Contains(rule.Methods, method) {
verb, resourceName = rule.Verb, rule.ResourceName
longest = len(prefix)
}
}
return verb, resourceName
}

// backendTargets resolves each backend once for the process: a gateway resolver
// holds a cache, and the router and the backend's own prefix share it.
func (s *Server) backendTargets() map[string]targetResolver {
Expand Down
62 changes: 60 additions & 2 deletions internal/server/proxy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,58 @@ func TestProxyAuthorizesPerBackendAndVerb(t *testing.T) {
}
}

func TestProxySeparatesBackendAccessFromSettingsWrites(t *testing.T) {
up, seen := upstream(t)
h := testServerWithConfig(t, &config.Config{Backends: []config.Backend{{
Name: "autotune", Prefix: "/api/autotune", URL: up.URL + "/api",
AccessRules: []config.BackendAccessRule{
{PathPrefix: "/search-spaces", Methods: []string{"POST"}, ResourceName: "autotune-settings", Verb: "create"},
{PathPrefix: "/search-spaces/preview", Methods: []string{"POST"}, ResourceName: "autotune", Verb: "get"},
{PathPrefix: "/policies", Methods: []string{"POST"}, ResourceName: "autotune-settings", Verb: "create"},
{PathPrefix: "/policies", Methods: []string{"PUT", "PATCH"}, ResourceName: "autotune-settings", Verb: "update"},
{PathPrefix: "/policies", Methods: []string{"DELETE"}, ResourceName: "autotune-settings", Verb: "delete"},
{PathPrefix: "/settings", Methods: []string{"GET", "HEAD", "OPTIONS"}, ResourceName: "autotune-settings", Verb: "get"},
{PathPrefix: "/settings", Methods: []string{"PUT", "PATCH"}, ResourceName: "autotune-settings", Verb: "update"},
{PathPrefix: "/campaigns", Methods: []string{"POST"}, ResourceName: "autotune", Verb: "create"},
{PathPrefix: "/", Methods: []string{"POST", "PUT", "PATCH", "DELETE"}, ResourceName: "autotune-unmapped", Verb: "update"},
},
}}}).Handler()
bob := login(t, h, "bob", "bob-pw")
check := func(method, endpoint string, status int) {
t.Helper()
if rec := do(h, method, "/api/autotune"+endpoint, bob, ""); rec.Code != status {
t.Fatalf("%s %s: want %d, got %d %s", method, endpoint, status, rec.Code, rec.Body.String())
}
}

grantNamedBackend(t, h, "bob", "autotune", "get")
check("GET", "/policies", http.StatusTeapot)
check("POST", "/search-spaces/preview?limit=3", http.StatusTeapot)
check("POST", "/campaigns", http.StatusForbidden)

for _, verb := range []string{"create", "update", "delete"} {
grantNamedBackend(t, h, "bob", "autotune", verb)
}
check("POST", "/campaigns", http.StatusTeapot)
check("POST", "/policies", http.StatusForbidden)
check("PUT", "/policies/7", http.StatusForbidden)
check("PATCH", "/policies/7", http.StatusForbidden)
check("DELETE", "/policies/7", http.StatusForbidden)
check("POST", "/search-spaces", http.StatusForbidden)
check("POST", "/search-spaces/previews", http.StatusForbidden)
check("POST", "/other", http.StatusForbidden)
check("GET", "/settings", http.StatusForbidden)
check("HEAD", "/settings", http.StatusForbidden)
check("PUT", "/settings", http.StatusForbidden)

grantNamedBackend(t, h, "bob", "autotune-settings", "update")
check("PUT", "/policies/7", http.StatusTeapot)
check("PUT", "/other", http.StatusForbidden)
if len(*seen) != 4 || (*seen)[1].path != "/api/search-spaces/preview" || (*seen)[1].query != "limit=3" {
t.Fatalf("unexpected upstream requests: %+v", *seen)
}
}

// A backend with a credential of its own (the model gateway) gets that key as
// its Bearer token, not the caller's session -- the session authorizes the
// caller to console, and nothing else.
Expand Down Expand Up @@ -350,13 +402,19 @@ func TestProxyLeavesOwnRoutesAlone(t *testing.T) {

// grantBackend binds user to a role allowing verb on the "swiss" backend.
func grantBackend(t *testing.T, h http.Handler, user, verb string) {
t.Helper()
grantNamedBackend(t, h, user, "swiss", verb)
}

func grantNamedBackend(t *testing.T, h http.Handler, user, backend, verb string) {
t.Helper()
admin := login(t, h, "admin", "admin-pw")
role := `{"name":"swiss-` + verb + `","rules":[{"verbs":["` + verb + `"],"apiGroups":["iam.theriseunion.io"],"resources":["backends"],"resourceNames":["swiss"]}]}`
name := backend + "-" + verb
role := fmt.Sprintf(`{"name":%q,"rules":[{"verbs":[%q],"apiGroups":["iam.theriseunion.io"],"resources":["backends"],"resourceNames":[%q]}]}`, name, verb, backend)
if rec := do(h, "POST", "/api/iam/roles", admin, role); rec.Code != http.StatusCreated {
t.Fatalf("create role: %d %s", rec.Code, rec.Body.String())
}
binding := `{"name":"` + user + `-swiss-` + verb + `","role":"swiss-` + verb + `","subjects":[{"kind":"User","name":"` + user + `"}]}`
binding := fmt.Sprintf(`{"name":%q,"role":%q,"subjects":[{"kind":"User","name":%q}]}`, user+"-"+name, name, user)
if rec := do(h, "POST", "/api/iam/rolebindings", admin, binding); rec.Code != http.StatusCreated {
t.Fatalf("create binding: %d %s", rec.Code, rec.Body.String())
}
Expand Down
3 changes: 2 additions & 1 deletion internal/server/route_options.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ func (s *Server) handleRouteOptions(w http.ResponseWriter, r *http.Request, b co
writeError(w, http.StatusMethodNotAllowed, "GET required")
return
}
if !s.authorize(w, r, "get", backendResource, b.Name) {
verb, name := backendAccess(b, r.Method, "/route-options")
if !s.authorize(w, r, verb, backendResource, name) {
return
}
route := r.URL.Query().Get("route")
Expand Down
Loading
Loading