Skip to content

feat(bff): introduce support of multiple auth methods (internal, user_token) #918

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Apr 17, 2025
Merged
Show file tree
Hide file tree
Changes from 4 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
3 changes: 2 additions & 1 deletion clients/ui/bff/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ MOCK_MR_CLIENT ?= false
DEV_MODE ?= false
DEV_MODE_PORT ?= 8080
STANDALONE_MODE ?= true
AUTH_METHOD ?= internal
#frontend static assets root directory
STATIC_ASSETS_DIR ?= ./static
# ENVTEST_K8S_VERSION refers to the version of kubebuilder assets to be downloaded by envtest binary.
Expand Down Expand Up @@ -50,7 +51,7 @@ build: fmt vet test ## Builds the project to produce a binary executable.
.PHONY: run
run: fmt vet envtest ## Runs the project.
ENVTEST_ASSETS="$(shell $(ENVTEST) use $(ENVTEST_K8S_VERSION) --bin-dir $(LOCALBIN) -p path)" \
go run ./cmd --port=$(PORT) --static-assets-dir=$(STATIC_ASSETS_DIR) --mock-k8s-client=$(MOCK_K8S_CLIENT) --mock-mr-client=$(MOCK_MR_CLIENT) --dev-mode=$(DEV_MODE) --dev-mode-port=$(DEV_MODE_PORT) --standalone-mode=$(STANDALONE_MODE) --log-level=$(LOG_LEVEL) --allowed-origins=$(ALLOWED_ORIGINS)
go run ./cmd --port=$(PORT) --auth-method=${AUTH_METHOD} --static-assets-dir=$(STATIC_ASSETS_DIR) --mock-k8s-client=$(MOCK_K8S_CLIENT) --mock-mr-client=$(MOCK_MR_CLIENT) --dev-mode=$(DEV_MODE) --dev-mode-port=$(DEV_MODE_PORT) --standalone-mode=$(STANDALONE_MODE) --log-level=$(LOG_LEVEL) --allowed-origins=$(ALLOWED_ORIGINS)

##@ Dependencies

Expand Down
65 changes: 45 additions & 20 deletions clients/ui/bff/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ The main difference between the two docker compose files is that `-local` one bu

When shutting down the docker compose, you might want to clean-up the SQLite db file generated by ML Metadata, for example `./test/config/ml-metadata/metadata.sqlite.db`

# Development
## Development

Run the following command to build the BFF:

Expand Down Expand Up @@ -61,7 +61,17 @@ make lint

For more information on configuring golangci-lint see the [documentation](https://golangci-lint.run/).

# Building and Deploying
## Running the linter locally
The BFF directory uses golangci-lint to combine multiple linters for a more comprehensive linting process. To install and run simply use:

```shell
cd clients/ui/bff
make lint
```

For more information on configuring golangci-lint see the [documentation](https://golangci-lint.run/).

## Building and Deploying

Run the following command to build the BFF:

Expand All @@ -88,25 +98,25 @@ See the [OpenAPI specification](../api/openapi/mod-arch.yaml) for a complete lis
You will need to inject your requests with a `kubeflow-userid` header and namespace for authorization purposes.

When running the service with the mocked Kubernetes client (MOCK_K8S_CLIENT=true), the user `[email protected]` is preconfigured with the necessary RBAC permissions to perform these actions.

```
# GET /v1/healthcheck
curl -i -H "kubeflow-userid: [email protected]" "localhost:4000/api/v1/healthcheck"
# GET /v1/healthcheck
curl -i "localhost:4000/healthcheck"
```
```

```
# GET /v1/user
# GET /v1/user
curl -i -H "kubeflow-userid: [email protected]" "localhost:4000/api/v1/user"
curl -i -H "X-Forwarded-Access-Token: $TOKEN" "localhost:4000/api/v1/user"
```

```
# GET /v1/namespaces (only works when DEV_MODE=true)
curl -i -H "kubeflow-userid: [email protected]" "localhost:4000/api/v1/namespaces"
curl -i -H "X-Forwarded-Access-Token: $TOKEN" "localhost:4000/api/v1/namespaces"
```

```
# GET /v1/model_registry
curl -i -H "kubeflow-userid: [email protected]" "localhost:4000/api/v1/model_registry?namespace=kubeflow"
curl -i -H "X-Forwarded-Access-Token: $TOKEN" "localhost:4000/api/v1/model_registry?namespace=kubeflow"
```

```
Expand All @@ -120,6 +130,7 @@ curl -i \
```
# GET /v1/model_registry/{model_registry_id}/registered_models
curl -i -H "kubeflow-userid: [email protected]" "localhost:4000/api/v1/model_registry/model-registry/registered_models?namespace=kubeflow"
curl -i -H "X-Forwarded-Access-Token: $TOKEN" "localhost:4000/api/v1/model_registry/model-registry-service/registered_models?namespace=kubeflow-user-example-com""
```

```
Expand Down Expand Up @@ -360,24 +371,38 @@ The mock Kubernetes environment is activated when the environment variable `MOCK
- `non-model-registry`: resides in the `kubeflow` namespace _without_ the label `component: model-registry`.
- `model-registry-dora`: resides in the `dora-namespace` namespace with the label `component: model-registry`.

#### 3. How BFF authorization works for kubeflow-userid and kubeflow-groups?
#### 3. Which Authentication methods are supported?

The BFF supports two authentication modes, selectable via the --auth-method flag or AUTH_METHOD environment variable (default: internal):

Authorization is performed using Kubernetes SubjectAccessReview (SAR), which validates user access to resources.
- `internal`: Uses the credentials of the running backend.
- If running inside the cluster, it uses the pod’s service account.
- If running locally (e.g. for development), it uses the current user's active kubeconfig context.
- In this mode, user identity is passed via the kubeflow-userid and optionally kubeflow-groups headers.
- This is the default mode and works well with mock clients and local testing.
- `user_token`: Uses a user-provided Bearer token for authentication.
- The token must be passed in the `X-Forwarded-Access-Token` header.
- Useful when the frontend is fronted by an auth proxy (e.g., Istio + OIDC) that injects a valid Kubernetes token.

- `kubeflow-userid`: Required header that specifies the user’s email. Access is checked directly for the user via SAR.
- `kubeflow-groups`: Optional header with a comma-separated list of groups. If the user does not have access, SAR checks group permissions using OR logic. If any group has access, the request is authorized.

Access to Model Registry List:
#### 4. How BFF authorization works?

- To list all model registries (/v1/model_registry), we perform a SAR check for get and list verbs on services within the specified namespace.
- If the user or any group has permission to get and list services in the namespace, the request is authorized.
Authorization is performed using Kubernetes access reviews, validating whether the user (or their groups) can perform certain actions.
There are two review mechanisms depending on the authentication mode:
- Internal mode (auth-method=internal):
Uses SubjectAccessReview (SAR) to check whether the impersonated user (from kubeflow-userid and kubeflow-groups headers) has the required permissions.
- User token mode (auth-method=user_token): Uses SelfSubjectAccessReview (SSAR), leveraging the Bearer token provided in the X-Forwarded-Access-Token header to check the current user's permissions directly.

Access to Specific Model Registry Endpoints:
##### Authorization logic
* Access to Model Registry List (/v1/model_registry):
- Checks for get and list on services in the target namespace.
- If the user (or groups, in internal mode) has permission, access is granted.

- For other endpoints (e.g., /v1/model_registry/{model_registry_id}/...), we perform a SAR check for get and list verbs on the specific service (identified by model_registry_id) within the namespace.
- If the user or any group has permission to get or list the specific service, the request is authorized.
* Access to Specific Model Registry Endpoints (/v1/model_registry/{model_registry_id}/...):
- Checks for get on the specific service (identified by model_registry_id) in the namespace.
- If authorized, access is granted.

#### 4. How do I allow CORS requests from other origins
#### 5. How do I allow CORS requests from other origins

When serving the UI directly from the BFF there is no need for any CORS headers to be served, by default they are turned off for security reasons.

Expand Down
13 changes: 10 additions & 3 deletions clients/ui/bff/cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import (
func main() {
var cfg config.EnvConfig
var certFile, keyFile string

fmt.Println("Starting Model Registry UI BFF!")
flag.IntVar(&cfg.Port, "port", getEnvAsInt("PORT", 8080), "API server port")
flag.StringVar(&certFile, "cert-file", "", "Path to TLS certificate file")
flag.StringVar(&keyFile, "key-file", "", "Path to TLS key file")
Expand All @@ -32,12 +32,19 @@ func main() {
flag.StringVar(&cfg.StaticAssetsDir, "static-assets-dir", "./static", "Configure frontend static assets root directory")
flag.TextVar(&cfg.LogLevel, "log-level", parseLevel(getEnvAsString("LOG_LEVEL", "INFO")), "Sets server log level, possible values: error, warn, info, debug")
flag.Func("allowed-origins", "Sets allowed origins for CORS purposes, accepts a comma separated list of origins or * to allow all, default none", newOriginParser(&cfg.AllowedOrigins, getEnvAsString("ALLOWED_ORIGINS", "")))
flag.StringVar(&cfg.AuthMethod, "auth-method", "internal", "Authentication method (internal or user_token)")
flag.Parse()

logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
Level: cfg.LogLevel,
}))

//validate auth method
if cfg.AuthMethod != config.AuthMethodInternal && cfg.AuthMethod != config.AuthMethodUser {
logger.Error("invalid auth method: (must be internal or user_token)", "authMethod", cfg.AuthMethod)
os.Exit(1)
}

// Only use for logging errors about logging configuration.
slog.SetDefault(logger)

Expand Down Expand Up @@ -92,8 +99,8 @@ func main() {
logger.Error("server shutdown failed", "error", err)
}

// Shutdown the Kubernetes manager gracefully
if err := app.Shutdown(ctx, logger); err != nil {
// Shutdown the App gracefully
if err := app.Shutdown(); err != nil {
logger.Error("failed to shutdown Kubernetes manager", "error", err)
}

Expand Down
9 changes: 0 additions & 9 deletions clients/ui/bff/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,9 @@ require (
)

require (
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/emicklei/go-restful/v3 v3.11.0 // indirect
github.com/evanphx/json-patch/v5 v5.9.0 // indirect
github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/fxamacker/cbor/v2 v2.7.0 // indirect
github.com/go-logr/logr v1.4.2 // indirect
github.com/go-logr/zapr v1.3.0 // indirect
Expand All @@ -32,7 +29,6 @@ require (
github.com/go-openapi/swag v0.23.0 // indirect
github.com/go-task/slim-sprig/v3 v3.0.0 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
github.com/golang/protobuf v1.5.4 // indirect
github.com/google/gnostic-models v0.6.8 // indirect
github.com/google/go-cmp v0.6.0 // indirect
Expand All @@ -47,10 +43,6 @@ require (
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/prometheus/client_golang v1.19.1 // indirect
github.com/prometheus/client_model v0.6.1 // indirect
github.com/prometheus/common v0.55.0 // indirect
github.com/prometheus/procfs v0.15.1 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/stretchr/objx v0.5.2 // indirect
github.com/x448/float16 v0.8.4 // indirect
Expand All @@ -64,7 +56,6 @@ require (
golang.org/x/text v0.21.0 // indirect
golang.org/x/time v0.7.0 // indirect
golang.org/x/tools v0.26.0 // indirect
gomodules.xyz/jsonpatch/v2 v2.4.0 // indirect
google.golang.org/protobuf v1.35.1 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
Expand Down
2 changes: 0 additions & 2 deletions clients/ui/bff/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/emicklei/go-restful/v3 v3.11.0 h1:rAQeMHw1c7zTmncogyy8VvRZwtkmkZ4FxERmMY4rD+g=
github.com/emicklei/go-restful/v3 v3.11.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc=
github.com/evanphx/json-patch v0.5.2 h1:xVCHIVMUu1wtM/VkR9jVZ45N3FhZfYMMYGorLCR8P3k=
github.com/evanphx/json-patch v0.5.2/go.mod h1:ZWS5hhDbVDyob71nXKNL0+PWn6ToqBHMikGIFbs31qQ=
github.com/evanphx/json-patch/v5 v5.9.0 h1:kcBlZQbplgElYIlo/n1hJbls2z/1awpXxpRi0/FOJfg=
github.com/evanphx/json-patch/v5 v5.9.0/go.mod h1:VNkHZ/282BpEyt/tObQO8s5CMPmYYq14uClGH4abBuQ=
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
Expand Down
Loading
Loading