diff --git a/access/pkg/server/server.go b/access/pkg/server/server.go index 018468a..7923b77 100644 --- a/access/pkg/server/server.go +++ b/access/pkg/server/server.go @@ -176,8 +176,7 @@ func Run(ctx context.Context, o *Options) error { if err != nil && !errors.Is(err, context.Canceled) { return fmt.Errorf("rbac provider failed: %w", err) } - <-serveErr - return nil + return <-serveErr case err := <-serveErr: return err } diff --git a/tenancy/README.md b/tenancy/README.md index 1407748..e25e17e 100644 --- a/tenancy/README.md +++ b/tenancy/README.md @@ -47,7 +47,7 @@ root │ │ │ ├── web ................... WorkspaceType: project │ │ APIBinding tenancy-access ... from the WorkspaceType - │ │ ClusterRole tenancy.contrib.kcp.io:role:admin + │ │ ClusterRole tenancy.platform.kcp.io:role:admin │ │ ClusterRoleBinding ...:membership:alice-admin │ │ Namespace "default" ... created by the operator │ │ @@ -203,6 +203,14 @@ run it twice and the second run is a no-op. Quote `"$KUBECONFIG"` — unset and unquoted, the shell drops the argument and `--kubeconfig` swallows the next flag, giving the baffling `load kubeconfig: stat --workspace-path`. +Platform administrators — whoever creates and deletes Tenants — are named +here too: `--platform-admin-user` and `--platform-admin-group` (both +repeatable) bind them to `tenancy.platform.kcp.io:platform-admin` in the +store, a role that may enter it and manage Tenants and nothing else. The +binding holds exactly the identities of the latest run, so dropping one +from the flags revokes it. In production, name a group your identity +provider asserts rather than individual users. + ### 5. Run the operator ```sh @@ -304,7 +312,7 @@ Workspace names are DNS labels; display names are arbitrary UTF-8. The - `slug` (default): lowercase the display name, collapse everything else to dashes ("Acme Corp" → `acme-corp`). On collision with a workspace owned by a different object, fall back to the slug plus a hash of the object's UID. - Ownership is tracked with a `tenancy.contrib.kcp.io/owner-uid` label, so + Ownership is tracked with a `tenancy.kcp.hub/owner-uid` label, so reconciles converge without storing decisions anywhere. - `uid`: always name by UID hash. Opaque, but immune to display-name games. @@ -317,7 +325,7 @@ always proposes the same candidates. front-proxy: ``` -POST /services/tenancy/apis/tenancy.contrib.kcp.io/v1alpha1/selftenancyreviews +POST /services/tenancy/apis/tenancy.platform.kcp.io/v1alpha1/selftenancyreviews ``` The caller POSTs an empty object; the answer lists their tenants with @@ -410,8 +418,12 @@ is for a self-signed local serving certificate; in a deployment pass `--certificate-authority` instead. `kubeconfig` is the other half of a login: it asks the virtual workspace -what the caller can reach and writes one context per tenant and per -project, each pointing at that workspace's own URL. There is still no user +what the caller can reach and writes one context per **project**, each +pointing at that workspace's own URL. Projects only, because a tenant +workspace is where this system keeps its own records — a Membership +materializes RBAC in that tenant's projects, never in the tenant itself, +so no member can enter it and a context for it would only ever answer +`Forbidden`. There is still no user registry to enrol into — `login` obtains a credential, it does not create an identity. Issuing identities belongs to your provider, and a `Membership` only records what one may do. @@ -471,8 +483,8 @@ PKI=$PWD/pki # or tenancy/.e2e/pki # ask who you are: curl -ks --cert "$PKI/alice.crt" --key "$PKI/alice.key" \ -X POST -H 'Content-Type: application/json' \ - -d '{"apiVersion":"tenancy.contrib.kcp.io/v1alpha1","kind":"SelfTenancyReview"}' \ - https://localhost:9445/services/tenancy/apis/tenancy.contrib.kcp.io/v1alpha1/selftenancyreviews + -d '{"apiVersion":"tenancy.platform.kcp.io/v1alpha1","kind":"SelfTenancyReview"}' \ + https://localhost:9445/services/tenancy/apis/tenancy.platform.kcp.io/v1alpha1/selftenancyreviews # ...and whether the directory is being fed at all: curl -ks --cert "$PKI/alice.crt" --key "$PKI/alice.key" \ @@ -490,6 +502,15 @@ Reading the answers: - `403 ... authentication required` means no certificate was presented at all; the review is only served to an authenticated caller. +## Regenerating the schemas + +The `apiresourceschema-*.yaml` assets are generated from the Go types by +`make generate` (controller-gen + kcp's `apigen`; see +[../hack/update-apiresourceschemas.sh](../hack/update-apiresourceschemas.sh)). +After changing anything under `sdk/apis/`, run it and commit the result — +and if a schema's name changed, update `ExportsOrder` in +[config/apiexport/bootstrap.go](config/apiexport/bootstrap.go). + ## Testing From the repository root: @@ -541,14 +562,21 @@ SelfTenancyReview scenarios authenticate with. identity exists because your IdP issued it a credential, and a `Membership` names it verbatim. A typo in a subject name is not an error, it is a grant nobody holds. -6. **There is no tenant self-service.** The virtual workspace serves - `SelfTenancyReview` and nothing else, so Projects and Memberships are - written straight to kcp by someone holding an admin kubeconfig — - `tenancyctl` included. A tenant cannot manage their own projects, - because the tier those objects live in names no tenant identity. The - intended shape is for those writes to arrive through the virtual - workspace, which would hold the only credential into that tier and - could enforce guards a direct write bypasses. +6. **Self-service is narrow, and mediated.** Besides `SelfTenancyReview`, + the virtual workspace accepts exactly three writes, each performed with + its own credential into the tenant tier rather than a grant to the + caller: + - `SelfTenantRequest` gives a caller their first tenant, with the + caller as its admin. It is off unless the deployment passes + `--self-service-tenants`, and `--self-service-tenant-groups` limits it + to groups the identity provider asserts. + - `SelfProjectRequest` creates a project in a tenant the caller + administers. The caller names the project and nothing else. + - `memberships` lists, grants and revokes access in tenants the caller + administers. + + Anything else — deleting a tenant or project, renaming one — is still + written straight to kcp by someone holding an admin kubeconfig. 7. **The operator is not an administrator, and that is load-bearing.** It holds no admin client; every write goes through one of the four exports, so its reach is exactly their claims. The flip side is that a workspace diff --git a/tenancy/cmd/init.go b/tenancy/cmd/init.go index dad63a7..ea25182 100644 --- a/tenancy/cmd/init.go +++ b/tenancy/cmd/init.go @@ -41,6 +41,8 @@ func newInitCommand() *cobra.Command { workspaceType string serverUsers []string serverGroups []string + adminUsers []string + adminGroups []string timeout time.Duration ) @@ -109,10 +111,17 @@ root down. Idempotent: safe to run on every pod start and every upgrade.`, if err != nil { return fmt.Errorf("resolve workspace path %s: %w", storePath, err) } - if err := bootstrap.BindStore(ctx, storeCfg, result); err != nil { + if err := bootstrap.BindStore(ctx, storeCfg, result, bootstrap.Options{ + ServerUsers: serverUsers, + ServerGroups: serverGroups, + }); err != nil { return fmt.Errorf("bind the Tenant API into %s: %w", storePath, err) } - logger.Info("tenant store ready", "workspace", storePath) + if err := bootstrap.GrantPlatformAdmins(ctx, storeCfg, adminUsers, adminGroups); err != nil { + return fmt.Errorf("grant platform admins in %s: %w", storePath, err) + } + logger.Info("tenant store ready", "workspace", storePath, + "platformAdminUsers", adminUsers, "platformAdminGroups", adminGroups) } if tenantsWorkspace != "" { tenantsPath, err = accessbootstrap.JoinWorkspacePath(workspacePrefix, tenantsWorkspace) @@ -187,6 +196,11 @@ root down. Idempotent: safe to run on every pod start and every upgrade.`, "or the virtual workspace does not run as this bootstrap's own credential.") cmd.Flags().StringSliceVar(&serverGroups, "server-group", nil, "Additional Group to grant the server role to, repeatable.") + cmd.Flags().StringSliceVar(&adminUsers, "platform-admin-user", nil, + "User who may manage Tenants in the store workspace, repeatable. Bound to a role "+ + "that allows exactly that; anyone left off the list on a later run loses it.") + cmd.Flags().StringSliceVar(&adminGroups, "platform-admin-group", nil, + "Group, as the identity provider asserts it, whose members may manage Tenants, repeatable.") cmd.Flags().DurationVar(&timeout, "timeout", 3*time.Minute, "Overall time budget for installing and verifying.") diff --git a/tenancy/cmd/root.go b/tenancy/cmd/root.go index ff98c90..85d8f36 100644 --- a/tenancy/cmd/root.go +++ b/tenancy/cmd/root.go @@ -25,6 +25,8 @@ import ( ctrllog "sigs.k8s.io/controller-runtime/pkg/log" "k8s.io/klog/v2" + + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/pkg/cli" ) // Execute runs the tenancy binary. @@ -45,6 +47,9 @@ func Execute() error { root.AddCommand(newInitCommand()) root.AddCommand(newOperatorCommand()) root.AddCommand(newVirtualWorkspaceCommand()) + // seed is shared with the CLI: one idempotent command any environment + // (Tilt, demos, CI) uses to converge on baseline tenancy data. + root.AddCommand(cli.NewSeedCommand()) return root.Execute() } diff --git a/tenancy/config/apiexport/apiexport-platform.yaml b/tenancy/config/apiexport/apiexport-platform.yaml index 8ab64bf..cbad10f 100644 --- a/tenancy/config/apiexport/apiexport-platform.yaml +++ b/tenancy/config/apiexport/apiexport-platform.yaml @@ -10,7 +10,7 @@ metadata: spec: resources: - name: tenants - group: tenancy.contrib.kcp.io - schema: v1alpha1.tenants.tenancy.contrib.kcp.io + group: tenancy.platform.kcp.io + schema: v260926-3d181e5.tenants.tenancy.platform.kcp.io storage: crd: {} diff --git a/tenancy/config/apiexport/apiexport-tenancy.yaml b/tenancy/config/apiexport/apiexport-tenancy.yaml index 47219ae..1989d8c 100644 --- a/tenancy/config/apiexport/apiexport-tenancy.yaml +++ b/tenancy/config/apiexport/apiexport-tenancy.yaml @@ -10,12 +10,12 @@ metadata: spec: resources: - name: projects - group: tenancy.contrib.kcp.io - schema: v1alpha1.projects.tenancy.contrib.kcp.io + group: tenancy.platform.kcp.io + schema: v260924-7813b03.projects.tenancy.platform.kcp.io storage: crd: {} - name: memberships - group: tenancy.contrib.kcp.io - schema: v1alpha1.memberships.tenancy.contrib.kcp.io + group: tenancy.platform.kcp.io + schema: v260924-7813b03.memberships.tenancy.platform.kcp.io storage: crd: {} diff --git a/tenancy/config/apiexport/apiresourceschema-memberships.tenancy.platform.kcp.io.yaml b/tenancy/config/apiexport/apiresourceschema-memberships.tenancy.platform.kcp.io.yaml new file mode 100644 index 0000000..970eff6 --- /dev/null +++ b/tenancy/config/apiexport/apiresourceschema-memberships.tenancy.platform.kcp.io.yaml @@ -0,0 +1,101 @@ +apiVersion: apis.kcp.io/v1alpha1 +kind: APIResourceSchema +metadata: + name: v260924-7813b03.memberships.tenancy.platform.kcp.io +spec: + group: tenancy.platform.kcp.io + names: + kind: Membership + listKind: MembershipList + plural: memberships + singular: membership + scope: Cluster + versions: + - name: v1alpha1 + schema: + description: |- + Membership grants one subject one role in one tenant, or in one project + of that tenant. The operator materializes it as RBAC in the target + workspace; deleting the Membership removes that RBAC again. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: MembershipSpec is the desired state of a Membership. + properties: + project: + description: |- + Project optionally narrows the grant to one project of the tenant. + Empty means the grant applies to the tenant's workspace, which every + project workspace nests under. + type: string + role: + description: 'Role is the access level granted: view, edit or admin.' + enum: + - view + - edit + - admin + type: string + subject: + description: Subject is who the grant is for. + properties: + kind: + description: Kind is User or Group. + enum: + - User + - Group + type: string + name: + description: |- + Name is the username or group name, compared verbatim against the + identity kcp authenticates. No issuer prefixes are added or stripped + here; the deployment's authentication configuration must agree with + kcp's. + type: string + required: + - kind + - name + type: object + tenant: + description: Tenant names the Tenant (in the same workspace) the grant + applies to. + type: string + required: + - role + - subject + - tenant + type: object + status: + description: MembershipStatus is the observed state of a Membership. + properties: + message: + type: string + phase: + description: |- + Phase describes where a tenancy object is in its lifecycle. It is a + coarse, human-first signal; Message carries the detail when a phase is + not Ready. + type: string + type: object + required: + - spec + type: object + served: true + storage: true + subresources: + status: {} diff --git a/tenancy/config/apiexport/apiresourceschema-memberships.yaml b/tenancy/config/apiexport/apiresourceschema-memberships.yaml deleted file mode 100644 index 973e396..0000000 --- a/tenancy/config/apiexport/apiresourceschema-memberships.yaml +++ /dev/null @@ -1,88 +0,0 @@ -apiVersion: apis.kcp.io/v1alpha1 -kind: APIResourceSchema -metadata: - name: v1alpha1.memberships.tenancy.contrib.kcp.io -spec: - group: tenancy.contrib.kcp.io - names: - kind: Membership - listKind: MembershipList - plural: memberships - singular: membership - scope: Cluster - versions: - - name: v1alpha1 - served: true - storage: true - subresources: - status: {} - schema: - description: | - Membership grants one subject one role in one tenant, or in one - project of that tenant. The operator materializes it as RBAC in - the target workspace; deleting the Membership removes that RBAC - again. - type: object - properties: - apiVersion: - type: string - kind: - type: string - metadata: - type: object - spec: - type: object - required: - - subject - - role - - tenant - properties: - subject: - description: Who the grant is for. - type: object - required: - - kind - - name - properties: - kind: - description: User or Group. - type: string - enum: - - User - - Group - name: - description: | - Username or group name, compared verbatim against - the identity kcp authenticates. - type: string - minLength: 1 - role: - description: Access level granted. - type: string - enum: - - view - - edit - - admin - tenant: - description: | - Name of the Tenant (in the same workspace) the grant - applies to. - type: string - minLength: 1 - project: - description: | - Optionally narrows the grant to one project of the - tenant. Empty means the grant applies to the tenant's - workspace, which every project workspace nests under. - type: string - status: - type: object - properties: - phase: - description: Pending, Ready or Error. - type: string - message: - description: Detail when phase is not Ready. - type: string - required: - - spec diff --git a/tenancy/config/apiexport/apiresourceschema-projects.tenancy.platform.kcp.io.yaml b/tenancy/config/apiexport/apiresourceschema-projects.tenancy.platform.kcp.io.yaml new file mode 100644 index 0000000..8b3caf6 --- /dev/null +++ b/tenancy/config/apiexport/apiresourceschema-projects.tenancy.platform.kcp.io.yaml @@ -0,0 +1,89 @@ +apiVersion: apis.kcp.io/v1alpha1 +kind: APIResourceSchema +metadata: + name: v260924-7813b03.projects.tenancy.platform.kcp.io +spec: + group: tenancy.platform.kcp.io + names: + kind: Project + listKind: ProjectList + plural: projects + singular: project + scope: Cluster + versions: + - name: v1alpha1 + schema: + description: |- + Project asks for a workspace nested under a tenant's workspace. Projects + are the unit teams actually work in; tenant-wide Memberships reach every + project, project Memberships reach one. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: ProjectSpec is the desired state of a Project. + properties: + description: + description: Description is free text for humans. + type: string + displayName: + description: |- + DisplayName is the human name of the project; it seeds the workspace + name the same way a tenant's does. + type: string + tenant: + description: |- + Tenant names the Tenant (in the same workspace) this project belongs + to. The project's workspace is created under that tenant's workspace. + type: string + required: + - displayName + - tenant + type: object + status: + description: ProjectStatus is the observed state of a Project. + properties: + message: + type: string + phase: + description: |- + Phase describes where a tenancy object is in its lifecycle. It is a + coarse, human-first signal; Message carries the detail when a phase is + not Ready. + type: string + url: + description: URL is the direct address of the provisioned workspace. + type: string + workspace: + description: |- + Workspace is the name of the provisioned Workspace object, inside the + tenant's workspace. + type: string + workspaceCluster: + description: |- + WorkspaceCluster is the logical cluster name backing the provisioned + workspace. + type: string + type: object + required: + - spec + type: object + served: true + storage: true + subresources: + status: {} diff --git a/tenancy/config/apiexport/apiresourceschema-projects.yaml b/tenancy/config/apiexport/apiresourceschema-projects.yaml deleted file mode 100644 index ae7f499..0000000 --- a/tenancy/config/apiexport/apiresourceschema-projects.yaml +++ /dev/null @@ -1,72 +0,0 @@ -apiVersion: apis.kcp.io/v1alpha1 -kind: APIResourceSchema -metadata: - name: v1alpha1.projects.tenancy.contrib.kcp.io -spec: - group: tenancy.contrib.kcp.io - names: - kind: Project - listKind: ProjectList - plural: projects - singular: project - scope: Cluster - versions: - - name: v1alpha1 - served: true - storage: true - subresources: - status: {} - schema: - description: | - Project asks for a workspace nested under a tenant's workspace. - Projects are the unit teams actually work in; tenant-wide - Memberships reach every project, project Memberships reach one. - type: object - properties: - apiVersion: - type: string - kind: - type: string - metadata: - type: object - spec: - type: object - required: - - tenant - - displayName - properties: - tenant: - description: | - Name of the Tenant (in the same workspace) this project - belongs to. - type: string - minLength: 1 - displayName: - description: | - Human name of the project; seeds the workspace name the - same way a tenant's does. - type: string - minLength: 1 - description: - description: Free text for humans. - type: string - status: - type: object - properties: - phase: - description: Pending, Ready or Error. - type: string - message: - description: Detail when phase is not Ready. - type: string - workspace: - description: Name of the provisioned Workspace object. - type: string - workspaceCluster: - description: Logical cluster backing the provisioned workspace. - type: string - url: - description: Direct address of the provisioned workspace. - type: string - required: - - spec diff --git a/tenancy/config/apiexport/apiresourceschema-tenants.tenancy.platform.kcp.io.yaml b/tenancy/config/apiexport/apiresourceschema-tenants.tenancy.platform.kcp.io.yaml new file mode 100644 index 0000000..2033b61 --- /dev/null +++ b/tenancy/config/apiexport/apiresourceschema-tenants.tenancy.platform.kcp.io.yaml @@ -0,0 +1,100 @@ +apiVersion: apis.kcp.io/v1alpha1 +kind: APIResourceSchema +metadata: + name: v260926-3d181e5.tenants.tenancy.platform.kcp.io +spec: + group: tenancy.platform.kcp.io + names: + kind: Tenant + listKind: TenantList + plural: tenants + singular: tenant + scope: Cluster + versions: + - name: v1alpha1 + schema: + description: |- + Tenant asks for an isolated kcp workspace for one organizational unit. + The operator provisions a workspace under the organization workspace the + Tenant object lives in and reports it in Status. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: TenantSpec is the desired state of a Tenant. + properties: + description: + description: Description is free text for humans. + type: string + displayName: + description: |- + DisplayName is the human name of the tenant. It seeds the workspace + name (subject to the operator's naming strategy) and is returned in + SelfTenancyReview answers. It is not required to be unique. + type: string + firstAdmin: + description: |- + FirstAdmin is an identity granted the admin role on this tenant once + its workspace is ready, as a Membership the operator creates. + + It exists because a tenant nobody administers is unusable, and the + two writes cannot be one: the Membership lives in the tenant's own + workspace, which does not exist when the Tenant is created. Naming + the admin here lets whoever creates the tenant hand it over without + waiting, and is what makes self-service possible — the virtual + workspace sets it to the caller, so a caller cannot make someone + else the admin of a tenant they asked for. + + Empty means nobody is seeded, which is the right answer when an + administrator intends to grant access separately. + type: string + required: + - displayName + type: object + status: + description: TenantStatus is the observed state of a Tenant. + properties: + message: + type: string + phase: + description: |- + Phase describes where a tenancy object is in its lifecycle. It is a + coarse, human-first signal; Message carries the detail when a phase is + not Ready. + type: string + url: + description: URL is the direct address of the provisioned workspace. + type: string + workspace: + description: |- + Workspace is the name of the provisioned Workspace object, in the + same workspace the Tenant lives in. + type: string + workspaceCluster: + description: |- + WorkspaceCluster is the logical cluster name backing the provisioned + workspace. It is the stable address of the tenant's workspace. + type: string + type: object + required: + - spec + type: object + served: true + storage: true + subresources: + status: {} diff --git a/tenancy/config/apiexport/apiresourceschema-tenants.yaml b/tenancy/config/apiexport/apiresourceschema-tenants.yaml deleted file mode 100644 index 694414b..0000000 --- a/tenancy/config/apiexport/apiresourceschema-tenants.yaml +++ /dev/null @@ -1,67 +0,0 @@ -apiVersion: apis.kcp.io/v1alpha1 -kind: APIResourceSchema -metadata: - name: v1alpha1.tenants.tenancy.contrib.kcp.io -spec: - group: tenancy.contrib.kcp.io - names: - kind: Tenant - listKind: TenantList - plural: tenants - singular: tenant - scope: Cluster - versions: - - name: v1alpha1 - served: true - storage: true - subresources: - status: {} - schema: - description: | - Tenant asks for an isolated kcp workspace for one organizational - unit. The tenancy operator provisions a workspace under the - organization workspace this object lives in and reports it in - status. - type: object - properties: - apiVersion: - type: string - kind: - type: string - metadata: - type: object - spec: - type: object - required: - - displayName - properties: - displayName: - description: | - Human name of the tenant. Seeds the workspace name, - subject to the operator's naming strategy. Not required - to be unique. - type: string - minLength: 1 - description: - description: Free text for humans. - type: string - status: - type: object - properties: - phase: - description: Pending, Ready or Error. - type: string - message: - description: Detail when phase is not Ready. - type: string - workspace: - description: Name of the provisioned Workspace object. - type: string - workspaceCluster: - description: Logical cluster backing the provisioned workspace. - type: string - url: - description: Direct address of the provisioned workspace. - type: string - required: - - spec diff --git a/tenancy/config/apiexport/bootstrap.go b/tenancy/config/apiexport/bootstrap.go index 314340f..392e42e 100644 --- a/tenancy/config/apiexport/bootstrap.go +++ b/tenancy/config/apiexport/bootstrap.go @@ -66,9 +66,9 @@ const ( // - the workspace types after the exports they default-bind, so the // references resolve. var ExportsOrder = []string{ - "apiresourceschema-tenants.yaml", - "apiresourceschema-projects.yaml", - "apiresourceschema-memberships.yaml", + "apiresourceschema-tenants.tenancy.platform.kcp.io.yaml", + "apiresourceschema-projects.tenancy.platform.kcp.io.yaml", + "apiresourceschema-memberships.tenancy.platform.kcp.io.yaml", "apiexport-platform.yaml", "apiexport-tenancy.yaml", "apiexport-provisioner.yaml", diff --git a/tenancy/config/apiexport/store-bindings.yaml b/tenancy/config/apiexport/store-bindings.yaml index b7d4cd8..71f671d 100644 --- a/tenancy/config/apiexport/store-bindings.yaml +++ b/tenancy/config/apiexport/store-bindings.yaml @@ -11,5 +11,9 @@ metadata: spec: reference: export: - path: __EXPORTS_PATH__ + # The logical cluster id, not the pretty path: an APIBinding reference + # resolves ids locally on the shard, while pretty paths need the cache + # server's path index — which multi-shard deployments have broken + # before. The WorkspaceTypes reference exports the same way. + path: __EXPORTS_REF__ name: tenancy-platform diff --git a/tenancy/config/apiexport/tenants-bindings.yaml b/tenancy/config/apiexport/tenants-bindings.yaml index fbb561a..c7ed075 100644 --- a/tenancy/config/apiexport/tenants-bindings.yaml +++ b/tenancy/config/apiexport/tenants-bindings.yaml @@ -12,7 +12,11 @@ metadata: spec: reference: export: - path: __EXPORTS_PATH__ + # The logical cluster id, not the pretty path: an APIBinding reference + # resolves ids locally on the shard, while pretty paths need the cache + # server's path index — which multi-shard deployments have broken + # before. The WorkspaceTypes reference exports the same way. + path: __EXPORTS_REF__ name: tenancy-provisioner permissionClaims: - group: tenancy.kcp.io diff --git a/tenancy/config/examples/apibinding-consumer.yaml b/tenancy/config/examples/apibinding-consumer.yaml index 88e64ea..5725087 100644 --- a/tenancy/config/examples/apibinding-consumer.yaml +++ b/tenancy/config/examples/apibinding-consumer.yaml @@ -10,17 +10,17 @@ # hash from the claim on the installed APIExport (init discovered and # injected it there): # -# kubectl get apiexport tenancy.contrib.kcp.io \ +# kubectl get apiexport tenancy.platform.kcp.io \ # -o jsonpath='{.spec.permissionClaims[0].identityHash}' apiVersion: apis.kcp.io/v1alpha2 kind: APIBinding metadata: - name: tenancy.contrib.kcp.io + name: tenancy.platform.kcp.io spec: reference: export: path: root:tenancy:controllers - name: tenancy.contrib.kcp.io + name: tenancy.platform.kcp.io permissionClaims: - group: tenancy.kcp.io resource: workspaces diff --git a/tenancy/pkg/bootstrap/bootstrap.go b/tenancy/pkg/bootstrap/bootstrap.go index 740bb24..a9ed29c 100644 --- a/tenancy/pkg/bootstrap/bootstrap.go +++ b/tenancy/pkg/bootstrap/bootstrap.go @@ -35,7 +35,6 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/apimachinery/pkg/util/yaml" "k8s.io/client-go/discovery" @@ -44,6 +43,7 @@ import ( "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" "k8s.io/client-go/restmapper" + "k8s.io/client-go/util/retry" "k8s.io/klog/v2" "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/config/apiexport" @@ -87,12 +87,6 @@ const ( DefaultTenantsWorkspace = "tenants" ) -// NudgeAnnotation is bumped on an endpoint slice to make kcp recompute its -// URLs. kcp's URLs controller runs when the slice object is reconciled, and -// a consumer binding the export is not a slice event, so a slice created -// before its first consumer would otherwise stay URL-less indefinitely. -const NudgeAnnotation = tenancyv1alpha1.GroupName + "/nudged-at" - // Options configures Bootstrap. type Options struct { // ServerUsers and ServerGroups are additional identities granted the @@ -174,11 +168,27 @@ func Bootstrap(ctx context.Context, cfg *rest.Config, exportsPath string, opts O // BindStore makes the workspace cfg points at the tenant registry: it // binds tenancy-platform, then waits until Tenants are actually servable. -func BindStore(ctx context.Context, cfg *rest.Config, result *Result) error { +func BindStore(ctx context.Context, cfg *rest.Config, result *Result, opts Options) error { if err := applyTier(ctx, cfg, result, apiexport.StoreOrder); err != nil { return err } + // The virtual workspace writes a requested tenant here, through the + // platform export — which needs no standing in this workspace. What it + // does need is to know which logical cluster this is, because an + // export's virtual workspace addresses clusters and not paths. That is + // the whole grant: enter, and read the one object that says where you + // are. + if len(opts.ServerUsers)+len(opts.ServerGroups) > 0 { + kube, err := kubernetes.NewForConfig(cfg) + if err != nil { + return fmt.Errorf("build kubernetes client: %w", err) + } + if err := applyStoreLocator(ctx, kube, opts.ServerUsers, opts.ServerGroups); err != nil { + return fmt.Errorf("grant the server identities the store locator role: %w", err) + } + } + dyn, err := dynamic.NewForConfig(cfg) if err != nil { return fmt.Errorf("build dynamic client: %w", err) @@ -335,15 +345,42 @@ func applyManifests(ctx context.Context, dyn dynamic.Interface, mapper *restmapp client := dyn.Resource(mapping.Resource) if _, err := client.Create(ctx, &obj, metav1.CreateOptions{}); err != nil { + // A hand-bound tier can land on a different shard than the + // exports, and the `bind` RBAC applied moments ago reaches that + // shard through cache replication — so a Forbidden here is + // usually a propagation lag, not a verdict. Retry it briefly. + if apierrors.IsForbidden(err) && gvk.Kind == "APIBinding" { + retryErr := wait.PollUntilContextTimeout(ctx, 3*time.Second, 2*time.Minute, false, func(ctx context.Context) (bool, error) { + _, err := client.Create(ctx, &obj, metav1.CreateOptions{}) + if err == nil || apierrors.IsAlreadyExists(err) { + return true, nil + } + if apierrors.IsForbidden(err) { + return false, nil + } + return false, err + }) + if retryErr != nil { + return fmt.Errorf("create %s %s (after retrying propagation of the bind grant): %w", gvk.Kind, obj.GetName(), retryErr) + } + continue + } if !apierrors.IsAlreadyExists(err) { return fmt.Errorf("create %s %s: %w", gvk.Kind, obj.GetName(), err) } - existing, err := client.Get(ctx, obj.GetName(), metav1.GetOptions{}) + // kcp reconciles some of these objects concurrently (it creates + // and keeps updating a default APIExportEndpointSlice per + // export), so a single get+update can 409. Re-read and retry. + err := retry.RetryOnConflict(retry.DefaultRetry, func() error { + existing, err := client.Get(ctx, obj.GetName(), metav1.GetOptions{}) + if err != nil { + return err + } + obj.SetResourceVersion(existing.GetResourceVersion()) + _, err = client.Update(ctx, &obj, metav1.UpdateOptions{}) + return err + }) if err != nil { - return fmt.Errorf("get existing %s %s: %w", gvk.Kind, obj.GetName(), err) - } - obj.SetResourceVersion(existing.GetResourceVersion()) - if _, err := client.Update(ctx, &obj, metav1.UpdateOptions{}); err != nil { // Some kcp objects reject spec updates (APIResourceSchemas // are immutable); existing is as good as applied. if apierrors.IsInvalid(err) || apierrors.IsForbidden(err) { @@ -355,77 +392,132 @@ func applyManifests(ctx context.Context, dyn dynamic.Interface, mapper *restmapp } } -// applyServerIdentity grants the server role to the given identities. -func applyServerIdentity(ctx context.Context, kube kubernetes.Interface, users, groups []string) error { +// applyStoreLocator grants the least a server needs to find out which +// logical cluster the store workspace is: kcp's workspace gate, and a read +// of the LogicalCluster that names it. Deliberately not the Tenant API — +// tenants are written through the platform export, not through here. +func applyStoreLocator(ctx context.Context, kube kubernetes.Interface, users, groups []string) error { role := &rbacv1.ClusterRole{ - ObjectMeta: metav1.ObjectMeta{Name: tenancyv1alpha1.GroupName + ":server"}, + ObjectMeta: metav1.ObjectMeta{Name: tenancyv1alpha1.GroupName + ":store-locator"}, Rules: []rbacv1.PolicyRule{ { Verbs: []string{"access"}, NonResourceURLs: []string{"/"}, }, { - APIGroups: []string{"apis.kcp.io"}, - Resources: []string{"apiexports", "apiexportendpointslices", "apibindings"}, - Verbs: []string{"get", "list", "watch"}, + APIGroups: []string{"core.kcp.io"}, + Resources: []string{"logicalclusters"}, + Verbs: []string{"get"}, }, + }, + } + return applyRoleAndBinding(ctx, kube, role, users, groups) +} + +// GrantPlatformAdmins makes the given identities administrators of the +// tenant registry cfg points at: they may enter it and manage Tenants, +// and nothing else. It is applied even with no identities, so that +// dropping someone from the list revokes them. +func GrantPlatformAdmins(ctx context.Context, cfg *rest.Config, users, groups []string) error { + kube, err := kubernetes.NewForConfig(cfg) + if err != nil { + return fmt.Errorf("build kubernetes client: %w", err) + } + role := &rbacv1.ClusterRole{ + ObjectMeta: metav1.ObjectMeta{Name: tenancyv1alpha1.GroupName + ":platform-admin"}, + Rules: []rbacv1.PolicyRule{ { - // The operator nudges a URL-less endpoint slice to work - // around kcp not reconciling slices on new bindings. - APIGroups: []string{"apis.kcp.io"}, - Resources: []string{"apiexportendpointslices"}, - Verbs: []string{"patch"}, + Verbs: []string{"access"}, + NonResourceURLs: []string{"/"}, }, { - APIGroups: []string{"apis.kcp.io"}, - Resources: []string{"apiexports/content"}, - Verbs: []string{"*"}, + APIGroups: []string{tenancyv1alpha1.GroupName}, + Resources: []string{"tenants"}, + Verbs: []string{"get", "list", "watch", "create", "update", "patch", "delete"}, }, }, } + return applyRoleAndBinding(ctx, kube, role, users, groups) +} + +// applyRoleAndBinding creates or updates a ClusterRole and a binding of the +// same name holding exactly the given subjects. Updates change only rules, +// subjects and roleRef on the stored object: kcp annotates these objects +// itself, and writing back a copy without its internal.kcp.io annotations +// is rejected as modifying reserved metadata. +func applyRoleAndBinding(ctx context.Context, kube kubernetes.Interface, role *rbacv1.ClusterRole, users, groups []string) error { if _, err := kube.RbacV1().ClusterRoles().Create(ctx, role, metav1.CreateOptions{}); err != nil { if !apierrors.IsAlreadyExists(err) { return err } - if _, err := kube.RbacV1().ClusterRoles().Update(ctx, role, metav1.UpdateOptions{}); err != nil { + if err := retry.RetryOnConflict(retry.DefaultRetry, func() error { + existing, err := kube.RbacV1().ClusterRoles().Get(ctx, role.Name, metav1.GetOptions{}) + if err != nil { + return err + } + existing.Rules = role.Rules + _, err = kube.RbacV1().ClusterRoles().Update(ctx, existing, metav1.UpdateOptions{}) + return err + }); err != nil { return err } } - binding := &rbacv1.ClusterRoleBinding{ - ObjectMeta: metav1.ObjectMeta{Name: tenancyv1alpha1.GroupName + ":server"}, - RoleRef: rbacv1.RoleRef{ - APIGroup: rbacv1.GroupName, - Kind: "ClusterRole", - Name: role.Name, - }, - } + subjects := make([]rbacv1.Subject, 0, len(users)+len(groups)) for _, u := range users { - binding.Subjects = append(binding.Subjects, rbacv1.Subject{ - APIGroup: rbacv1.GroupName, Kind: "User", Name: u, - }) + subjects = append(subjects, rbacv1.Subject{Kind: rbacv1.UserKind, APIGroup: rbacv1.GroupName, Name: u}) } for _, g := range groups { - binding.Subjects = append(binding.Subjects, rbacv1.Subject{ - APIGroup: rbacv1.GroupName, Kind: "Group", Name: g, - }) + subjects = append(subjects, rbacv1.Subject{Kind: rbacv1.GroupKind, APIGroup: rbacv1.GroupName, Name: g}) + } + + binding := &rbacv1.ClusterRoleBinding{ + ObjectMeta: metav1.ObjectMeta{Name: role.Name}, + RoleRef: rbacv1.RoleRef{APIGroup: rbacv1.GroupName, Kind: "ClusterRole", Name: role.Name}, + Subjects: subjects, } if _, err := kube.RbacV1().ClusterRoleBindings().Create(ctx, binding, metav1.CreateOptions{}); err != nil { if !apierrors.IsAlreadyExists(err) { return err } - existing, err := kube.RbacV1().ClusterRoleBindings().Get(ctx, binding.Name, metav1.GetOptions{}) - if err != nil { - return err - } - binding.ResourceVersion = existing.ResourceVersion - if _, err := kube.RbacV1().ClusterRoleBindings().Update(ctx, binding, metav1.UpdateOptions{}); err != nil { + return retry.RetryOnConflict(retry.DefaultRetry, func() error { + existing, err := kube.RbacV1().ClusterRoleBindings().Get(ctx, binding.Name, metav1.GetOptions{}) + if err != nil { + return err + } + existing.Subjects = subjects + existing.RoleRef = binding.RoleRef + _, err = kube.RbacV1().ClusterRoleBindings().Update(ctx, existing, metav1.UpdateOptions{}) return err - } + }) } return nil } +// applyServerIdentity grants the server role to the given identities. +func applyServerIdentity(ctx context.Context, kube kubernetes.Interface, users, groups []string) error { + role := &rbacv1.ClusterRole{ + ObjectMeta: metav1.ObjectMeta{Name: tenancyv1alpha1.GroupName + ":server"}, + Rules: []rbacv1.PolicyRule{ + { + Verbs: []string{"access"}, + NonResourceURLs: []string{"/"}, + }, + { + APIGroups: []string{"apis.kcp.io"}, + Resources: []string{"apiexports", "apiexportendpointslices", "apibindings"}, + Verbs: []string{"get", "list", "watch"}, + }, + { + APIGroups: []string{"apis.kcp.io"}, + Resources: []string{"apiexports/content"}, + Verbs: []string{"*"}, + }, + }, + } + return applyRoleAndBinding(ctx, kube, role, users, groups) +} + // WaitForEndpointSliceURLs reports the virtual workspace URLs one endpoint // slice has published. kcp fills a slice only once a workspace binds the // export, so this is worth calling after binding, not before. An empty @@ -445,14 +537,6 @@ func waitForEndpointSlice(ctx context.Context, dyn dynamic.Interface, sliceName ctx, cancel := context.WithTimeout(ctx, 30*time.Second) defer cancel() - // See NudgeAnnotation: without a write to the slice, the URLs for a - // freshly bound export never appear and this wait is 30 seconds of - // nothing. - patch := fmt.Sprintf(`{"metadata":{"annotations":{%q:%q}}}`, NudgeAnnotation, time.Now().UTC().Format(time.RFC3339)) - if _, err := dyn.Resource(endpointSliceGVR).Patch(ctx, sliceName, types.MergePatchType, []byte(patch), metav1.PatchOptions{}); err != nil { - logger.V(2).Info("could not nudge the endpoint slice", "slice", sliceName, "error", err.Error()) - } - var urls []string err := wait.PollUntilContextCancel(ctx, 2*time.Second, true, func(ctx context.Context) (bool, error) { slice, err := dyn.Resource(endpointSliceGVR).Get(ctx, sliceName, metav1.GetOptions{}) diff --git a/tenancy/pkg/cli/login.go b/tenancy/pkg/cli/login.go index 24e3032..7c3ebb4 100644 --- a/tenancy/pkg/cli/login.go +++ b/tenancy/pkg/cli/login.go @@ -37,6 +37,8 @@ import ( "github.com/spf13/cobra" "golang.org/x/oauth2" + + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/pkg/clicontext" ) // Login obtains an ID token — the JWT every other command presents — and @@ -140,6 +142,13 @@ func anyCachedToken(path string) (string, bool) { return found, found != "" } +// CachedToken returns the token `login` cached in the default location, or +// "" when there is none, it expired, or more than one provider is cached. +func CachedToken() string { + token, _ := anyCachedToken(defaultTokenCachePath()) + return token +} + // oidcEndpoints is the slice of the discovery document this needs. type oidcEndpoints struct { Issuer string `json:"issuer"` @@ -197,17 +206,20 @@ func httpClientFor(caFile string, insecure bool) (*http.Client, error) { func newLoginCommand() *cobra.Command { var ( - issuer string - clientID string - clientSecret string - scopes []string - username string - passwordStdin bool - password string - listen string - caFile string - insecure bool - cachePath string + issuer string + clientID string + clientSecret string + scopes []string + username string + passwordStdin bool + password string + listen string + caFile string + insecure bool + cachePath string + server string + serverCAFile string + serverInsecure bool ) cmd := &cobra.Command{ @@ -305,6 +317,24 @@ a Membership has to name.`, if !token.Expiry.IsZero() { fmt.Printf("expires %s\n", token.Expiry.Local().Format(time.RFC1123)) } + + // Remember the server, so nothing after this has to be told + // where kcp is. Every virtual workspace hangs off it under + // /services/, so one address covers them all. + if server != "" { + if err := clicontext.Update(func(c *clicontext.Context) { + c.Server = strings.TrimSuffix(server, "/") + c.CertificateAuthority = serverCAFile + c.Insecure = serverInsecure + }); err != nil { + return err + } + fmt.Printf("server %s saved in %s\n", strings.TrimSuffix(server, "/"), clicontext.Where()) + } else if clicontext.Load().Server == "" { + fmt.Fprintf(os.Stderr, + "\nno server known yet: pass --url https://:8443 to store one, "+ + "or give each command --url\n") + } return nil }, } @@ -329,6 +359,14 @@ a Membership has to name.`, "Do not verify the issuer's certificate. For a local provider only.") cmd.Flags().StringVar(&cachePath, "token-cache", defaultTokenCachePath(), "File the token is cached in.") + cmd.Flags().StringVar(&server, "url", "", + "Base URL of the kcp front-proxy, e.g. https://kcp.example.com:8443. Remembered in "+ + clicontext.Where()+" so later commands need no --url: every virtual workspace "+ + "answers on it under /services/.") + cmd.Flags().StringVar(&serverCAFile, "server-certificate-authority", "", + "CA bundle that verifies the server's certificate. Remembered with --url.") + cmd.Flags().BoolVar(&serverInsecure, "server-insecure-skip-tls-verify", false, + "Do not verify the server's certificate. For local testing only. Remembered with --url.") return cmd } diff --git a/tenancy/pkg/cli/membership.go b/tenancy/pkg/cli/membership.go index 34e55ea..650dc6f 100644 --- a/tenancy/pkg/cli/membership.go +++ b/tenancy/pkg/cli/membership.go @@ -17,6 +17,7 @@ limitations under the License. package cli import ( + "context" "fmt" "github.com/spf13/cobra" @@ -69,50 +70,7 @@ identity provider's job, and this only records what that identity may do.`, if asGroup { kind = tenancyv1alpha1.SubjectKindGroup } - subject := args[0] - name := membershipName(subject, tenant, project) - - membership := &tenancyv1alpha1.Membership{ - ObjectMeta: metav1.ObjectMeta{Name: name}, - Spec: tenancyv1alpha1.MembershipSpec{ - Subject: tenancyv1alpha1.Subject{Kind: kind, Name: subject}, - Role: tenancyv1alpha1.Role(role), - Tenant: tenant, - Project: project, - }, - } - - err = c.Create(cmd.Context(), membership) - if apierrors.IsAlreadyExists(err) { - // The name is derived from (subject, tenant, project), so - // an existing object is the same grant: re-granting is a - // role change, not a duplicate. - var existing tenancyv1alpha1.Membership - if err := c.Get(cmd.Context(), client.ObjectKey{Name: name}, &existing); err != nil { - return fmt.Errorf("get existing membership: %w", err) - } - if existing.Spec.Role == tenancyv1alpha1.Role(role) { - fmt.Printf("membership/%s already grants %s\n", name, role) - return nil - } - previous := existing.Spec.Role - existing.Spec.Role = tenancyv1alpha1.Role(role) - if err := c.Update(cmd.Context(), &existing); err != nil { - return fmt.Errorf("update membership: %w", err) - } - fmt.Printf("membership/%s changed from %s to %s\n", name, previous, role) - return nil - } - if err != nil { - return fmt.Errorf("create membership: %w", err) - } - - scope := "every project of tenant " + tenant - if project != "" { - scope = "project " + project + " of tenant " + tenant - } - fmt.Printf("membership/%s created: %s %q is %s in %s\n", name, kind, subject, role, scope) - return nil + return upsertMembership(cmd.Context(), c, kind, args[0], tenancyv1alpha1.Role(role), tenant, project) }, } o.addFlags(cmd) @@ -132,6 +90,7 @@ func newRevokeCommand() *cobra.Command { tenant string project string list bool + asGroup bool ) cmd := &cobra.Command{ @@ -172,7 +131,7 @@ With --list it prints every grant instead of removing one.`, return nil } - name := membershipName(args[0], tenant, project) + name := membershipName(subjectKind(asGroup), args[0], tenant, project) membership := &tenancyv1alpha1.Membership{ObjectMeta: metav1.ObjectMeta{Name: name}} if err := c.Delete(cmd.Context(), membership); err != nil { if apierrors.IsNotFound(err) { @@ -188,6 +147,54 @@ With --list it prints every grant instead of removing one.`, cmd.Flags().StringVar(&tenant, "tenant", "", "Tenant whose grants to list or revoke (required).") cmd.Flags().StringVar(&project, "project", "", "Project of the grant, if it was project-scoped.") cmd.Flags().BoolVar(&list, "list", false, "List grants instead of revoking one.") + cmd.Flags().BoolVar(&asGroup, "group", false, "Treat SUBJECT as a group rather than a username.") return cmd } + +// upsertMembership creates a grant, or — because the name is derived from +// (kind, subject, tenant, project), so an existing object IS the same grant — +// updates its role in place. Re-granting is a role change, never a +// duplicate, which is what makes grant and seed idempotent. +func upsertMembership(ctx context.Context, c client.Client, kind tenancyv1alpha1.SubjectKind, subject string, role tenancyv1alpha1.Role, tenant, project string) error { + name := membershipName(kind, subject, tenant, project) + + membership := &tenancyv1alpha1.Membership{ + ObjectMeta: metav1.ObjectMeta{Name: name}, + Spec: tenancyv1alpha1.MembershipSpec{ + Subject: tenancyv1alpha1.Subject{Kind: kind, Name: subject}, + Role: role, + Tenant: tenant, + Project: project, + }, + } + + err := c.Create(ctx, membership) + if apierrors.IsAlreadyExists(err) { + var existing tenancyv1alpha1.Membership + if err := c.Get(ctx, client.ObjectKey{Name: name}, &existing); err != nil { + return fmt.Errorf("get existing membership: %w", err) + } + if existing.Spec.Role == role { + fmt.Printf("membership/%s already grants %s\n", name, role) + return nil + } + previous := existing.Spec.Role + existing.Spec.Role = role + if err := c.Update(ctx, &existing); err != nil { + return fmt.Errorf("update membership: %w", err) + } + fmt.Printf("membership/%s changed from %s to %s\n", name, previous, role) + return nil + } + if err != nil { + return fmt.Errorf("create membership: %w", err) + } + + scope := "every project of tenant " + tenant + if project != "" { + scope = "project " + project + " of tenant " + tenant + } + fmt.Printf("membership/%s created: %s %q is %s in %s\n", name, kind, subject, role, scope) + return nil +} diff --git a/tenancy/pkg/cli/memberships.go b/tenancy/pkg/cli/memberships.go new file mode 100644 index 0000000..156a7f7 --- /dev/null +++ b/tenancy/pkg/cli/memberships.go @@ -0,0 +1,214 @@ +/* +Copyright 2026 The kcp Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package cli + +import ( + "fmt" + + "github.com/spf13/cobra" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + tenancyv1alpha1 "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1" +) + +// NewMembershipCommand groups the grant lifecycle under one noun: +// `membership` lists, `membership add` grants, `membership remove` +// revokes. +// +// Unlike the user-facing commands, these need a kubeconfig for kcp: a +// Membership lives in its tenant's workspace, which is the record store +// no member can enter, so managing access is an administrator's job by +// construction rather than by a check. +func NewMembershipCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "membership", + Aliases: []string{"memberships"}, + Short: "List, grant and revoke access to a tenant or project", + Long: `A Membership records what an identity may do, and the operator +materializes it as RBAC in the tenant's project workspaces. + +There is no user registry to enrol anyone into: issuing credentials is +the identity provider's job, and a Membership only names the identity it +already issues. + +Run without a subcommand it lists the grants in the tenant.`, + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + return cmd.Help() + }, + } + + cmd.AddCommand( + newMembershipListCommand(), + newMembershipAddCommand(), + newMembershipRemoveCommand(), + ) + return cmd +} + +// tenantFlag adds --tenant, defaulting to whatever `use` selected, so the +// admin commands compose with the user-facing ones. +func tenantFlag(cmd *cobra.Command, tenant *string) { + cmd.Flags().StringVar(tenant, "tenant", "", + "Tenant to act on. Defaults to the one `use` selected.") +} + +func newMembershipListCommand() *cobra.Command { + o := &adminOptions{} + var tenant string + + cmd := &cobra.Command{ + Use: "list", + Aliases: []string{"ls"}, + Short: "List the grants in a tenant", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + selected, err := selectionFor(tenant, "") + if err != nil { + return err + } + c, err := o.tenantClient(cmd.Context(), selected.Tenant) + if err != nil { + return err + } + var memberships tenancyv1alpha1.MembershipList + if err := c.List(cmd.Context(), &memberships); err != nil { + return fmt.Errorf("list memberships: %w", err) + } + if len(memberships.Items) == 0 { + fmt.Printf("No grants in tenant %s.\n", selected.Tenant) + return nil + } + rows := make([][]string, 0, len(memberships.Items)) + for _, m := range memberships.Items { + rows = append(rows, []string{ + m.Name, string(m.Spec.Subject.Kind), m.Spec.Subject.Name, + string(m.Spec.Role), dash(m.Spec.Project), + string(dashPhase(m.Status.Phase)), + }) + } + table([]string{"NAME", "KIND", "SUBJECT", "ROLE", "PROJECT", "PHASE"}, rows) + return nil + }, + } + o.addFlags(cmd) + tenantFlag(cmd, &tenant) + return cmd +} + +func newMembershipAddCommand() *cobra.Command { + o := &adminOptions{} + var ( + role string + tenant string + project string + asGroup bool + ) + + cmd := &cobra.Command{ + Use: "add SUBJECT", + Aliases: []string{"grant"}, + Short: "Grant a user or group a role", + Long: `Grant access by creating a Membership. + +SUBJECT is matched verbatim against the identity kcp authenticates: the +CommonName of a client certificate, or the username an OIDC token maps +to. With --group it is matched against the caller's groups instead. + +Without --project the grant is tenant-wide and reaches every project, +including ones created later. Re-running with a different --role changes +the grant in place rather than adding a second one.`, + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + switch tenancyv1alpha1.Role(role) { + case tenancyv1alpha1.RoleView, tenancyv1alpha1.RoleEdit, tenancyv1alpha1.RoleAdmin: + default: + return fmt.Errorf("--role must be one of view, edit, admin (got %q)", role) + } + selected, err := selectionFor(tenant, project) + if err != nil { + return err + } + c, err := o.tenantClient(cmd.Context(), selected.Tenant) + if err != nil { + return err + } + kind := tenancyv1alpha1.SubjectKindUser + if asGroup { + kind = tenancyv1alpha1.SubjectKindGroup + } + return upsertMembership(cmd.Context(), c, kind, args[0], + tenancyv1alpha1.Role(role), selected.Tenant, selected.Project) + }, + } + o.addFlags(cmd) + tenantFlag(cmd, &tenant) + cmd.Flags().StringVar(&role, "role", string(tenancyv1alpha1.RoleView), "view, edit or admin.") + cmd.Flags().StringVar(&project, "project", "", + "Narrow the grant to one project. Defaults to the one `use` selected; "+ + "pass --project= to grant tenant-wide.") + cmd.Flags().BoolVar(&asGroup, "group", false, "Treat SUBJECT as a group rather than a username.") + return cmd +} + +func newMembershipRemoveCommand() *cobra.Command { + o := &adminOptions{} + var ( + tenant string + project string + asGroup bool + ) + + cmd := &cobra.Command{ + Use: "remove SUBJECT", + Aliases: []string{"revoke", "rm"}, + Short: "Revoke a grant", + Long: `Delete the Membership, and with it the RBAC the operator +materialized in the target workspaces. + +--project has to match how the grant was made: a tenant-wide grant and a +project-scoped one are different objects.`, + Args: cobra.ExactArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + selected, err := selectionFor(tenant, project) + if err != nil { + return err + } + c, err := o.tenantClient(cmd.Context(), selected.Tenant) + if err != nil { + return err + } + name := membershipName(subjectKind(asGroup), args[0], selected.Tenant, selected.Project) + membership := &tenancyv1alpha1.Membership{ObjectMeta: metav1.ObjectMeta{Name: name}} + if err := c.Delete(cmd.Context(), membership); err != nil { + if apierrors.IsNotFound(err) { + return fmt.Errorf("no such grant: %s (try `membership list`)", name) + } + return fmt.Errorf("delete membership: %w", err) + } + fmt.Printf("membership/%s revoked\n", name) + return nil + }, + } + o.addFlags(cmd) + tenantFlag(cmd, &tenant) + cmd.Flags().StringVar(&project, "project", "", "Project of the grant, if it was project-scoped.") + cmd.Flags().BoolVar(&asGroup, "group", false, "Treat SUBJECT as a group rather than a username.") + return cmd +} diff --git a/tenancy/pkg/cli/org.go b/tenancy/pkg/cli/org.go index 088b712..045f1af 100644 --- a/tenancy/pkg/cli/org.go +++ b/tenancy/pkg/cli/org.go @@ -99,7 +99,10 @@ them.`, if err != nil { return fmt.Errorf("resolve workspace path %s: %w", orgPath, err) } - if err := bootstrap.BindStore(cmd.Context(), orgCfg, result); err != nil { + // No server identities here: `org bootstrap` makes an additional + // platform workspace, and which servers may locate it is init's + // business rather than this command's. + if err := bootstrap.BindStore(cmd.Context(), orgCfg, result, bootstrap.Options{}); err != nil { return fmt.Errorf("bind the Tenant API into %s: %w", orgPath, err) } diff --git a/tenancy/pkg/cli/review.go b/tenancy/pkg/cli/review.go index a80a868..321fd3f 100644 --- a/tenancy/pkg/cli/review.go +++ b/tenancy/pkg/cli/review.go @@ -53,15 +53,19 @@ type userOptions struct { } func (o *userOptions) addFlags(cmd *cobra.Command) { - cmd.Flags().StringVar(&o.url, "url", os.Getenv("TENANCY_VW_URL"), - "Base URL of the tenancy virtual workspace, e.g. https://kcp.example.com. "+ - "Defaults to $TENANCY_VW_URL.") + // The address is learned once, by `login --url`, and kept in the + // shared context; $TENANCY_VW_URL still wins for a one-off, and an + // explicit flag wins over both. + cmd.Flags().StringVar(&o.url, "url", envOr("TENANCY_VW_URL", storedServiceURL("tenancy")), + "Base URL of the tenancy virtual workspace. Defaults to the server `login --url` "+ + "stored, or $TENANCY_VW_URL.") cmd.Flags().StringVar(&o.certFile, "client-cert", "", "Client certificate to authenticate with.") cmd.Flags().StringVar(&o.keyFile, "client-key", "", "Key for --client-cert.") cmd.Flags().StringVar(&o.tokenFile, "token-file", "", "File holding a bearer token to authenticate with.") - cmd.Flags().StringVar(&o.caFile, "certificate-authority", "", + storedCA, storedInsecure := storedTLS() + cmd.Flags().StringVar(&o.caFile, "certificate-authority", storedCA, "CA bundle used to verify the virtual workspace's serving certificate.") - cmd.Flags().BoolVar(&o.insecure, "insecure-skip-tls-verify", false, + cmd.Flags().BoolVar(&o.insecure, "insecure-skip-tls-verify", storedInsecure, "Do not verify the virtual workspace's serving certificate. For local testing only.") cmd.Flags().StringVar(&o.kubeconfig, "kubeconfig", "", "Take credentials from this kubeconfig's current context instead of --client-cert/--token-file.") @@ -219,13 +223,19 @@ func newKubeconfigCommand() *cobra.Command { cmd := &cobra.Command{ Use: "kubeconfig", - Short: "Write a kubeconfig with a context per tenant and project you can reach", + Short: "Write a kubeconfig with a context per project you can reach", Long: `Ask the virtual workspace what you can reach and turn the answer -into a kubeconfig: one context per tenant and per project, each pointing at -that workspace's own URL, all sharing your credential. +into a kubeconfig: one context per project, each pointing at that +workspace's own URL, all sharing your credential. + +Projects only, because those are the workspaces a member can work in. A +tenant workspace is the record store the tenancy system keeps its own +objects in — a Membership materializes RBAC in that tenant's projects and +never in the tenant itself — so no member can enter it, and a context for +it would only ever answer Forbidden. This is the closest thing to a login: after running it, "kubectl ---context=" talks to that tenant's workspace directly.`, +--context=-" talks to that project's workspace directly.`, Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { review, err := o.review(cmd.Context()) @@ -271,15 +281,16 @@ This is the closest thing to a login: after running it, "kubectl kubeconfig.Contexts[name] = ctx } + // Projects only: the tenant workspace is a record store no + // member can enter, so a context for it would be a trap. for _, t := range review.Status.Tenants { - add(t.Name, t.Endpoint) for _, p := range t.Projects { add(t.Name+"-"+p.Name, p.Endpoint) } } if len(kubeconfig.Contexts) == 0 { - return fmt.Errorf("no workspace in the answer carried an endpoint URL; " + - "is the virtual workspace started with --endpoint-base?") + return fmt.Errorf("you are a member of no project yet, so there is nothing to write "+ + "(`%s whoami` shows what you can reach)", cmd.Root().Name()) } if context_ != "" { @@ -288,7 +299,7 @@ This is the closest thing to a login: after running it, "kubectl } kubeconfig.CurrentContext = context_ } else { - kubeconfig.CurrentContext = review.Status.Tenants[0].Name + kubeconfig.CurrentContext = defaultContext(review.Status.Tenants, kubeconfig.Contexts) } if output == "" || output == "-" { @@ -302,8 +313,12 @@ This is the closest thing to a login: after running it, "kubectl if err := clientcmd.WriteToFile(*kubeconfig, output); err != nil { return fmt.Errorf("write %s: %w", output, err) } - fmt.Printf("wrote %s with %d contexts (current: %s)\n", - output, len(kubeconfig.Contexts), kubeconfig.CurrentContext) + plural := "s" + if len(kubeconfig.Contexts) == 1 { + plural = "" + } + fmt.Printf("wrote %s with %d project context%s (current: %s)\n", + output, len(kubeconfig.Contexts), plural, kubeconfig.CurrentContext) return nil }, } @@ -336,3 +351,30 @@ func hint(err error) string { return "" } } + +// defaultContext picks which project context a freshly written kubeconfig +// starts in: the first one the caller actually holds a role in. +// +// A project can be listed with no roles of its own — a tenant-wide grant +// is reported on the tenant, not repeated on every project — so "no +// roles" is not "no access" and such a context is still worth keeping. +// Preferring one with roles just makes the default the least surprising. +func defaultContext(tenants []tenancyv1alpha1.TenantClaim, contexts map[string]*clientcmdapi.Context) string { + var fallback string + + for _, t := range tenants { + for _, p := range t.Projects { + name := t.Name + "-" + p.Name + if _, ok := contexts[name]; !ok { + continue // no endpoint, so no context was written for it + } + if len(p.Roles) > 0 { + return name + } + if fallback == "" { + fallback = name + } + } + } + return fallback +} diff --git a/tenancy/pkg/cli/review_test.go b/tenancy/pkg/cli/review_test.go new file mode 100644 index 0000000..e0fb97d --- /dev/null +++ b/tenancy/pkg/cli/review_test.go @@ -0,0 +1,106 @@ +/* +Copyright 2026 The kcp Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package cli + +import ( + "testing" + + clientcmdapi "k8s.io/client-go/tools/clientcmd/api" + + tenancyv1alpha1 "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1" +) + +func TestDefaultContext(t *testing.T) { + // Only projects get contexts at all — a tenant workspace is a record + // store no member can enter — so this only ever chooses between + // projects, preferring one the caller holds a role in. + cases := map[string]struct { + tenants []tenancyv1alpha1.TenantClaim + contexts []string + want string + }{ + "the only project is the default": { + tenants: []tenancyv1alpha1.TenantClaim{{ + Name: "acme", + Roles: []string{"admin"}, + Projects: []tenancyv1alpha1.ProjectClaim{ + {Name: "web", Roles: []string{"admin"}}, + }, + }}, + contexts: []string{"acme-web"}, + want: "acme-web", + }, + "a project with roles wins over one without": { + tenants: []tenancyv1alpha1.TenantClaim{{ + Name: "acme", + Projects: []tenancyv1alpha1.ProjectClaim{ + {Name: "attic"}, + {Name: "web", Roles: []string{"edit"}}, + }, + }}, + contexts: []string{"acme-attic", "acme-web"}, + want: "acme-web", + }, + "a project reached only by a tenant-wide grant still counts": { + tenants: []tenancyv1alpha1.TenantClaim{{ + Name: "acme", + Roles: []string{"admin"}, // fans out; not repeated per project + Projects: []tenancyv1alpha1.ProjectClaim{ + {Name: "web"}, + }, + }}, + contexts: []string{"acme-web"}, + want: "acme-web", + }, + "a project whose workspace has no endpoint is skipped": { + tenants: []tenancyv1alpha1.TenantClaim{{ + Name: "acme", + Projects: []tenancyv1alpha1.ProjectClaim{ + {Name: "pending", Roles: []string{"admin"}}, + {Name: "web", Roles: []string{"view"}}, + }, + }}, + // "pending" is still provisioning, so no context was written. + contexts: []string{"acme-web"}, + want: "acme-web", + }, + "the first project of the first tenant, across tenants": { + tenants: []tenancyv1alpha1.TenantClaim{ + {Name: "acme", Projects: []tenancyv1alpha1.ProjectClaim{ + {Name: "web", Roles: []string{"view"}}, + }}, + {Name: "globex", Projects: []tenancyv1alpha1.ProjectClaim{ + {Name: "api", Roles: []string{"admin"}}, + }}, + }, + contexts: []string{"acme-web", "globex-api"}, + want: "acme-web", + }, + } + + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + contexts := map[string]*clientcmdapi.Context{} + for _, c := range tc.contexts { + contexts[c] = clientcmdapi.NewContext() + } + if got := defaultContext(tc.tenants, contexts); got != tc.want { + t.Errorf("defaultContext = %q, want %q", got, tc.want) + } + }) + } +} diff --git a/tenancy/pkg/cli/root.go b/tenancy/pkg/cli/root.go index 176ff10..8d13675 100644 --- a/tenancy/pkg/cli/root.go +++ b/tenancy/pkg/cli/root.go @@ -54,10 +54,13 @@ func init() { utilruntime.Must(tenancyv1alpha1.AddToScheme(scheme)) } -// Execute runs tenancyctl. -func Execute() error { +// New builds the tenancy CLI command tree under the given name — +// "tenancyctl" for the standalone binary, "tenancy" when mounted as a +// subcommand of the repo-wide CLI. It registers no logging flags; the +// binary that owns the process does that once, at its own root. +func New(use string) *cobra.Command { root := &cobra.Command{ - Use: "tenancyctl", + Use: use, Short: "Manage kcp tenants, projects and access", Long: `tenancyctl is the client for the kcp tenancy model. @@ -70,10 +73,6 @@ with no kubeconfig for kcp itself and no credential flags.`, SilenceUsage: true, } - klogFlags := goflag.NewFlagSet("klog", goflag.ContinueOnError) - klog.InitFlags(klogFlags) - root.PersistentFlags().AddGoFlagSet(klogFlags) - root.AddCommand( newLoginCommand(), newLogoutCommand(), @@ -84,8 +83,20 @@ with no kubeconfig for kcp itself and no credential flags.`, newWhoAmICommand(), newKubeconfigCommand(), newOrgCommand(), + newSeedCommand(), ) + return root +} + +// Execute runs the standalone tenancyctl binary. +func Execute() error { + root := New("tenancyctl") + + klogFlags := goflag.NewFlagSet("klog", goflag.ContinueOnError) + klog.InitFlags(klogFlags) + root.PersistentFlags().AddGoFlagSet(klogFlags) + return root.Execute() } diff --git a/tenancy/pkg/cli/seed.go b/tenancy/pkg/cli/seed.go new file mode 100644 index 0000000..d68544a --- /dev/null +++ b/tenancy/pkg/cli/seed.go @@ -0,0 +1,164 @@ +/* +Copyright 2026 The kcp Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package cli + +import ( + "fmt" + + "github.com/spf13/cobra" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + tenancyv1alpha1 "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1" +) + +// NewSeedCommand exposes seed for the tenancy binary, so a development +// environment (Tilt, a demo) can converge on baseline data with the +// component's own tooling and nothing else. +func NewSeedCommand() *cobra.Command { return newSeedCommand() } + +// newSeedCommand builds `seed`: one idempotent call that converges on a +// tenant, optionally a project, and a set of grants. Everything it does +// is if-not-present or an in-place role change, so calling it again — on +// every environment start, say — is always safe. The identities are +// arguments, not defaults: which users exist is the environment's +// business, not the component's. +func newSeedCommand() *cobra.Command { + o := &adminOptions{} + var ( + tenant string + displayName string + project string + admins []string + views []string + wait_ bool + ) + + cmd := &cobra.Command{ + Use: "seed", + Short: "Idempotently converge on a tenant, a project and grants", + Long: `Seed baseline tenancy data for an environment, idempotently. + +Creates the tenant and project when missing (and waits for their +workspaces), then upserts the grants: --admin subjects become tenant-wide +admins, --view subjects get view on the project (tenant-wide when no +project is given). Safe to run on every environment start.`, + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + if tenant == "" { + return fmt.Errorf("--tenant is required") + } + ctx := cmd.Context() + + platform, err := o.client() + if err != nil { + return err + } + if displayName == "" { + displayName = tenant + } + t := &tenancyv1alpha1.Tenant{ + ObjectMeta: metav1.ObjectMeta{Name: tenant}, + Spec: tenancyv1alpha1.TenantSpec{ + DisplayName: displayName, + // The first --admin also seeds the tenant, so the + // grant exists the moment the workspace does rather + // than after the projects below it. + FirstAdmin: firstOf(admins), + }, + } + switch err := platform.Create(ctx, t); { + case err == nil: + fmt.Printf("tenant/%s created in %s\n", tenant, o.workspace) + case apierrors.IsAlreadyExists(err): + fmt.Printf("tenant/%s already exists in %s\n", tenant, o.workspace) + default: + return fmt.Errorf("create tenant: %w", err) + } + if wait_ { + if err := waitForTenant(ctx, platform, tenant); err != nil { + return err + } + } + + tc, err := o.tenantClient(ctx, tenant) + if err != nil { + return err + } + + if project != "" { + p := &tenancyv1alpha1.Project{ + ObjectMeta: metav1.ObjectMeta{Name: project}, + Spec: tenancyv1alpha1.ProjectSpec{ + Tenant: tenant, + DisplayName: project, + }, + } + switch err := tc.Create(ctx, p); { + case err == nil: + fmt.Printf("project/%s created in tenant %s\n", project, tenant) + case apierrors.IsAlreadyExists(err): + fmt.Printf("project/%s already exists in tenant %s\n", project, tenant) + default: + return fmt.Errorf("create project: %w", err) + } + if wait_ { + if err := waitForProject(ctx, tc, project); err != nil { + return err + } + } + } + + for _, subject := range admins { + if err := upsertMembership(ctx, tc, tenancyv1alpha1.SubjectKindUser, subject, + tenancyv1alpha1.RoleAdmin, tenant, ""); err != nil { + return err + } + } + for _, subject := range views { + if err := upsertMembership(ctx, tc, tenancyv1alpha1.SubjectKindUser, subject, + tenancyv1alpha1.RoleView, tenant, project); err != nil { + return err + } + } + + fmt.Printf("seeded tenant %s\n", tenant) + return nil + }, + } + o.addFlags(cmd) + cmd.Flags().StringVar(&tenant, "tenant", "", "Tenant to converge on (required).") + cmd.Flags().StringVar(&displayName, "display-name", "", + "Human name of the tenant; seeds the workspace name. Defaults to the tenant name.") + cmd.Flags().StringVar(&project, "project", "", "Project to converge on inside the tenant.") + cmd.Flags().StringArrayVar(&admins, "admin", nil, + "Subject to grant tenant-wide admin (repeatable).") + cmd.Flags().StringArrayVar(&views, "view", nil, + "Subject to grant view on the project, or tenant-wide without --project (repeatable).") + cmd.Flags().BoolVar(&wait_, "wait", true, "Wait until the workspaces are ready.") + + return cmd +} + +// firstOf returns the first element, or "". +func firstOf(ss []string) string { + if len(ss) == 0 { + return "" + } + return ss[0] +} diff --git a/tenancy/pkg/cli/selection.go b/tenancy/pkg/cli/selection.go new file mode 100644 index 0000000..19a86ad --- /dev/null +++ b/tenancy/pkg/cli/selection.go @@ -0,0 +1,85 @@ +/* +Copyright 2026 The kcp Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package cli + +import ( + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/pkg/clicontext" +) + +// Selection is the tenant and project the user is currently working in: +// what `use` picks, and what every command that needs a workspace falls +// back to when no flag names one. +// +// It is a view onto the shared CLI context in ~/.kube, which also holds +// the server `login` learned — one file, so a command never has to be +// told twice where anything is. +type Selection struct { + Tenant string + Project string + // URL is the project's workspace, as the virtual workspace reported + // it, so commands that only need somewhere to talk to do not have to + // ask again. + URL string +} + +// String renders the selection the way the CLI prints it. +func (s Selection) String() string { + if s.Project == "" { + return s.Tenant + } + return s.Tenant + "/" + s.Project +} + +// Empty reports whether nothing has been selected yet. +func (s Selection) Empty() bool { return s.Tenant == "" } + +// CurrentSelection reads the selection from the shared context. +func CurrentSelection() Selection { + c := clicontext.Load() + return Selection{Tenant: c.Tenant, Project: c.Project, URL: c.WorkspaceURL} +} + +// WriteSelection stores the selection, leaving the rest of the context — +// the server, the TLS settings — as it was. +func WriteSelection(s Selection) error { + return clicontext.Update(func(c *clicontext.Context) { + c.Tenant, c.Project, c.WorkspaceURL = s.Tenant, s.Project, s.URL + }) +} + +// ClearSelection forgets where the user was working, but keeps them +// logged in and keeps the server: they chose a project, not a cluster. +func ClearSelection() error { + return clicontext.Update(func(c *clicontext.Context) { + c.Tenant, c.Project, c.WorkspaceURL = "", "", "" + }) +} + +// storedServiceURL is where a virtual workspace answers on the server +// `login --url` stored, or "" when no server is known yet — in which case +// the flag is required and says so. +func storedServiceURL(name string) string { + return clicontext.Load().ServiceURL(name) +} + +// storedTLS reports the TLS settings saved with the server, so a +// development setup does not need --insecure-skip-tls-verify on every +// command. +func storedTLS() (caFile string, insecure bool) { + c := clicontext.Load() + return c.CertificateAuthority, c.Insecure +} diff --git a/tenancy/pkg/cli/tenant.go b/tenancy/pkg/cli/tenant.go index 79e00a8..df164fd 100644 --- a/tenancy/pkg/cli/tenant.go +++ b/tenancy/pkg/cli/tenant.go @@ -44,6 +44,7 @@ func newTenantCommand() *cobra.Command { var ( displayName string description string + firstAdmin string wait_ bool ) @@ -66,6 +67,7 @@ func newTenantCommand() *cobra.Command { Spec: tenancyv1alpha1.TenantSpec{ DisplayName: displayName, Description: description, + FirstAdmin: firstAdmin, }, } if err := c.Create(cmd.Context(), tenant); err != nil { @@ -85,6 +87,9 @@ func newTenantCommand() *cobra.Command { create.Flags().StringVar(&displayName, "display-name", "", "Human name of the tenant; seeds the workspace name. Defaults to NAME.") create.Flags().StringVar(&description, "description", "", "Free text for humans.") + create.Flags().StringVar(&firstAdmin, "first-admin", "", + "Identity to grant admin on this tenant once its workspace exists. Saves a second "+ + "`membership add`, and is what makes the tenant usable by anyone but you.") create.Flags().BoolVar(&wait_, "wait", true, "Wait until the tenant's workspace is ready.") list := &cobra.Command{ @@ -178,11 +183,16 @@ func dashPhase(p tenancyv1alpha1.Phase) tenancyv1alpha1.Phase { } // membershipName derives a deterministic object name for a grant, so that -// granting the same access twice is a no-op rather than a duplicate. -func membershipName(subject, tenant, project string) string { - parts := naming.Slugify(subject) + "-" + naming.Slugify(tenant) - if project != "" { - parts += "-" + naming.Slugify(project) +// granting the same access twice is a no-op rather than a duplicate. The +// virtual workspace derives the same name for grants made through it, so +// the two paths cannot produce competing objects for one grant. +func membershipName(kind tenancyv1alpha1.SubjectKind, subject, tenant, project string) string { + return naming.MembershipName(string(kind), subject, tenant, project) +} + +func subjectKind(asGroup bool) tenancyv1alpha1.SubjectKind { + if asGroup { + return tenancyv1alpha1.SubjectKindGroup } - return parts + return tenancyv1alpha1.SubjectKindUser } diff --git a/tenancy/pkg/cli/user.go b/tenancy/pkg/cli/user.go new file mode 100644 index 0000000..1beb4aa --- /dev/null +++ b/tenancy/pkg/cli/user.go @@ -0,0 +1,324 @@ +/* +Copyright 2026 The kcp Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package cli + +import ( + "bufio" + "fmt" + "os" + "strconv" + "strings" + + "github.com/spf13/cobra" + + tenancyv1alpha1 "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1" +) + +// The user-facing half of the CLI: everything here answers from the +// caller's own credential through the virtual workspace, with no +// kubeconfig for kcp and no administrative rights. These are the +// commands mounted at the root of the repo-wide CLI. + +// NewLoginCommand obtains a token from the identity provider and caches it. +func NewLoginCommand() *cobra.Command { return newLoginCommand() } + +// NewLogoutCommand forgets the cached token. +func NewLogoutCommand() *cobra.Command { return newLogoutCommand() } + +// NewWhoAmICommand shows the tenants and projects the caller can reach. +func NewWhoAmICommand() *cobra.Command { return newWhoAmICommand() } + +// NewKubeconfigCommand writes a kubeconfig for the caller's projects. +func NewKubeconfigCommand() *cobra.Command { return newKubeconfigCommand() } + +// NewAdminCommand groups everything that writes to kcp with a kubeconfig +// rather than answering from the caller's own credential: creating +// tenants and projects, bootstrapping an organization, seeding an +// environment. Whoever runs the platform uses these; a tenant does not. +func NewAdminCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "admin", + Short: "Create tenants and projects, bootstrap and seed (needs a kubeconfig)", + Long: `The platform side of the tenancy model. + +These commands write to kcp directly — they need a kubeconfig with rights +in the workspace they touch, which is exactly what a tenant does not +have. The user-facing commands at the root need no kubeconfig at all.`, + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { return cmd.Help() }, + } + cmd.AddCommand( + newTenantCommand(), + newProjectCommand(), + newOrgCommand(), + newSeedCommand(), + ) + return cmd +} + +// NewTenantsCommand lists the tenants the caller is a member of. +func NewTenantsCommand() *cobra.Command { + o := &userOptions{} + cmd := &cobra.Command{ + Use: "tenants", + Aliases: []string{"tenant"}, + Short: "List the tenants you can reach", + Long: `List the tenants the calling identity is a member of, as the +tenancy virtual workspace reports them. + +This is the user's view: it needs no kubeconfig for kcp, only your own +credential. To create a tenant, which is an administrator's job, see +"admin tenant create".`, + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + review, err := o.review(cmd.Context()) + if err != nil { + return err + } + if len(review.Status.Tenants) == 0 { + fmt.Println("You are not a member of any tenant.") + return nil + } + current := CurrentSelection() + rows := make([][]string, 0, len(review.Status.Tenants)) + for _, t := range review.Status.Tenants { + rows = append(rows, []string{ + marker(current.Tenant == t.Name), t.Name, dash(t.DisplayName), + dash(strings.Join(t.Roles, ",")), strconv.Itoa(len(t.Projects)), + }) + } + table([]string{"", "TENANT", "DISPLAY NAME", "ROLES", "PROJECTS"}, rows) + return nil + }, + } + o.addFlags(cmd) + return cmd +} + +// NewProjectsCommand lists the projects the caller can reach. +func NewProjectsCommand() *cobra.Command { + o := &userOptions{} + var tenant string + + cmd := &cobra.Command{ + Use: "projects", + Aliases: []string{"project"}, + Short: "List the projects you can reach", + Long: `List the projects the calling identity can reach, across every +tenant, or only within one with --tenant. + +A project is where work happens: it is the workspace your kubeconfig +context points at.`, + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + review, err := o.review(cmd.Context()) + if err != nil { + return err + } + current := CurrentSelection() + rows := [][]string{} + for _, t := range review.Status.Tenants { + if tenant != "" && t.Name != tenant { + continue + } + for _, p := range t.Projects { + selected := current.Tenant == t.Name && current.Project == p.Name + rows = append(rows, []string{ + marker(selected), t.Name, p.Name, dash(p.DisplayName), + dash(strings.Join(rolesFor(t, p), ",")), dash(p.Endpoint), + }) + } + } + if len(rows) == 0 { + if tenant != "" { + fmt.Printf("No projects you can reach in tenant %q.\n", tenant) + } else { + fmt.Println("You can reach no projects.") + } + return nil + } + table([]string{"", "TENANT", "PROJECT", "DISPLAY NAME", "ROLES", "ENDPOINT"}, rows) + return nil + }, + } + o.addFlags(cmd) + cmd.Flags().StringVar(&tenant, "tenant", "", "Only show projects of this tenant.") + return cmd +} + +// NewUseCommand selects the tenant and project later commands default to. +func NewUseCommand() *cobra.Command { + o := &userOptions{} + var clear bool + + cmd := &cobra.Command{ + Use: "use [TENANT[/PROJECT]]", + Short: "Choose the tenant and project to work in", + Long: `Pick the project later commands act on, so they do not each need +--tenant and --project. + +Given no argument it lists what you can reach and asks; given +TENANT/PROJECT it selects that directly. The choice is remembered in +` + "`" + `current.json` + "`" + ` next to the token cache, and "whoami" or "projects" shows +it marked with *. + +Selecting nothing authorizes nothing: it is a convenience, and kcp still +decides what you may do in the workspace.`, + Args: cobra.MaximumNArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + if clear { + if err := ClearSelection(); err != nil { + return err + } + fmt.Println("Selection cleared.") + return nil + } + + review, err := o.review(cmd.Context()) + if err != nil { + return err + } + choices := flatten(review) + if len(choices) == 0 { + return fmt.Errorf("you can reach no project yet; `whoami` shows what you are a member of") + } + + var chosen Selection + if len(args) == 1 { + chosen, err = matchChoice(choices, args[0]) + } else { + chosen, err = promptForChoice(choices) + } + if err != nil { + return err + } + + if err := WriteSelection(chosen); err != nil { + return err + } + fmt.Printf("Now using %s\n", chosen) + if chosen.URL != "" { + fmt.Printf(" %s\n", chosen.URL) + } + return nil + }, + } + o.addFlags(cmd) + cmd.Flags().BoolVar(&clear, "clear", false, "Forget the current selection instead of choosing one.") + return cmd +} + +// flatten turns a review into the list of things that can be selected: +// every project, since a tenant workspace is a record store no member can +// enter (see defaultContext). +func flatten(review *tenancyv1alpha1.SelfTenancyReview) []Selection { + out := []Selection{} + for _, t := range review.Status.Tenants { + for _, p := range t.Projects { + out = append(out, Selection{Tenant: t.Name, Project: p.Name, URL: p.Endpoint}) + } + } + return out +} + +// matchChoice resolves "tenant/project", or a bare tenant when it has +// exactly one project. +func matchChoice(choices []Selection, arg string) (Selection, error) { + tenant, project, hasProject := strings.Cut(arg, "/") + + matches := []Selection{} + for _, c := range choices { + if c.Tenant != tenant { + continue + } + if hasProject && c.Project != project { + continue + } + matches = append(matches, c) + } + + switch len(matches) { + case 0: + return Selection{}, fmt.Errorf("no project %q you can reach (try `projects`)", arg) + case 1: + return matches[0], nil + default: + names := make([]string, 0, len(matches)) + for _, m := range matches { + names = append(names, m.String()) + } + return Selection{}, fmt.Errorf("tenant %q has several projects, say which: %s", + tenant, strings.Join(names, ", ")) + } +} + +// promptForChoice lists the options and reads a number. Deliberately a +// plain numbered list read from stdin: it works over ssh, in a pipe with +// `echo 2 |`, and without a terminal library. +func promptForChoice(choices []Selection) (Selection, error) { + current := CurrentSelection() + fmt.Fprintln(os.Stderr, "Projects you can reach:") + for i, c := range choices { + fmt.Fprintf(os.Stderr, " %s%2d) %s\n", marker(c.Tenant == current.Tenant && c.Project == current.Project), i+1, c) + } + fmt.Fprintf(os.Stderr, "Select [1-%d]: ", len(choices)) + + line, err := bufio.NewReader(os.Stdin).ReadString('\n') + if err != nil && strings.TrimSpace(line) == "" { + return Selection{}, fmt.Errorf("nothing selected") + } + n, err := strconv.Atoi(strings.TrimSpace(line)) + if err != nil || n < 1 || n > len(choices) { + return Selection{}, fmt.Errorf("not a choice between 1 and %d: %q", len(choices), strings.TrimSpace(line)) + } + return choices[n-1], nil +} + +// rolesFor reports the roles that reach a project: its own, plus the +// tenant-wide ones, which fan out to every project and are reported on +// the tenant rather than repeated on each. +func rolesFor(t tenancyv1alpha1.TenantClaim, p tenancyv1alpha1.ProjectClaim) []string { + if len(p.Roles) > 0 { + return p.Roles + } + return t.Roles +} + +// marker flags the current selection in a listing. +func marker(selected bool) string { + if selected { + return "*" + } + return "" +} + +// selectionFor resolves which tenant and project a command should act on: +// the flags when given, otherwise whatever `use` selected. +func selectionFor(tenant, project string) (Selection, error) { + if tenant != "" { + return Selection{Tenant: tenant, Project: project}, nil + } + current := CurrentSelection() + if current.Empty() { + return Selection{}, fmt.Errorf("no tenant selected: pass --tenant, or run `use` to choose one") + } + if project != "" { + current.Project = project + current.URL = "" + } + return current, nil +} diff --git a/tenancy/pkg/clicontext/context.go b/tenancy/pkg/clicontext/context.go new file mode 100644 index 0000000..fe9b119 --- /dev/null +++ b/tenancy/pkg/clicontext/context.go @@ -0,0 +1,146 @@ +/* +Copyright 2026 The kcp Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package clicontext holds what the CLI remembers between commands: the +// server it talks to, and where the user is working. +// +// It lives beside the kubeconfig, in ~/.kube, because it is the same kind +// of thing — the local note about which cluster you mean — and because +// anyone debugging a CLI looks there first. +// +// It belongs to the tenancy CLI because that is where it is written: +// `login` learns the server, `use` picks the project. Other components' +// commands are handed what they need from it by whichever binary composes +// them (contribctl), the way the marketplace's `enable` is handed a +// workspace resolver — so the components still never import each other, +// and a component's CLI on its own needs nothing but its flags. +// +// Nothing here authorizes anything. It is a convenience that saves +// repeating flags — kcp decides what the caller may do. +package clicontext + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" +) + +// EnvPath overrides where the context is stored. +const EnvPath = "CONTRIBCTL_CONTEXT" + +// Context is the CLI's memory between invocations. +type Context struct { + // Server is the front-proxy's base URL, e.g. + // https://kcp.example.com:8443. Every virtual workspace hangs off it + // under /services/, so one address is all a client needs. + Server string `json:"server,omitempty"` + // Tenant and Project are what `use` selected. + Tenant string `json:"tenant,omitempty"` + Project string `json:"project,omitempty"` + // WorkspaceURL is the selected project's own workspace, as the + // tenancy virtual workspace reported it. + WorkspaceURL string `json:"workspaceURL,omitempty"` + // Insecure records that the servers' certificates are not verified, + // so a development setup does not need the flag on every command. + Insecure bool `json:"insecureSkipTLSVerify,omitempty"` + // CertificateAuthority is the CA bundle that verifies them, when they + // are verified. + CertificateAuthority string `json:"certificateAuthority,omitempty"` +} + +// Where returns the path the context is read from and written to. +func Where() string { + if p := os.Getenv(EnvPath); p != "" { + return p + } + home, err := os.UserHomeDir() + if err != nil { + return "" + } + return filepath.Join(home, ".kube", "contribctl.json") +} + +// Load reads the stored context. A missing or unreadable file is an empty +// context, not an error: every caller has to cope with "nothing chosen +// yet" anyway, and a corrupt file should not make the CLI unusable. +func Load() Context { + path := Where() + if path == "" { + return Context{} + } + raw, err := os.ReadFile(path) + if err != nil { + return Context{} + } + var c Context + if err := json.Unmarshal(raw, &c); err != nil { + return Context{} + } + return c +} + +// Save writes the context, creating ~/.kube if it is not there yet. +func Save(c Context) error { + path := Where() + if path == "" { + return fmt.Errorf("no home directory could be determined; set %s", EnvPath) + } + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return fmt.Errorf("create %s: %w", filepath.Dir(path), err) + } + raw, err := json.MarshalIndent(c, "", " ") + if err != nil { + return fmt.Errorf("serialize the context: %w", err) + } + if err := os.WriteFile(path, append(raw, '\n'), 0o600); err != nil { + return fmt.Errorf("write %s: %w", path, err) + } + return nil +} + +// Update reads the context, applies mutate, and writes it back, so a +// command changes only the field it owns. +func Update(mutate func(*Context)) error { + c := Load() + mutate(&c) + return Save(c) +} + +// ServiceURL is where a virtual workspace answers on the stored server: +// the front-proxy routes /services/ to it. +// +// Empty when no server is known, which is the caller's cue to ask for +// one — the CLI cannot guess an address. +func (c Context) ServiceURL(name string) string { + if c.Server == "" { + return "" + } + return strings.TrimSuffix(c.Server, "/") + "/services/" + name +} + +// Selection renders where the user is working, for messages. +func (c Context) Selection() string { + switch { + case c.Tenant == "": + return "" + case c.Project == "": + return c.Tenant + default: + return c.Tenant + "/" + c.Project + } +} diff --git a/tenancy/pkg/directory/directory.go b/tenancy/pkg/directory/directory.go index 2197d0f..ef9d3dc 100644 --- a/tenancy/pkg/directory/directory.go +++ b/tenancy/pkg/directory/directory.go @@ -166,6 +166,38 @@ func (d *Directory) RemoveMembership(k Key) { delete(d.memberships, k) } +// NamedMembership is a membership together with the name of the object it +// was mirrored from, which is what a caller needs to delete it again. +type NamedMembership struct { + Name string + Membership +} + +// MembershipsIn lists every grant recorded in one tenant workspace, +// sorted by name so the answer is stable. +// +// Unlike ReviewFor this is not filtered to one identity: it reports who +// else holds what, which only an administrator of that tenant may see. +// Callers are responsible for having established that first. +func (d *Directory) MembershipsIn(cluster string) []NamedMembership { + if cluster == "" { + return nil + } + + d.mu.RLock() + defer d.mu.RUnlock() + + out := make([]NamedMembership, 0, len(d.memberships)) + for k, m := range d.memberships { + if k.Cluster != cluster { + continue + } + out = append(out, NamedMembership{Name: k.Name, Membership: m}) + } + sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) + return out +} + // ForgetCluster drops everything recorded for one organization workspace, // for when a cluster leaves the fleet. func (d *Directory) ForgetCluster(cluster string) { diff --git a/tenancy/pkg/generated/openapi/zz_generated.openapi.go b/tenancy/pkg/generated/openapi/zz_generated.openapi.go index 68bbfce..b1a0694 100644 --- a/tenancy/pkg/generated/openapi/zz_generated.openapi.go +++ b/tenancy/pkg/generated/openapi/zz_generated.openapi.go @@ -1,10 +1,6 @@ //go:build !ignore_autogenerated // +build !ignore_autogenerated -/* -Copyright 2026 The kcp Authors. -*/ - // Code generated by openapi-gen. DO NOT EDIT. package openapi @@ -19,24 +15,32 @@ import ( func GetOpenAPIDefinitions(ref common.ReferenceCallback) map[string]common.OpenAPIDefinition { return map[string]common.OpenAPIDefinition{ - "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.Membership": schema_sdk_apis_tenancy_v1alpha1_Membership(ref), - "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.MembershipList": schema_sdk_apis_tenancy_v1alpha1_MembershipList(ref), - "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.MembershipSpec": schema_sdk_apis_tenancy_v1alpha1_MembershipSpec(ref), - "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.MembershipStatus": schema_sdk_apis_tenancy_v1alpha1_MembershipStatus(ref), - "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.Project": schema_sdk_apis_tenancy_v1alpha1_Project(ref), - "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.ProjectClaim": schema_sdk_apis_tenancy_v1alpha1_ProjectClaim(ref), - "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.ProjectList": schema_sdk_apis_tenancy_v1alpha1_ProjectList(ref), - "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.ProjectSpec": schema_sdk_apis_tenancy_v1alpha1_ProjectSpec(ref), - "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.ProjectStatus": schema_sdk_apis_tenancy_v1alpha1_ProjectStatus(ref), - "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.SelfTenancyReview": schema_sdk_apis_tenancy_v1alpha1_SelfTenancyReview(ref), - "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.SelfTenancyReviewList": schema_sdk_apis_tenancy_v1alpha1_SelfTenancyReviewList(ref), - "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.SelfTenancyReviewStatus": schema_sdk_apis_tenancy_v1alpha1_SelfTenancyReviewStatus(ref), - "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.Subject": schema_sdk_apis_tenancy_v1alpha1_Subject(ref), - "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.Tenant": schema_sdk_apis_tenancy_v1alpha1_Tenant(ref), - "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.TenantClaim": schema_sdk_apis_tenancy_v1alpha1_TenantClaim(ref), - "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.TenantList": schema_sdk_apis_tenancy_v1alpha1_TenantList(ref), - "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.TenantSpec": schema_sdk_apis_tenancy_v1alpha1_TenantSpec(ref), - "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.TenantStatus": schema_sdk_apis_tenancy_v1alpha1_TenantStatus(ref), + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.Membership": schema_sdk_apis_tenancy_v1alpha1_Membership(ref), + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.MembershipList": schema_sdk_apis_tenancy_v1alpha1_MembershipList(ref), + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.MembershipSpec": schema_sdk_apis_tenancy_v1alpha1_MembershipSpec(ref), + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.MembershipStatus": schema_sdk_apis_tenancy_v1alpha1_MembershipStatus(ref), + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.Project": schema_sdk_apis_tenancy_v1alpha1_Project(ref), + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.ProjectClaim": schema_sdk_apis_tenancy_v1alpha1_ProjectClaim(ref), + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.ProjectList": schema_sdk_apis_tenancy_v1alpha1_ProjectList(ref), + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.ProjectSpec": schema_sdk_apis_tenancy_v1alpha1_ProjectSpec(ref), + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.ProjectStatus": schema_sdk_apis_tenancy_v1alpha1_ProjectStatus(ref), + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.SelfProjectRequest": schema_sdk_apis_tenancy_v1alpha1_SelfProjectRequest(ref), + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.SelfProjectRequestList": schema_sdk_apis_tenancy_v1alpha1_SelfProjectRequestList(ref), + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.SelfProjectRequestSpec": schema_sdk_apis_tenancy_v1alpha1_SelfProjectRequestSpec(ref), + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.SelfProjectRequestStatus": schema_sdk_apis_tenancy_v1alpha1_SelfProjectRequestStatus(ref), + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.SelfTenancyReview": schema_sdk_apis_tenancy_v1alpha1_SelfTenancyReview(ref), + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.SelfTenancyReviewList": schema_sdk_apis_tenancy_v1alpha1_SelfTenancyReviewList(ref), + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.SelfTenancyReviewStatus": schema_sdk_apis_tenancy_v1alpha1_SelfTenancyReviewStatus(ref), + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.SelfTenantRequest": schema_sdk_apis_tenancy_v1alpha1_SelfTenantRequest(ref), + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.SelfTenantRequestList": schema_sdk_apis_tenancy_v1alpha1_SelfTenantRequestList(ref), + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.SelfTenantRequestSpec": schema_sdk_apis_tenancy_v1alpha1_SelfTenantRequestSpec(ref), + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.SelfTenantRequestStatus": schema_sdk_apis_tenancy_v1alpha1_SelfTenantRequestStatus(ref), + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.Subject": schema_sdk_apis_tenancy_v1alpha1_Subject(ref), + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.Tenant": schema_sdk_apis_tenancy_v1alpha1_Tenant(ref), + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.TenantClaim": schema_sdk_apis_tenancy_v1alpha1_TenantClaim(ref), + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.TenantList": schema_sdk_apis_tenancy_v1alpha1_TenantList(ref), + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.TenantSpec": schema_sdk_apis_tenancy_v1alpha1_TenantSpec(ref), + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.TenantStatus": schema_sdk_apis_tenancy_v1alpha1_TenantStatus(ref), v1.APIGroup{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_APIGroup(ref), v1.APIGroupList{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_APIGroupList(ref), v1.APIResource{}.OpenAPIModelName(): schema_pkg_apis_meta_v1_APIResource(ref), @@ -497,6 +501,180 @@ func schema_sdk_apis_tenancy_v1alpha1_ProjectStatus(ref common.ReferenceCallback } } +func schema_sdk_apis_tenancy_v1alpha1_SelfProjectRequest(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "SelfProjectRequest asks for a project in a tenant the caller administers. It is the one write the tenancy virtual workspace does on a caller's behalf, and it exists because the alternative is worse: Projects live in the tenant's own workspace, which is the record store that decides who may reach what, so letting a tenant admin write there directly would hand them the Memberships governing themselves.\n\nThe virtual workspace therefore holds the only credential into that tier. It authorizes the request against the caller's own Membership — admin on that tenant — and creates the Project itself. Nothing is relayed and no privilege is lent: a caller who is not an admin of the named tenant is refused, and one who is gets exactly one object created.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref(v1.ObjectMeta{}.OpenAPIModelName()), + }, + }, + "spec": { + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.SelfProjectRequestSpec"), + }, + }, + "status": { + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.SelfProjectRequestStatus"), + }, + }, + }, + Required: []string{"spec"}, + }, + }, + Dependencies: []string{ + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.SelfProjectRequestSpec", "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.SelfProjectRequestStatus", v1.ObjectMeta{}.OpenAPIModelName()}, + } +} + +func schema_sdk_apis_tenancy_v1alpha1_SelfProjectRequestList(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "SelfProjectRequestList is the list form, which exists because the API machinery requires it; the resource is create-only.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref(v1.ListMeta{}.OpenAPIModelName()), + }, + }, + "items": { + SchemaProps: spec.SchemaProps{ + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Ref: ref("github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.SelfProjectRequest"), + }, + }, + }, + }, + }, + }, + Required: []string{"items"}, + }, + }, + Dependencies: []string{ + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.SelfProjectRequest", v1.ListMeta{}.OpenAPIModelName()}, + } +} + +func schema_sdk_apis_tenancy_v1alpha1_SelfProjectRequestSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "SelfProjectRequestSpec names the project to create.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "tenant": { + SchemaProps: spec.SchemaProps{ + Description: "Tenant is the tenant to create the project in. The caller must hold the admin role there.", + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + "name": { + SchemaProps: spec.SchemaProps{ + Description: "Name is the project's object name, which also seeds its workspace name.", + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + "displayName": { + SchemaProps: spec.SchemaProps{ + Description: "DisplayName is the project's human name. Defaults to Name.", + Type: []string{"string"}, + Format: "", + }, + }, + "description": { + SchemaProps: spec.SchemaProps{ + Description: "Description is free text for humans.", + Type: []string{"string"}, + Format: "", + }, + }, + }, + Required: []string{"tenant", "name"}, + }, + }, + } +} + +func schema_sdk_apis_tenancy_v1alpha1_SelfProjectRequestStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "SelfProjectRequestStatus reports what the request produced.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "created": { + SchemaProps: spec.SchemaProps{ + Description: "Created is true when the Project was created by this request, and false when it already existed — the request is idempotent, so asking twice is not an error.", + Type: []string{"boolean"}, + Format: "", + }, + }, + "project": { + SchemaProps: spec.SchemaProps{ + Description: "Project is the created object's name.", + Type: []string{"string"}, + Format: "", + }, + }, + "message": { + SchemaProps: spec.SchemaProps{ + Description: "Message explains the outcome in a sentence.", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + } +} + func schema_sdk_apis_tenancy_v1alpha1_SelfTenancyReview(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ @@ -613,6 +791,172 @@ func schema_sdk_apis_tenancy_v1alpha1_SelfTenancyReviewStatus(ref common.Referen } } +func schema_sdk_apis_tenancy_v1alpha1_SelfTenantRequest(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "SelfTenantRequest asks for a tenant, with the caller as its first admin. It is how someone who is a member of nothing gets started.\n\nUnlike every other self-service path here, there is no Membership to authorize against — that is the point — so the gate is the deployment's: self-service is off unless enabled, and may be limited to groups the identity provider asserts.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref(v1.ObjectMeta{}.OpenAPIModelName()), + }, + }, + "spec": { + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.SelfTenantRequestSpec"), + }, + }, + "status": { + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref("github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.SelfTenantRequestStatus"), + }, + }, + }, + Required: []string{"spec"}, + }, + }, + Dependencies: []string{ + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.SelfTenantRequestSpec", "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.SelfTenantRequestStatus", v1.ObjectMeta{}.OpenAPIModelName()}, + } +} + +func schema_sdk_apis_tenancy_v1alpha1_SelfTenantRequestList(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "SelfTenantRequestList is the list form, which the API machinery requires; the resource is create-only.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "kind": { + SchemaProps: spec.SchemaProps{ + Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", + Type: []string{"string"}, + Format: "", + }, + }, + "apiVersion": { + SchemaProps: spec.SchemaProps{ + Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", + Type: []string{"string"}, + Format: "", + }, + }, + "metadata": { + SchemaProps: spec.SchemaProps{ + Default: map[string]interface{}{}, + Ref: ref(v1.ListMeta{}.OpenAPIModelName()), + }, + }, + "items": { + SchemaProps: spec.SchemaProps{ + Type: []string{"array"}, + Items: &spec.SchemaOrArray{ + Schema: &spec.Schema{ + SchemaProps: spec.SchemaProps{ + Ref: ref("github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.SelfTenantRequest"), + }, + }, + }, + }, + }, + }, + Required: []string{"items"}, + }, + }, + Dependencies: []string{ + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1.SelfTenantRequest", v1.ListMeta{}.OpenAPIModelName()}, + } +} + +func schema_sdk_apis_tenancy_v1alpha1_SelfTenantRequestSpec(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "SelfTenantRequestSpec names the tenant to create. The first admin is not here: it is the caller, and the server sets it.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "name": { + SchemaProps: spec.SchemaProps{ + Description: "Name is the tenant's object name, which also seeds its workspace name.", + Default: "", + Type: []string{"string"}, + Format: "", + }, + }, + "displayName": { + SchemaProps: spec.SchemaProps{ + Description: "DisplayName is the tenant's human name. Defaults to Name.", + Type: []string{"string"}, + Format: "", + }, + }, + "description": { + SchemaProps: spec.SchemaProps{ + Description: "Description is free text for humans.", + Type: []string{"string"}, + Format: "", + }, + }, + }, + Required: []string{"name"}, + }, + }, + } +} + +func schema_sdk_apis_tenancy_v1alpha1_SelfTenantRequestStatus(ref common.ReferenceCallback) common.OpenAPIDefinition { + return common.OpenAPIDefinition{ + Schema: spec.Schema{ + SchemaProps: spec.SchemaProps{ + Description: "SelfTenantRequestStatus reports what the request produced.", + Type: []string{"object"}, + Properties: map[string]spec.Schema{ + "created": { + SchemaProps: spec.SchemaProps{ + Description: "Created is true when this request created the tenant, and false when one of that name already existed — which does not mean the caller can reach it.", + Type: []string{"boolean"}, + Format: "", + }, + }, + "tenant": { + SchemaProps: spec.SchemaProps{ + Description: "Tenant is the tenant's name.", + Type: []string{"string"}, + Format: "", + }, + }, + "message": { + SchemaProps: spec.SchemaProps{ + Description: "Message explains the outcome in a sentence.", + Type: []string{"string"}, + Format: "", + }, + }, + }, + }, + }, + } +} + func schema_sdk_apis_tenancy_v1alpha1_Subject(ref common.ReferenceCallback) common.OpenAPIDefinition { return common.OpenAPIDefinition{ Schema: spec.Schema{ @@ -833,6 +1177,13 @@ func schema_sdk_apis_tenancy_v1alpha1_TenantSpec(ref common.ReferenceCallback) c Format: "", }, }, + "firstAdmin": { + SchemaProps: spec.SchemaProps{ + Description: "FirstAdmin is an identity granted the admin role on this tenant once its workspace is ready, as a Membership the operator creates.\n\nIt exists because a tenant nobody administers is unusable, and the two writes cannot be one: the Membership lives in the tenant's own workspace, which does not exist when the Tenant is created. Naming the admin here lets whoever creates the tenant hand it over without waiting, and is what makes self-service possible — the virtual workspace sets it to the caller, so a caller cannot make someone else the admin of a tenant they asked for.\n\nEmpty means nobody is seeded, which is the right answer when an administrator intends to grant access separately.", + Type: []string{"string"}, + Format: "", + }, + }, }, Required: []string{"displayName"}, }, diff --git a/tenancy/pkg/naming/naming.go b/tenancy/pkg/naming/naming.go index f2fdf9d..2074de1 100644 --- a/tenancy/pkg/naming/naming.go +++ b/tenancy/pkg/naming/naming.go @@ -39,6 +39,10 @@ const maxNameLength = 54 // fallback appends. const suffixLength = 8 +// subjectHashLength is how many hex characters of the subject hash a +// membership name carries. +const subjectHashLength = 6 + // A Strategy proposes workspace names for an object. Propose returns // candidates in preference order; the caller tries each until one is free // or already owned by the same object. The last candidate embeds the @@ -128,6 +132,26 @@ func Slugify(displayName string) string { return truncate(b.String(), maxNameLength) } +// MembershipName derives the object name of a grant from what it grants +// to whom. It is deterministic so that granting the same access twice is +// an update in place rather than a second object saying the same thing — +// which is what lets a role be changed by re-granting it, and what makes +// seeding safe to repeat. +// +// Subject, tenant and project are slugified because they become part of an +// object name: a subject is usually an email address, which is not a DNS +// label. Different subjects can end up with the same slug (alice@x.com, +// ALICE@X.COM and a group called alice.x.com all become alice-x-com), so a +// short hash of the kind and subject is added to tell them apart. +func MembershipName(kind, subject, tenant, project string) string { + sum := sha256.Sum256([]byte(kind + "\x00" + subject)) + name := Slugify(subject) + "-" + hex.EncodeToString(sum[:])[:subjectHashLength] + "-" + Slugify(tenant) + if project != "" { + name += "-" + Slugify(project) + } + return name +} + // truncate shortens s to at most n bytes without leaving a trailing dash. func truncate(s string, n int) string { if len(s) > n { diff --git a/tenancy/pkg/naming/naming_test.go b/tenancy/pkg/naming/naming_test.go index becabc0..bd0c2d9 100644 --- a/tenancy/pkg/naming/naming_test.go +++ b/tenancy/pkg/naming/naming_test.go @@ -104,6 +104,27 @@ func TestCollidingDisplayNamesDivergeOnFallback(t *testing.T) { } } +func TestMembershipNamesKeepSubjectsApart(t *testing.T) { + // All three slugify to alice-x-com. + names := map[string]string{ + "user alice@x.com": MembershipName("User", "alice@x.com", "acme", ""), + "user ALICE@X.COM": MembershipName("User", "ALICE@X.COM", "acme", ""), + "group alice.x.com": MembershipName("Group", "alice.x.com", "acme", ""), + "group alice@x.com": MembershipName("Group", "alice@x.com", "acme", ""), + "project-scoped one": MembershipName("User", "alice@x.com", "acme", "web"), + } + seen := map[string]string{} + for who, name := range names { + if other, ok := seen[name]; ok { + t.Errorf("%s and %s share the name %q", who, other, name) + } + seen[name] = who + } + if a, b := MembershipName("User", "alice", "acme", ""), MembershipName("User", "alice", "acme", ""); a != b { + t.Errorf("MembershipName is not deterministic: %q vs %q", a, b) + } +} + func TestUnknownStrategyIsAnError(t *testing.T) { if _, err := ForName("cute-animals"); err == nil { t.Error("expected an error for an unknown strategy") diff --git a/tenancy/pkg/operator/operator.go b/tenancy/pkg/operator/operator.go index bc79e9b..c8e419e 100644 --- a/tenancy/pkg/operator/operator.go +++ b/tenancy/pkg/operator/operator.go @@ -52,10 +52,8 @@ import ( mcreconcile "sigs.k8s.io/multicluster-runtime/pkg/reconcile" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/types" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/client-go/dynamic" "k8s.io/client-go/kubernetes/scheme" @@ -196,17 +194,6 @@ func Run(ctx context.Context, opts Options) error { return fmt.Errorf("build membership controller: %w", err) } - // Every slice needs the same nudge: kcp computes a slice's URLs when - // the slice object is reconciled, and a consumer binding the export is - // not a slice event. - for _, slice := range []string{opts.PlatformSlice, opts.TenancySlice, opts.ProvisionerSlice, opts.AccessSlice} { - if err := m.platform.GetLocalManager().Add(manager.RunnableFunc(func(ctx context.Context) error { - return nudgeEndpointSlice(ctx, opts.RestConfig, slice, logger) - })); err != nil { - return fmt.Errorf("register endpoint slice nudger for %s: %w", slice, err) - } - } - logger.Info("tenancy operator running", "tenantStore", "(the clusters bound to "+opts.PlatformSlice+")", "provisioningParent", opts.TenantsPath+" ("+tenantsCluster+")", @@ -319,42 +306,3 @@ func requeueAfterStatus(err error) (ctrl.Result, error) { } return requeue() } - -var endpointSliceGVR = schema.GroupVersionResource{ - Group: "apis.kcp.io", Version: "v1alpha1", Resource: "apiexportendpointslices", -} - -func nudgeEndpointSlice(ctx context.Context, cfg *rest.Config, sliceName string, logger logr.Logger) error { - dyn, err := dynamic.NewForConfig(cfg) - if err != nil { - return fmt.Errorf("build dynamic client: %w", err) - } - - ticker := time.NewTicker(20 * time.Second) - defer ticker.Stop() - - for { - select { - case <-ctx.Done(): - return nil - case <-ticker.C: - } - - slice, err := dyn.Resource(endpointSliceGVR).Get(ctx, sliceName, metav1.GetOptions{}) - if err != nil { - logger.V(2).Info("endpoint slice nudge: get failed", "slice", sliceName, "error", err.Error()) - continue - } - endpoints, _, _ := unstructured.NestedSlice(slice.Object, "status", "endpoints") - if len(endpoints) > 0 { - continue - } - - patch := fmt.Sprintf(`{"metadata":{"annotations":{%q:%q}}}`, bootstrap.NudgeAnnotation, time.Now().UTC().Format(time.RFC3339)) - if _, err := dyn.Resource(endpointSliceGVR).Patch(ctx, sliceName, types.MergePatchType, []byte(patch), metav1.PatchOptions{}); err != nil { - logger.V(2).Info("endpoint slice nudge: patch failed", "slice", sliceName, "error", err.Error()) - continue - } - logger.V(2).Info("nudged URL-less endpoint slice", "slice", sliceName) - } -} diff --git a/tenancy/pkg/operator/tenant.go b/tenancy/pkg/operator/tenant.go index b1b2748..96e0f88 100644 --- a/tenancy/pkg/operator/tenant.go +++ b/tenancy/pkg/operator/tenant.go @@ -18,6 +18,7 @@ package operator import ( "context" + "fmt" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" @@ -26,8 +27,11 @@ import ( mcreconcile "sigs.k8s.io/multicluster-runtime/pkg/reconcile" apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/multicluster-runtime/pkg/multicluster" "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/pkg/bootstrap" + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/pkg/naming" tenancyv1alpha1 "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1" ) @@ -111,10 +115,85 @@ func (r *reconcilers) reconcileTenant(ctx context.Context, req mcreconcile.Reque if !ws.Ready { return requeue() } + + // The tenant's workspace exists now, so the first admin can finally be + // granted. This is the second half of a write that could not be one: + // the Membership lives in a workspace that did not exist when the + // Tenant was created. + if err := r.seedFirstAdmin(ctx, c, &tenant, ws.Cluster); err != nil { + return ctrl.Result{}, err + } + logger.V(2).Info("tenant ready", "workspace", ws.Name, "workspaceCluster", ws.Cluster) return ctrl.Result{}, nil } +// firstAdminSeededAnnotation is set on a Tenant once its first admin has +// been granted, so the grant is made only once. +const firstAdminSeededAnnotation = "tenancy.platform.kcp.io/first-admin-seeded" + +// seedFirstAdmin grants spec.firstAdmin the admin role on the tenant, once. +// +// This seeds the first admin, it does not keep them. Whoever holds the +// tenant afterwards may revoke it like any other grant, and it must not +// come back, so the Tenant is marked once the grant is made. +func (r *reconcilers) seedFirstAdmin(ctx context.Context, platform client.Client, tenant *tenancyv1alpha1.Tenant, cluster string) error { + if tenant.Spec.FirstAdmin == "" || tenant.Annotations[firstAdminSeededAnnotation] == "true" { + return nil + } + + c, err := clientFor(ctx, r.m.tenancy, multicluster.ClusterName(cluster)) + if err != nil { + // The tenant tier is served by the tenancy export, which the new + // workspace binds through its WorkspaceType. A moment after the + // workspace is ready that binding may still be settling. + return err + } + + // Same shape as the CLI's grant naming, so a seeded grant and a + // hand-made one for the same subject are the same object rather than + // two that fight. + name := naming.MembershipName(string(tenancyv1alpha1.SubjectKindUser), tenant.Spec.FirstAdmin, tenant.Name, "") + membership := &tenancyv1alpha1.Membership{ + ObjectMeta: metav1.ObjectMeta{Name: name}, + Spec: tenancyv1alpha1.MembershipSpec{ + Subject: tenancyv1alpha1.Subject{ + Kind: tenancyv1alpha1.SubjectKindUser, + Name: tenant.Spec.FirstAdmin, + }, + Role: tenancyv1alpha1.RoleAdmin, + Tenant: tenant.Name, + }, + } + err = c.Create(ctx, membership) + if apierrors.IsAlreadyExists(err) { + // The same user already has a grant on the tenant, maybe with a + // lower role. Make it admin, or the tenant could end up with none. + var existing tenancyv1alpha1.Membership + if err := c.Get(ctx, client.ObjectKey{Name: name}, &existing); err != nil { + return fmt.Errorf("get the existing grant of tenant %q's first admin: %w", tenant.Name, err) + } + if existing.Spec.Role != tenancyv1alpha1.RoleAdmin { + existing.Spec.Role = tenancyv1alpha1.RoleAdmin + if err := c.Update(ctx, &existing); err != nil { + return fmt.Errorf("make tenant %q's first admin an admin: %w", tenant.Name, err) + } + } + } else if err != nil { + return fmt.Errorf("seed the first admin of tenant %q: %w", tenant.Name, err) + } + + patch := client.MergeFrom(tenant.DeepCopy()) + if tenant.Annotations == nil { + tenant.Annotations = map[string]string{} + } + tenant.Annotations[firstAdminSeededAnnotation] = "true" + if err := platform.Patch(ctx, tenant, patch); err != nil { + return fmt.Errorf("mark tenant %q's first admin as seeded: %w", tenant.Name, err) + } + return nil +} + func updateTenantStatus(ctx context.Context, c client.Client, tenant *tenancyv1alpha1.Tenant, status tenancyv1alpha1.TenantStatus) error { if tenant.Status == status { return nil diff --git a/tenancy/pkg/operator/workspaces.go b/tenancy/pkg/operator/workspaces.go index f3d0fa2..c310282 100644 --- a/tenancy/pkg/operator/workspaces.go +++ b/tenancy/pkg/operator/workspaces.go @@ -27,15 +27,13 @@ import ( corev1alpha1 "github.com/kcp-dev/sdk/apis/core/v1alpha1" kcptenancyv1alpha1 "github.com/kcp-dev/sdk/apis/tenancy/v1alpha1" - - tenancyv1alpha1 "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1" ) // ownerUIDLabel ties a provisioned Workspace to the Tenant or Project that // asked for it. It is how a reconcile recognizes its own workspace among // naming candidates, and how a collision with someone else's workspace is // told apart from an earlier run of the same reconcile. -const ownerUIDLabel = tenancyv1alpha1.GroupName + "/owner-uid" +const ownerUIDLabel = "tenancy.kcp.hub/owner-uid" // provisioned describes the workspace a tenant or project ended up with. type provisioned struct { diff --git a/tenancy/pkg/provider/clusters.go b/tenancy/pkg/provider/clusters.go new file mode 100644 index 0000000..9345766 --- /dev/null +++ b/tenancy/pkg/provider/clusters.go @@ -0,0 +1,109 @@ +/* +Copyright 2026 The kcp Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package provider + +import ( + "context" + "fmt" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + "sigs.k8s.io/controller-runtime/pkg/client" + mcmanager "sigs.k8s.io/multicluster-runtime/pkg/manager" + "sigs.k8s.io/multicluster-runtime/pkg/multicluster" +) + +// Clusters hands out a client for one logical cluster in the fleet. +// +// An APIExport's virtual workspace runs per shard: the endpoint slice +// lists one URL for each shard serving the export, and each of those URLs +// serves only the clusters that live on that shard. So there is no single +// URL a write can be addressed to. Asking a shard about a cluster it does +// not host is refused as a plain Forbidden — that shard has no APIBinding +// for the cluster, and the virtual workspace's authorizer anonymizes the +// reason, so the answer is indistinguishable from the caller having no +// standing at all. +// +// The read side already solves this: the provider watches every URL the +// slice publishes and knows which endpoint each cluster was discovered +// through. Clusters exposes that, so a write goes to the shard that +// actually holds the workspace rather than to whichever URL happened to +// be listed first. +type Clusters struct { + // ready is closed once Run has built the managers. Everything below is + // written before the close and only read after it, which is what makes + // the handoff to request handlers safe without a lock. + ready chan struct{} + platform mcmanager.Manager + tenancy mcmanager.Manager +} + +// NewClusters returns a Clusters that Run fills in. +func NewClusters() *Clusters { + return &Clusters{ready: make(chan struct{})} +} + +func (c *Clusters) set(platform, tenancy mcmanager.Manager) { + c.platform, c.tenancy = platform, tenancy + close(c.ready) +} + +// Tenancy returns a client for a tenant workspace, which is where Projects +// and Memberships live. +func (c *Clusters) Tenancy(ctx context.Context, cluster string) (client.Client, error) { + if err := c.wait(ctx); err != nil { + return nil, err + } + return clientFor(ctx, c.tenancy, cluster) +} + +// Platform returns a client for a workspace in the platform tier, which is +// where Tenant records live. +func (c *Clusters) Platform(ctx context.Context, cluster string) (client.Client, error) { + if err := c.wait(ctx); err != nil { + return nil, err + } + return clientFor(ctx, c.platform, cluster) +} + +// wait blocks until the managers exist. In practice they always do by the +// time a write is attempted: every write is authorized against the +// directory first, and the directory is not ready until both managers have +// synced. +func (c *Clusters) wait(ctx context.Context) error { + select { + case <-c.ready: + return nil + case <-ctx.Done(): + return apierrors.NewServiceUnavailable("the tenancy directory is still starting") + } +} + +func clientFor(ctx context.Context, mgr mcmanager.Manager, cluster string) (client.Client, error) { + if cluster == "" { + return nil, fmt.Errorf("no logical cluster given") + } + cl, err := mgr.GetCluster(ctx, multicluster.ClusterName(cluster)) + if err != nil { + // A cluster the provider has not discovered is one no shard has + // reported binding the export — usually a workspace that is still + // initializing, which is worth retrying rather than reporting as a + // refusal. + return nil, apierrors.NewServiceUnavailable(fmt.Sprintf( + "workspace %s has not joined the fleet yet: %v", cluster, err)) + } + return cl.GetClient(), nil +} diff --git a/tenancy/pkg/provider/provider.go b/tenancy/pkg/provider/provider.go index 395a63a..3f937fe 100644 --- a/tenancy/pkg/provider/provider.go +++ b/tenancy/pkg/provider/provider.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -// Package provider populates the tenancy directory from the organization +// Package provider populates the tenancy directory from the tenant // workspaces bound to the tenancy APIExport. It is the read side of the // operator: the same discovery (multicluster-runtime over the apiexport // endpoint slice), but instead of materializing workspaces it only mirrors @@ -63,6 +63,10 @@ type Options struct { // different tiers, so the directory is fed by two managers. PlatformSlice string TenancySlice string + // Clusters, when non-nil, is filled with a handle on the two managers, + // so the caller can address a write to the shard that hosts a given + // workspace. See the type for why that is not a free choice. + Clusters *Clusters } // Run fills dir until ctx is cancelled. It marks the directory ready once @@ -112,6 +116,10 @@ func Run(ctx context.Context, opts Options, dir *directory.Directory) error { return err } + if opts.Clusters != nil { + opts.Clusters.set(platform, tenancy) + } + if err := registerTenantMirror(platform, dir); err != nil { return err } @@ -161,7 +169,7 @@ func (c clusterLifecycle) OnDelete(obj client.Object) { if cluster == "" { return } - c.logger.Info("organization workspace left the fleet, dropping from directory", "cluster", cluster) + c.logger.Info("workspace left the fleet, dropping from directory", "cluster", cluster) c.dir.ForgetCluster(cluster) } diff --git a/tenancy/pkg/server/options.go b/tenancy/pkg/server/options.go index 744abd3..f32bcd6 100644 --- a/tenancy/pkg/server/options.go +++ b/tenancy/pkg/server/options.go @@ -55,6 +55,14 @@ type Options struct { // workspace endpoints in review answers. EndpointBase string + // SelfServiceTenants lets a caller with no membership request a tenant + // and become its admin. SelfServiceTenantGroups narrows who may. + SelfServiceTenants bool + SelfServiceTenantGroups []string + // StoreWorkspace is where Tenant records live; a requested tenant is + // created there. + StoreWorkspace string + // PlatformSlice and TenancySlice are the endpoint slices the directory // is fed from: Tenants come from the platform tier, Projects and // Memberships from inside each tenant's workspace. @@ -91,6 +99,18 @@ func (o *Options) AddFlags(fs *pflag.FlagSet) { fs.StringVar(&o.EndpointBase, "endpoint-base", "https://kcp.example.com/clusters/", "FrontProxy URL prefix for workspace endpoints returned in review answers.") + // Self-service tenants: how someone with no membership gets started. + // Off by default, because handing out tenants is a decision a + // deployment makes rather than one this server makes for it. + fs.BoolVar(&o.SelfServiceTenants, "self-service-tenants", false, + "Let any authenticated caller request a tenant, becoming its admin. "+ + "Off means tenants are an administrator's job.") + fs.StringSliceVar(&o.SelfServiceTenantGroups, "self-service-tenant-groups", nil, + "Restrict --self-service-tenants to callers in one of these groups, as kcp sees them. "+ + "Empty means any authenticated caller.") + fs.StringVar(&o.StoreWorkspace, "store-workspace", bootstrap.DefaultWorkspacePrefix+":"+bootstrap.DefaultStoreWorkspace, + "Path of the workspace Tenant records live in, written to when a tenant is requested.") + fs.StringVar(&o.PlatformSlice, "platform-endpointslice", bootstrap.ExportPlatform, "APIExportEndpointSlice serving Tenants.") fs.StringVar(&o.TenancySlice, "tenancy-endpointslice", bootstrap.ExportTenancy, @@ -102,6 +122,27 @@ func (o *Options) AddFlags(fs *pflag.FlagSet) { if fs.Lookup("kubeconfig") == nil { fs.StringVar(&o.Kubeconfig, "kubeconfig", "", "Path to the kubeconfig for the target kcp (required).") } + + addIgnoredOperatorFlags(fs) +} + +// addIgnoredOperatorFlags accepts, and ignores, flags the kcp-operator +// puts on every VirtualWorkspace deployment. +// +// --shard-external-url is one of kcp's own virtual-workspace server's +// flags and means nothing here, but the operator appends it +// unconditionally (internal/resources/compiledvirtualworkspace: +// "TODO(ntnn): We need a way to shut this off if it isn't required"), +// even though the API type documents spec.command as suppressing it +// "because a custom server would reject the unknown flags and refuse to +// start". An apiserver built on pflag exits on a flag it does not know, +// so accepting it is what lets this server be deployed by the operator +// at all. Remove once the operator stops sending it. +func addIgnoredOperatorFlags(fs *pflag.FlagSet) { + var ignored string + fs.StringVar(&ignored, "shard-external-url", "", + "Ignored. Accepted only because the kcp-operator passes it to every virtual workspace.") + _ = fs.MarkHidden("shard-external-url") } // Complete fills in derived defaults. diff --git a/tenancy/pkg/server/projects.go b/tenancy/pkg/server/projects.go new file mode 100644 index 0000000..cef54c6 --- /dev/null +++ b/tenancy/pkg/server/projects.go @@ -0,0 +1,210 @@ +/* +Copyright 2026 The kcp Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package server + +import ( + "context" + "fmt" + "strings" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/client-go/dynamic" + "k8s.io/client-go/rest" + "k8s.io/client-go/util/retry" + "sigs.k8s.io/controller-runtime/pkg/client" + + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/pkg/provider" + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/pkg/virtual/membership" + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/pkg/virtual/selfprojectrequest" + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/pkg/virtual/selftenantrequest" + tenancyv1alpha1 "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1" +) + +// projectWriter creates Projects in tenant workspaces through the tenancy +// APIExport's virtual workspace — the same export the directory reads, so +// the server needs no reach it does not already have. +// +// This is the credential a tenant admin deliberately does not hold. What +// keeps that honest is the narrowness of what it is used for: the storage +// authorizes the caller first, and then exactly one object is created +// from fields the caller controls. Nothing here can name a workspace, +// choose a cluster, or touch a Membership. +type projectWriter struct { + clusters *provider.Clusters +} + +func newProjectWriter(clusters *provider.Clusters) *projectWriter { + return &projectWriter{clusters: clusters} +} + +// CreateProject satisfies selfprojectrequest.CreateProjectFunc. +func (w *projectWriter) CreateProject(ctx context.Context, cluster string, project *tenancyv1alpha1.Project) (bool, error) { + c, err := w.clusters.Tenancy(ctx, cluster) + if err != nil { + return false, err + } + + if err := c.Create(ctx, project); err != nil { + // Asking twice is not an error: the request says what should + // exist, and it does. + if apierrors.IsAlreadyExists(err) { + return false, nil + } + return false, fmt.Errorf("create project %q in tenant workspace %s: %w", project.Name, cluster, err) + } + return true, nil +} + +var _ selfprojectrequest.CreateProjectFunc = (*projectWriter)(nil).CreateProject + +// membershipWriter changes grants inside tenant workspaces, through the +// same export the directory reads them from. +// +// This is the credential a tenant admin cannot hold: the grants governing +// their own access live beside the projects. What keeps it honest is that +// the storage authorizes the caller as an admin of that very tenant first, +// and derives both the cluster and the object name itself — nothing the +// caller sends chooses where a write lands. +type membershipWriter struct { + clusters *provider.Clusters +} + +func newMembershipWriter(clusters *provider.Clusters) *membershipWriter { + return &membershipWriter{clusters: clusters} +} + +// Create satisfies membership.CreateFunc. Re-granting the same access is +// an update in place rather than a conflict, because the request states +// what should be true and the name is derived from that. +func (w *membershipWriter) Create(ctx context.Context, cluster string, m *tenancyv1alpha1.Membership) (bool, error) { + c, err := w.clusters.Tenancy(ctx, cluster) + if err != nil { + return false, err + } + + if err := c.Create(ctx, m); err == nil { + return true, nil + } else if !apierrors.IsAlreadyExists(err) { + return false, fmt.Errorf("grant %q in tenant workspace %s: %w", m.Name, cluster, err) + } + + // Already there: bring the role (and anything else in the spec) to what + // was asked for, retrying the read-modify-write on a conflicting update. + spec := m.Spec + err = retry.RetryOnConflict(retry.DefaultRetry, func() error { + var existing tenancyv1alpha1.Membership + if err := c.Get(ctx, client.ObjectKey{Name: m.Name}, &existing); err != nil { + return err + } + if existing.Spec == spec { + return nil + } + existing.Spec = spec + return c.Update(ctx, &existing) + }) + if err != nil { + return false, fmt.Errorf("update grant %q in tenant workspace %s: %w", m.Name, cluster, err) + } + return false, nil +} + +// Delete satisfies membership.DeleteFunc. +func (w *membershipWriter) Delete(ctx context.Context, cluster, name string) error { + c, err := w.clusters.Tenancy(ctx, cluster) + if err != nil { + return err + } + m := &tenancyv1alpha1.Membership{ObjectMeta: metav1.ObjectMeta{Name: name}} + if err := c.Delete(ctx, m); err != nil { + // Gone is the state that was asked for. + if apierrors.IsNotFound(err) { + return nil + } + return fmt.Errorf("revoke %q in tenant workspace %s: %w", name, cluster, err) + } + return nil +} + +var ( + _ membership.CreateFunc = (*membershipWriter)(nil).Create + _ membership.DeleteFunc = (*membershipWriter)(nil).Delete +) + +// tenantWriter creates Tenants in the store workspace through the platform +// APIExport — the same export the directory reads Tenants from. +// +// Only one operation is offered through it, and the Tenant it writes names +// its first admin, so the credential cannot be used to grant anything to +// anyone the caller is not. +type tenantWriter struct { + clusters *provider.Clusters + store string +} + +func newTenantWriter(clusters *provider.Clusters, store string) *tenantWriter { + return &tenantWriter{clusters: clusters, store: store} +} + +// CreateTenant satisfies selftenantrequest.CreateTenantFunc. +func (w *tenantWriter) CreateTenant(ctx context.Context, tenant *tenancyv1alpha1.Tenant) (bool, error) { + c, err := w.clusters.Platform(ctx, w.store) + if err != nil { + return false, err + } + + if err := c.Create(ctx, tenant); err != nil { + if apierrors.IsAlreadyExists(err) { + return false, nil + } + return false, fmt.Errorf("create tenant %q: %w", tenant.Name, err) + } + return true, nil +} + +var _ selftenantrequest.CreateTenantFunc = (*tenantWriter)(nil).CreateTenant + +// resolveCluster reads the logical cluster name of a workspace path. +// +// The writers address workspaces by cluster rather than by path, because +// an APIExport's virtual workspace serves clusters: it has no view of the +// tree the path walks. +func resolveCluster(cfg *rest.Config, path string) (string, error) { + scoped := rest.CopyConfig(cfg) + host := scoped.Host + if i := strings.Index(host, "/clusters/"); i >= 0 { + host = host[:i] + } + scoped.Host = strings.TrimSuffix(host, "/") + "/clusters/" + path + + dyn, err := dynamic.NewForConfig(scoped) + if err != nil { + return "", fmt.Errorf("build dynamic client: %w", err) + } + lc, err := dyn.Resource(schema.GroupVersionResource{ + Group: "core.kcp.io", Version: "v1alpha1", Resource: "logicalclusters", + }).Get(context.Background(), "cluster", metav1.GetOptions{}) + if err != nil { + return "", err + } + name := lc.GetAnnotations()["kcp.io/cluster"] + if name == "" { + return "", fmt.Errorf("the LogicalCluster of %s carries no kcp.io/cluster annotation", path) + } + return name, nil +} diff --git a/tenancy/pkg/server/server.go b/tenancy/pkg/server/server.go index 685d5e0..1a06c68 100644 --- a/tenancy/pkg/server/server.go +++ b/tenancy/pkg/server/server.go @@ -15,7 +15,7 @@ limitations under the License. */ // Package server wires the tenancy virtual workspace binary together: the -// directory, the provider that fills it from organization workspaces, and +// directory, the provider that fills it from tenant workspaces, and // a virtual-workspace root apiserver serving SelfTenancyReview at // /services/tenancy behind kcp's front-proxy. package server @@ -46,7 +46,9 @@ import ( "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/pkg/directory" generatedopenapi "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/pkg/generated/openapi" "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/pkg/provider" + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/pkg/virtual/membership" "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/pkg/virtual/selftenancyreview" + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/pkg/virtual/selftenantrequest" tenancyv1alpha1 "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1" ) @@ -90,12 +92,18 @@ func Run(ctx context.Context, o *Options) error { dir := directory.New() + // The writes below go through the same discovery that fills the + // directory, which is what makes them land on the shard that actually + // hosts the workspace. + clusters := provider.NewClusters() + providerErr := make(chan error, 1) go func() { providerErr <- provider.Run(ctx, provider.Options{ RestConfig: restConfig, PlatformSlice: o.PlatformSlice, TenancySlice: o.TenancySlice, + Clusters: clusters, }, dir) }() @@ -103,12 +111,41 @@ func Run(ctx context.Context, o *Options) error { "platformSlice", o.PlatformSlice, "tenancySlice", o.TenancySlice, "kubeconfig", o.Kubeconfig, "host", restConfig.Host) + scheme := runtime.NewScheme() + utilruntime.Must(tenancyv1alpha1.AddToScheme(scheme)) + + // The writes this server performs on a caller's behalf, all through + // the tenancy export, because the tenant tier is closed to its own + // members by design: a project in a tenant they administer, and the + // grants deciding who else may reach it. + writer := newProjectWriter(clusters) + grants := newMembershipWriter(clusters) + + // And the one that starts someone off with nothing: a tenant, with + // themselves as its admin. Off unless the deployment enabled it. + storeCluster, err := resolveCluster(restConfig, o.StoreWorkspace) + if err != nil && o.SelfServiceTenants { + return fmt.Errorf("resolve the tenant store %s: %w", o.StoreWorkspace, err) + } + tenants := newTenantWriter(clusters, storeCluster) + vws := []rootapiserver.NamedVirtualWorkspace{ - selftenancyreview.NewVirtualWorkspace(dir, endpointFor(o.EndpointBase)), + selftenancyreview.NewVirtualWorkspace(selftenancyreview.Config{ + Directory: dir, + EndpointFor: endpointFor(o.EndpointBase), + CreateProject: writer.CreateProject, + Tenants: selftenantrequest.Options{ + Enabled: o.SelfServiceTenants, + Groups: o.SelfServiceTenantGroups, + }, + CreateTenant: tenants.CreateTenant, + Memberships: membership.Options{ + Create: grants.Create, + Delete: grants.Delete, + }, + }), } - scheme := runtime.NewScheme() - utilruntime.Must(tenancyv1alpha1.AddToScheme(scheme)) codecs := serializer.NewCodecFactory(scheme) recommended := genericapiserver.NewRecommendedConfig(codecs) @@ -189,8 +226,7 @@ func Run(ctx context.Context, o *Options) error { if err != nil && !errors.Is(err, context.Canceled) { return fmt.Errorf("directory provider failed: %w", err) } - <-serveErr - return nil + return <-serveErr case err := <-serveErr: return err } diff --git a/tenancy/pkg/virtual/membership/storage.go b/tenancy/pkg/virtual/membership/storage.go new file mode 100644 index 0000000..4c81a40 --- /dev/null +++ b/tenancy/pkg/virtual/membership/storage.go @@ -0,0 +1,377 @@ +/* +Copyright 2026 The kcp Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package membership serves the grants of the tenants a caller +// administers, so RBAC can be managed without entering the workspace the +// grants live in. +// +// Memberships live inside their tenant's workspace, which is closed to the +// tenant's own members — including its admins — precisely because it holds +// the records that decide their access. That makes it the one part of the +// model a tenant admin cannot administer directly, which is not a gap to +// leave open: someone has to be able to add a colleague. +// +// So this is mediated the same way project creation is. The caller's own +// admin Membership, as the directory already reports it, is the +// authorization; the server's credential performs the write; and what is +// offered through it is only ever a Membership in a tenant the caller +// already administers. A caller cannot name a workspace or a cluster, and +// cannot reach a tenant they do not administer — not even to discover that +// it exists. +// +// Listing here is deliberately wider than a self-review: it reports what +// OTHER people hold, which is the point of administering access, and is +// why every path checks for admin rather than for mere membership. +package membership + +import ( + "context" + "fmt" + "slices" + "sort" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + metainternalversion "k8s.io/apimachinery/pkg/apis/meta/internalversion" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/util/validation/field" + "k8s.io/apiserver/pkg/authentication/user" + genericapirequest "k8s.io/apiserver/pkg/endpoints/request" + "k8s.io/apiserver/pkg/registry/rest" + "k8s.io/klog/v2" + + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/pkg/directory" + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/pkg/naming" + tenancyv1alpha1 "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1" +) + +// CreateFunc upserts a Membership in one tenant's workspace. The server +// supplies it, because how the virtual workspace reaches that workspace is +// a detail of the deployment rather than of the API. +type CreateFunc func(ctx context.Context, cluster string, m *tenancyv1alpha1.Membership) (created bool, err error) + +// DeleteFunc removes a Membership from one tenant's workspace. +type DeleteFunc func(ctx context.Context, cluster, name string) error + +// Options carries the write side. Both funcs may be nil, in which case the +// resource stays readable and says plainly that changing grants is not +// configured rather than appearing to work. +type Options struct { + Create CreateFunc + Delete DeleteFunc +} + +// REST serves memberships for the tenants the caller administers. +type REST struct { + directory *directory.Directory + opts Options +} + +var ( + _ rest.Storage = &REST{} + _ rest.Lister = &REST{} + _ rest.Getter = &REST{} + _ rest.Creater = &REST{} + _ rest.GracefulDeleter = &REST{} + _ rest.Scoper = &REST{} + _ rest.SingularNameProvider = &REST{} +) + +// NewREST returns the storage. +func NewREST(d *directory.Directory, opts Options) *REST { + return &REST{directory: d, opts: opts} +} + +func (r *REST) New() runtime.Object { return &tenancyv1alpha1.Membership{} } + +func (r *REST) NewList() runtime.Object { return &tenancyv1alpha1.MembershipList{} } + +func (r *REST) Destroy() {} + +func (r *REST) NamespaceScoped() bool { return false } + +func (r *REST) GetSingularName() string { return "membership" } + +func (r *REST) ConvertToTable(ctx context.Context, object runtime.Object, tableOptions runtime.Object) (*metav1.Table, error) { + return rest.NewDefaultTableConvertor(tenancyv1alpha1.Resource("memberships")). + ConvertToTable(ctx, object, tableOptions) +} + +// List returns every grant in every tenant the caller administers. +// +// There is no scoping parameter: the answer is the caller's whole +// administrative surface, and a client that cares about one tenant filters +// on spec.tenant. That keeps the authorization rule here a single +// sentence, which is worth more than saving the client a loop. +func (r *REST) List(ctx context.Context, _ *metainternalversion.ListOptions) (runtime.Object, error) { + admin, err := r.adminTenants(ctx) + if err != nil { + return nil, err + } + + list := &tenancyv1alpha1.MembershipList{} + for _, claim := range admin { + for _, m := range r.directory.MembershipsIn(claim.Cluster) { + list.Items = append(list.Items, membershipObject(m)) + } + } + // Stable across calls: by tenant, then by name. + sort.Slice(list.Items, func(i, j int) bool { + if list.Items[i].Spec.Tenant != list.Items[j].Spec.Tenant { + return list.Items[i].Spec.Tenant < list.Items[j].Spec.Tenant + } + return list.Items[i].Name < list.Items[j].Name + }) + return list, nil +} + +// Get returns one grant, if it is in a tenant the caller administers. +func (r *REST) Get(ctx context.Context, name string, _ *metav1.GetOptions) (runtime.Object, error) { + admin, err := r.adminTenants(ctx) + if err != nil { + return nil, err + } + for _, claim := range admin { + for _, m := range r.directory.MembershipsIn(claim.Cluster) { + if m.Name == name { + out := membershipObject(m) + return &out, nil + } + } + } + return nil, apierrors.NewNotFound(tenancyv1alpha1.Resource("memberships"), name) +} + +// Create grants access in a tenant the caller administers. +// +// The object's name is derived from what is being granted to whom, not +// taken from the request: two requests saying the same thing are the same +// grant, so re-granting changes the role in place instead of leaving two +// objects disagreeing about it. +func (r *REST) Create(ctx context.Context, obj runtime.Object, _ rest.ValidateObjectFunc, _ *metav1.CreateOptions) (runtime.Object, error) { + m, ok := obj.(*tenancyv1alpha1.Membership) + if !ok { + return nil, apierrors.NewBadRequest(fmt.Sprintf("not a Membership: %T", obj)) + } + if r.opts.Create == nil { + return nil, apierrors.NewServiceUnavailable( + "this virtual workspace was started without membership management; grants are read-only here") + } + + if errs := validateSpec(&m.Spec); len(errs) > 0 { + return nil, apierrors.NewInvalid( + tenancyv1alpha1.SchemeGroupVersion.WithKind("Membership").GroupKind(), m.Name, errs) + } + + claim, err := r.adminOn(ctx, m.Spec.Tenant) + if err != nil { + return nil, err + } + // A grant naming a project that does not exist would be a grant that + // never applies to anything — worth refusing while the caller is still + // looking at it. + if m.Spec.Project != "" && !slices.ContainsFunc(claim.Projects, + func(p tenancyv1alpha1.ProjectClaim) bool { return p.Name == m.Spec.Project }) { + return nil, apierrors.NewInvalid( + tenancyv1alpha1.SchemeGroupVersion.WithKind("Membership").GroupKind(), m.Name, + field.ErrorList{field.NotFound( + field.NewPath("spec", "project"), m.Spec.Project)}) + } + + grant := &tenancyv1alpha1.Membership{ + ObjectMeta: metav1.ObjectMeta{ + Name: naming.MembershipName(string(m.Spec.Subject.Kind), m.Spec.Subject.Name, m.Spec.Tenant, m.Spec.Project), + }, + Spec: m.Spec, + } + + // Granting again changes the role of the existing grant. Do not let that + // turn the last tenant admin into a non-admin, same as Delete. + grants := r.directory.MembershipsIn(claim.Cluster) + if idx := slices.IndexFunc(grants, func(g directory.NamedMembership) bool { return g.Name == grant.Name }); idx >= 0 { + existing := grants[idx] + if existing.Role == string(tenancyv1alpha1.RoleAdmin) && existing.Project == "" && + m.Spec.Role != tenancyv1alpha1.RoleAdmin && lastTenantAdmin(grants, m.Spec.Tenant) { + return nil, apierrors.NewForbidden( + tenancyv1alpha1.Resource("memberships"), grant.Name, + fmt.Errorf("this is the last admin of tenant %q; grant admin to someone else first", m.Spec.Tenant)) + } + } + + created, err := r.opts.Create(ctx, claim.Cluster, grant) + if err != nil { + return nil, err + } + + user, _ := genericapirequest.UserFrom(ctx) + klog.FromContext(ctx).V(2).Info("granted membership", + "by", userName(user), "subject", m.Spec.Subject.Name, "role", m.Spec.Role, + "tenant", m.Spec.Tenant, "project", m.Spec.Project, + "cluster", claim.Cluster, "created", created) + + return grant, nil +} + +// Delete revokes a grant in a tenant the caller administers. +func (r *REST) Delete(ctx context.Context, name string, _ rest.ValidateObjectFunc, _ *metav1.DeleteOptions) (runtime.Object, bool, error) { + if r.opts.Delete == nil { + return nil, false, apierrors.NewServiceUnavailable( + "this virtual workspace was started without membership management; grants are read-only here") + } + + admin, err := r.adminTenants(ctx) + if err != nil { + return nil, false, err + } + + for _, claim := range admin { + grants := r.directory.MembershipsIn(claim.Cluster) + idx := slices.IndexFunc(grants, func(m directory.NamedMembership) bool { return m.Name == name }) + if idx < 0 { + continue + } + found := grants[idx] + + // Refuse the one deletion that cannot be undone through this API: + // removing the last tenant-wide admin leaves nobody who may grant + // anything, including the grant that would fix it. + if found.Role == string(tenancyv1alpha1.RoleAdmin) && found.Project == "" && + lastTenantAdmin(grants, found.Tenant) { + return nil, false, apierrors.NewForbidden( + tenancyv1alpha1.Resource("memberships"), name, + fmt.Errorf("this is the last admin of tenant %q; grant admin to someone else first, "+ + "or nobody will be able to", found.Tenant)) + } + + if err := r.opts.Delete(ctx, claim.Cluster, name); err != nil { + return nil, false, err + } + + user, _ := genericapirequest.UserFrom(ctx) + klog.FromContext(ctx).V(2).Info("revoked membership", + "by", userName(user), "name", name, "tenant", found.Tenant, "cluster", claim.Cluster) + + out := membershipObject(found) + return &out, true, nil + } + + return nil, false, apierrors.NewNotFound(tenancyv1alpha1.Resource("memberships"), name) +} + +// adminTenants returns the caller's claims on the tenants they administer +// and whose workspace exists. +func (r *REST) adminTenants(ctx context.Context) ([]tenancyv1alpha1.TenantClaim, error) { + if !r.directory.Ready() { + return nil, apierrors.NewServiceUnavailable("tenancy directory is not ready; try again shortly") + } + user, ok := genericapirequest.UserFrom(ctx) + if !ok { + return nil, apierrors.NewUnauthorized("no user present in request context") + } + + // noEndpoints: this path needs roles and clusters, not URLs. + var admin []tenancyv1alpha1.TenantClaim + for _, claim := range r.directory.ReviewFor(user.GetName(), user.GetGroups(), noEndpoints) { + if slices.Contains(claim.Roles, string(tenancyv1alpha1.RoleAdmin)) && claim.Cluster != "" { + admin = append(admin, claim) + } + } + return admin, nil +} + +// adminOn resolves one tenant the caller administers, or explains the +// refusal without revealing whether the tenant exists. +func (r *REST) adminOn(ctx context.Context, tenant string) (tenancyv1alpha1.TenantClaim, error) { + admin, err := r.adminTenants(ctx) + if err != nil { + return tenancyv1alpha1.TenantClaim{}, err + } + for _, claim := range admin { + if claim.Name == tenant { + return claim, nil + } + } + return tenancyv1alpha1.TenantClaim{}, apierrors.NewForbidden( + tenancyv1alpha1.Resource("memberships"), "", + fmt.Errorf("you are not an admin of tenant %q", tenant)) +} + +// lastTenantAdmin reports whether exactly one tenant-wide admin grant +// covers the tenant. +func lastTenantAdmin(grants []directory.NamedMembership, tenant string) bool { + count := 0 + for _, g := range grants { + if g.Tenant == tenant && g.Project == "" && g.Role == string(tenancyv1alpha1.RoleAdmin) { + count++ + } + } + return count <= 1 +} + +// membershipObject renders the directory's projection back as the API +// object it was mirrored from. +func membershipObject(m directory.NamedMembership) tenancyv1alpha1.Membership { + return tenancyv1alpha1.Membership{ + ObjectMeta: metav1.ObjectMeta{Name: m.Name}, + Spec: tenancyv1alpha1.MembershipSpec{ + Subject: m.Subject, + Role: tenancyv1alpha1.Role(m.Role), + Tenant: m.Tenant, + Project: m.Project, + }, + } +} + +func userName(u user.Info) string { + if u == nil { + return "" + } + return u.GetName() +} + +// noEndpoints renders no URL, for the paths that do not need one. +func noEndpoints(string) string { return "" } + +// validateSpec checks what the caller controls. +func validateSpec(spec *tenancyv1alpha1.MembershipSpec) field.ErrorList { + var errs field.ErrorList + path := field.NewPath("spec") + + switch spec.Subject.Kind { + case tenancyv1alpha1.SubjectKindUser, tenancyv1alpha1.SubjectKindGroup: + default: + errs = append(errs, field.NotSupported(path.Child("subject", "kind"), spec.Subject.Kind, + []string{string(tenancyv1alpha1.SubjectKindUser), string(tenancyv1alpha1.SubjectKindGroup)})) + } + if spec.Subject.Name == "" { + errs = append(errs, field.Required(path.Child("subject", "name"), "who the grant is for")) + } else if naming.Slugify(spec.Subject.Name) == "" { + // The subject becomes part of an object name, so something of it has + // to survive slugification. + errs = append(errs, field.Invalid(path.Child("subject", "name"), spec.Subject.Name, + "must contain at least one letter or digit")) + } + switch spec.Role { + case tenancyv1alpha1.RoleView, tenancyv1alpha1.RoleEdit, tenancyv1alpha1.RoleAdmin: + default: + errs = append(errs, field.NotSupported(path.Child("role"), spec.Role, + []string{string(tenancyv1alpha1.RoleView), string(tenancyv1alpha1.RoleEdit), string(tenancyv1alpha1.RoleAdmin)})) + } + if spec.Tenant == "" { + errs = append(errs, field.Required(path.Child("tenant"), "which tenant the grant applies to")) + } + return errs +} diff --git a/tenancy/pkg/virtual/membership/storage_test.go b/tenancy/pkg/virtual/membership/storage_test.go new file mode 100644 index 0000000..b8a9a82 --- /dev/null +++ b/tenancy/pkg/virtual/membership/storage_test.go @@ -0,0 +1,372 @@ +/* +Copyright 2026 The kcp Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package membership + +import ( + "context" + "testing" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apiserver/pkg/authentication/user" + genericapirequest "k8s.io/apiserver/pkg/endpoints/request" + + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/pkg/directory" + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/pkg/naming" + tenancyv1alpha1 "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1" +) + +// This storage decides who may see and change other people's access, so +// what it refuses is the interesting part. + +// readyDirectory: alice administers acme, carol administers other, bob +// only views one of acme's projects, and mallory is a member of nothing. +func readyDirectory() *directory.Directory { + d := directory.New() + d.UpsertTenant(directory.Key{Cluster: "platform", Name: "acme"}, + directory.Tenant{DisplayName: "Acme", WorkspaceCluster: "ws1"}) + d.UpsertTenant(directory.Key{Cluster: "platform", Name: "other"}, + directory.Tenant{DisplayName: "Other", WorkspaceCluster: "ws2"}) + d.UpsertProject(directory.Key{Cluster: "ws1", Name: "web"}, + directory.Project{Tenant: "acme", WorkspaceCluster: "ws-web"}) + + d.UpsertMembership(directory.Key{Cluster: "ws1", Name: nameOf("alice", "acme", "")}, + directory.Membership{ + Subject: tenancyv1alpha1.Subject{Kind: tenancyv1alpha1.SubjectKindUser, Name: "alice"}, + Role: "admin", Tenant: "acme", + }) + // A second admin, so revoking one is not revoking the last. + d.UpsertMembership(directory.Key{Cluster: "ws1", Name: nameOf("dave", "acme", "")}, + directory.Membership{ + Subject: tenancyv1alpha1.Subject{Kind: tenancyv1alpha1.SubjectKindUser, Name: "dave"}, + Role: "admin", Tenant: "acme", + }) + d.UpsertMembership(directory.Key{Cluster: "ws1", Name: nameOf("bob", "acme", "web")}, + directory.Membership{ + Subject: tenancyv1alpha1.Subject{Kind: tenancyv1alpha1.SubjectKindUser, Name: "bob"}, + Role: "view", Tenant: "acme", Project: "web", + }) + d.UpsertMembership(directory.Key{Cluster: "ws2", Name: nameOf("carol", "other", "")}, + directory.Membership{ + Subject: tenancyv1alpha1.Subject{Kind: tenancyv1alpha1.SubjectKindUser, Name: "carol"}, + Role: "admin", Tenant: "other", + }) + d.SetReady() + return d +} + +// nameOf is the name the storage gives a user's grant. +func nameOf(subject, tenant, project string) string { + return naming.MembershipName(string(tenancyv1alpha1.SubjectKindUser), subject, tenant, project) +} + +func ctxWithUser(name string) context.Context { + return genericapirequest.WithUser(context.Background(), &user.DefaultInfo{Name: name}) +} + +// recorder captures what the storage asked to have written. +type recorder struct { + cluster string + grant *tenancyv1alpha1.Membership + created bool + creates int + deleted string + delCluster string + deletes int +} + +func (r *recorder) create(_ context.Context, cluster string, m *tenancyv1alpha1.Membership) (bool, error) { + r.creates++ + r.cluster, r.grant = cluster, m + return r.created, nil +} + +func (r *recorder) delete(_ context.Context, cluster, name string) error { + r.deletes++ + r.delCluster, r.deleted = cluster, name + return nil +} + +func (r *recorder) options() Options { return Options{Create: r.create, Delete: r.delete} } + +func grantFor(tenant, project, subject string, role tenancyv1alpha1.Role) *tenancyv1alpha1.Membership { + return &tenancyv1alpha1.Membership{ + Spec: tenancyv1alpha1.MembershipSpec{ + Subject: tenancyv1alpha1.Subject{Kind: tenancyv1alpha1.SubjectKindUser, Name: subject}, + Role: role, Tenant: tenant, Project: project, + }, + } +} + +func listFor(t *testing.T, r *REST, username string) *tenancyv1alpha1.MembershipList { + t.Helper() + obj, err := r.List(ctxWithUser(username), nil) + if err != nil { + t.Fatalf("List as %s: %v", username, err) + } + list, ok := obj.(*tenancyv1alpha1.MembershipList) + if !ok { + t.Fatalf("List returned %T", obj) + } + return list +} + +func TestAdminSeesEveryGrantInTheirTenant(t *testing.T) { + rec := &recorder{} + r := NewREST(readyDirectory(), rec.options()) + + list := listFor(t, r, "alice") + if len(list.Items) != 3 { + t.Fatalf("alice sees %d grants, want acme's 3: %+v", len(list.Items), list.Items) + } + // Including grants that are not her own — that is the point of + // administering access. + var subjects []string + for _, m := range list.Items { + subjects = append(subjects, m.Spec.Subject.Name) + if m.Spec.Tenant != "acme" { + t.Errorf("alice sees a grant on tenant %q", m.Spec.Tenant) + } + } + t.Logf("alice sees grants for %v", subjects) +} + +func TestNonAdminsSeeNothing(t *testing.T) { + rec := &recorder{} + r := NewREST(readyDirectory(), rec.options()) + + for _, who := range []string{"bob", "mallory"} { + list := listFor(t, r, who) + if len(list.Items) != 0 { + t.Errorf("%s sees %d grants, want none: %+v", who, len(list.Items), list.Items) + } + } +} + +func TestListIsScopedToTheTenantsYouAdminister(t *testing.T) { + rec := &recorder{} + r := NewREST(readyDirectory(), rec.options()) + + list := listFor(t, r, "carol") + if len(list.Items) != 1 || list.Items[0].Spec.Tenant != "other" { + t.Fatalf("carol sees %+v, want only her own tenant's grant", list.Items) + } +} + +func TestAdminGrantsInTheTenantWorkspace(t *testing.T) { + rec := &recorder{created: true} + r := NewREST(readyDirectory(), rec.options()) + + obj, err := r.Create(ctxWithUser("alice"), grantFor("acme", "", "erin@example.com", tenancyv1alpha1.RoleEdit), nil, nil) + if err != nil { + t.Fatalf("Create: %v", err) + } + + // The cluster comes from the directory, never from the request. + if rec.cluster != "ws1" { + t.Errorf("wrote to cluster %q, want the tenant's own ws1", rec.cluster) + } + // The name is derived, so granting the same access twice is one object. + if rec.grant.Name != nameOf("erin@example.com", "acme", "") { + t.Errorf("derived name %q", rec.grant.Name) + } + if got := obj.(*tenancyv1alpha1.Membership).Name; got != rec.grant.Name { + t.Errorf("returned name %q, want %q", got, rec.grant.Name) + } +} + +func TestCallerCannotChooseTheObjectName(t *testing.T) { + rec := &recorder{created: true} + r := NewREST(readyDirectory(), rec.options()) + + grant := grantFor("acme", "", "erin@example.com", tenancyv1alpha1.RoleView) + grant.Name = "something-else" + if _, err := r.Create(ctxWithUser("alice"), grant, nil, nil); err != nil { + t.Fatalf("Create: %v", err) + } + if rec.grant.Name != nameOf("erin@example.com", "acme", "") { + t.Errorf("name %q followed the request instead of the grant", rec.grant.Name) + } +} + +func TestNonAdminCannotGrant(t *testing.T) { + for _, who := range []string{"bob", "mallory"} { + rec := &recorder{} + r := NewREST(readyDirectory(), rec.options()) + + _, err := r.Create(ctxWithUser(who), grantFor("acme", "", "erin", tenancyv1alpha1.RoleAdmin), nil, nil) + if !apierrors.IsForbidden(err) { + t.Errorf("%s granting: %v, want Forbidden", who, err) + } + if rec.creates != 0 { + t.Errorf("%s reached the writer", who) + } + } +} + +func TestAdminOfOneTenantCannotGrantInAnother(t *testing.T) { + rec := &recorder{} + r := NewREST(readyDirectory(), rec.options()) + + // carol administers "other", and must not be able to reach "acme" — + // nor learn from the refusal whether it exists. + _, err := r.Create(ctxWithUser("carol"), grantFor("acme", "", "carol", tenancyv1alpha1.RoleAdmin), nil, nil) + if !apierrors.IsForbidden(err) { + t.Fatalf("cross-tenant grant: %v, want Forbidden", err) + } + if rec.creates != 0 { + t.Error("cross-tenant grant reached the writer") + } +} + +func TestGrantOnAnUnknownProjectIsRefused(t *testing.T) { + rec := &recorder{} + r := NewREST(readyDirectory(), rec.options()) + + _, err := r.Create(ctxWithUser("alice"), grantFor("acme", "nope", "erin", tenancyv1alpha1.RoleView), nil, nil) + if !apierrors.IsInvalid(err) { + t.Fatalf("grant on a missing project: %v, want Invalid", err) + } + if rec.creates != 0 { + t.Error("it reached the writer anyway") + } +} + +func TestInvalidGrantsAreRefusedBeforeTheWrite(t *testing.T) { + cases := map[string]*tenancyv1alpha1.Membership{ + "no subject": grantFor("acme", "", "", tenancyv1alpha1.RoleView), + "unsluggable subject": grantFor("acme", "", "!!!", tenancyv1alpha1.RoleView), + "unknown role": grantFor("acme", "", "erin", tenancyv1alpha1.Role("root")), + "no tenant": grantFor("", "", "erin", tenancyv1alpha1.RoleView), + } + for name, grant := range cases { + rec := &recorder{} + r := NewREST(readyDirectory(), rec.options()) + + _, err := r.Create(ctxWithUser("alice"), grant, nil, nil) + if !apierrors.IsInvalid(err) { + t.Errorf("%s: %v, want Invalid", name, err) + } + if rec.creates != 0 { + t.Errorf("%s: reached the writer", name) + } + } +} + +func TestAdminRevokesAGrant(t *testing.T) { + rec := &recorder{} + r := NewREST(readyDirectory(), rec.options()) + + _, deleted, err := r.Delete(ctxWithUser("alice"), nameOf("bob", "acme", "web"), nil, nil) + if err != nil { + t.Fatalf("Delete: %v", err) + } + if !deleted { + t.Error("Delete reported nothing removed") + } + if rec.delCluster != "ws1" || rec.deleted != nameOf("bob", "acme", "web") { + t.Errorf("deleted %q in %q", rec.deleted, rec.delCluster) + } +} + +func TestTheLastAdminCannotBeRevoked(t *testing.T) { + d := readyDirectory() + // Leave acme with a single admin. + d.RemoveMembership(directory.Key{Cluster: "ws1", Name: nameOf("dave", "acme", "")}) + + rec := &recorder{} + r := NewREST(d, rec.options()) + + _, _, err := r.Delete(ctxWithUser("alice"), nameOf("alice", "acme", ""), nil, nil) + if !apierrors.IsForbidden(err) { + t.Fatalf("revoking the last admin: %v, want Forbidden", err) + } + if rec.deletes != 0 { + t.Error("it reached the writer, leaving the tenant unadministerable") + } +} + +func TestTheLastAdminCannotBeDemoted(t *testing.T) { + d := readyDirectory() + d.RemoveMembership(directory.Key{Cluster: "ws1", Name: nameOf("dave", "acme", "")}) + + rec := &recorder{} + r := NewREST(d, rec.options()) + + _, err := r.Create(ctxWithUser("alice"), grantFor("acme", "", "alice", tenancyv1alpha1.RoleView), nil, nil) + if !apierrors.IsForbidden(err) { + t.Fatalf("demoting the last admin: %v, want Forbidden", err) + } + if rec.creates != 0 { + t.Error("it reached the writer, leaving the tenant without an admin") + } +} + +func TestAnAdminCanBeDemotedWhenAnotherRemains(t *testing.T) { + rec := &recorder{} + r := NewREST(readyDirectory(), rec.options()) + + if _, err := r.Create(ctxWithUser("alice"), grantFor("acme", "", "dave", tenancyv1alpha1.RoleView), nil, nil); err != nil { + t.Fatalf("demoting dave while alice is still admin: %v", err) + } +} + +func TestRevokingSomethingYouDoNotAdministerIsNotFound(t *testing.T) { + rec := &recorder{} + r := NewREST(readyDirectory(), rec.options()) + + // carol administers another tenant: acme's grants are not hers to see, + // so they are reported as absent rather than refused. + _, _, err := r.Delete(ctxWithUser("carol"), nameOf("bob", "acme", "web"), nil, nil) + if !apierrors.IsNotFound(err) { + t.Fatalf("cross-tenant revoke: %v, want NotFound", err) + } + if rec.deletes != 0 { + t.Error("cross-tenant revoke reached the writer") + } +} + +func TestReadOnlyDeploymentRefusesWrites(t *testing.T) { + r := NewREST(readyDirectory(), Options{}) + + if _, err := r.Create(ctxWithUser("alice"), grantFor("acme", "", "erin", tenancyv1alpha1.RoleView), nil, nil); !apierrors.IsServiceUnavailable(err) { + t.Errorf("Create without a writer: %v, want ServiceUnavailable", err) + } + if _, _, err := r.Delete(ctxWithUser("alice"), nameOf("bob", "acme", "web"), nil, nil); !apierrors.IsServiceUnavailable(err) { + t.Errorf("Delete without a writer: %v, want ServiceUnavailable", err) + } +} + +func TestAnUnsyncedDirectoryAnswersNothing(t *testing.T) { + rec := &recorder{} + r := NewREST(directory.New(), rec.options()) + + if _, err := r.List(ctxWithUser("alice"), nil); !apierrors.IsServiceUnavailable(err) { + t.Errorf("List before sync: %v, want ServiceUnavailable", err) + } +} + +func TestGetOnlyReachesYourOwnTenants(t *testing.T) { + rec := &recorder{} + r := NewREST(readyDirectory(), rec.options()) + + if _, err := r.Get(ctxWithUser("alice"), nameOf("bob", "acme", "web"), nil); err != nil { + t.Fatalf("alice getting a grant in acme: %v", err) + } + if _, err := r.Get(ctxWithUser("carol"), nameOf("bob", "acme", "web"), nil); !apierrors.IsNotFound(err) { + t.Errorf("carol getting a grant in acme: %v, want NotFound", err) + } +} diff --git a/tenancy/pkg/virtual/selfprojectrequest/storage.go b/tenancy/pkg/virtual/selfprojectrequest/storage.go new file mode 100644 index 0000000..1b6d88d --- /dev/null +++ b/tenancy/pkg/virtual/selfprojectrequest/storage.go @@ -0,0 +1,219 @@ +/* +Copyright 2026 The kcp Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package selfprojectrequest implements the one write the tenancy virtual +// workspace performs on a caller's behalf: creating a project in a tenant +// the caller administers. +// +// Everything else this component serves is a read of the caller's own +// state. This is a write, so it is worth being explicit about why it is +// mediated rather than delegated: +// +// Projects live in their tenant's workspace, which is also where the +// Memberships that decide who may reach what live. Granting a tenant +// admin RBAC there to create projects would hand them the records +// governing their own access. The virtual workspace therefore holds the +// only credential into that tier, and offers exactly one operation +// through it — create a project — gated on the caller's own admin +// Membership as the directory already reports it. +// +// The mediation is narrow on purpose: one verb, one kind, one field the +// caller controls. A caller cannot name a workspace, choose a cluster, or +// touch anything else in the tenant tier. +package selfprojectrequest + +import ( + "context" + "fmt" + "slices" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/validation" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/util/validation/field" + genericapirequest "k8s.io/apiserver/pkg/endpoints/request" + "k8s.io/apiserver/pkg/registry/rest" + "k8s.io/klog/v2" + + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/pkg/directory" + tenancyv1alpha1 "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1" +) + +// CreateProjectFunc creates a Project in one tenant's workspace. The +// server supplies it, because how the virtual workspace reaches that +// workspace — through the tenancy export — is a detail of the deployment +// rather than of the API. +type CreateProjectFunc func(ctx context.Context, cluster string, project *tenancyv1alpha1.Project) (created bool, err error) + +// REST answers SelfProjectRequest creates. +type REST struct { + directory *directory.Directory + create CreateProjectFunc +} + +var ( + _ rest.Storage = &REST{} + _ rest.Creater = &REST{} + _ rest.Scoper = &REST{} + _ rest.SingularNameProvider = &REST{} +) + +// NewREST returns the storage. create may be nil, in which case the +// resource reports that project creation is not configured rather than +// pretending to work. +func NewREST(d *directory.Directory, create CreateProjectFunc) *REST { + return &REST{directory: d, create: create} +} + +func (r *REST) New() runtime.Object { return &tenancyv1alpha1.SelfProjectRequest{} } + +func (r *REST) Destroy() {} + +func (r *REST) NamespaceScoped() bool { return false } + +func (r *REST) GetSingularName() string { return "selfprojectrequest" } + +// Create authorizes the request against the caller's own membership and, +// if it holds, creates the project. +func (r *REST) Create(ctx context.Context, obj runtime.Object, _ rest.ValidateObjectFunc, _ *metav1.CreateOptions) (runtime.Object, error) { + req, ok := obj.(*tenancyv1alpha1.SelfProjectRequest) + if !ok { + return nil, apierrors.NewBadRequest(fmt.Sprintf("not a SelfProjectRequest: %T", obj)) + } + if r.create == nil { + return nil, apierrors.NewServiceUnavailable( + "this virtual workspace was started without project creation; it can only answer reviews") + } + if !r.directory.Ready() { + return nil, apierrors.NewServiceUnavailable("tenancy directory is not ready; try again shortly") + } + + user, ok := genericapirequest.UserFrom(ctx) + if !ok { + return nil, apierrors.NewUnauthorized("no user present in request context") + } + + if errs := validateSpec(&req.Spec); len(errs) > 0 { + return nil, apierrors.NewInvalid( + tenancyv1alpha1.SchemeGroupVersion.WithKind("SelfProjectRequest").GroupKind(), + req.Name, errs) + } + + // The caller's own answer decides: admin on that tenant, or nothing. + // Deliberately the same view `whoami` returns, so what a person is + // told they can do and what they can do cannot drift apart. + // noEndpoints: this path needs the caller's roles and the tenant's + // cluster, not URLs, and ReviewFor calls the renderer for every + // workspace it reports. + claim, ok := tenantFor( + r.directory.ReviewFor(user.GetName(), user.GetGroups(), noEndpoints), + req.Spec.Tenant, + ) + if !ok { + // Not revealing whether the tenant exists: to a non-member the two + // cases are the same, and saying which would leak the tenant list. + return nil, apierrors.NewForbidden( + tenancyv1alpha1.Resource("selfprojectrequests"), req.Spec.Name, + fmt.Errorf("you are not an admin of tenant %q", req.Spec.Tenant)) + } + if !slices.Contains(claim.Roles, string(tenancyv1alpha1.RoleAdmin)) { + return nil, apierrors.NewForbidden( + tenancyv1alpha1.Resource("selfprojectrequests"), req.Spec.Name, + fmt.Errorf("creating a project in tenant %q needs the admin role; you hold %v", + req.Spec.Tenant, claim.Roles)) + } + if claim.Cluster == "" { + return nil, apierrors.NewServiceUnavailable( + fmt.Sprintf("tenant %q has no workspace yet; try again once it is ready", req.Spec.Tenant)) + } + + displayName := req.Spec.DisplayName + if displayName == "" { + displayName = req.Spec.Name + } + + project := &tenancyv1alpha1.Project{ + ObjectMeta: metav1.ObjectMeta{Name: req.Spec.Name}, + Spec: tenancyv1alpha1.ProjectSpec{ + Tenant: req.Spec.Tenant, + DisplayName: displayName, + Description: req.Spec.Description, + }, + } + + created, err := r.create(ctx, claim.Cluster, project) + if err != nil { + return nil, err + } + + logger := klog.FromContext(ctx) + logger.V(2).Info("answered SelfProjectRequest", + "username", user.GetName(), + "tenant", req.Spec.Tenant, + "project", req.Spec.Name, + "cluster", claim.Cluster, + "created", created, + ) + + out := req.DeepCopy() + out.Status = tenancyv1alpha1.SelfProjectRequestStatus{ + Created: created, + Project: req.Spec.Name, + Message: message(created, req.Spec.Name, req.Spec.Tenant), + } + return out, nil +} + +func message(created bool, project, tenant string) string { + if created { + return fmt.Sprintf("project %q created in tenant %q", project, tenant) + } + return fmt.Sprintf("project %q already exists in tenant %q", project, tenant) +} + +// noEndpoints renders no URL, for the paths that do not need one. +func noEndpoints(string) string { return "" } + +// tenantFor finds the caller's claim on one tenant. +func tenantFor(claims []tenancyv1alpha1.TenantClaim, name string) (tenancyv1alpha1.TenantClaim, bool) { + for _, c := range claims { + if c.Name == name { + return c, true + } + } + return tenancyv1alpha1.TenantClaim{}, false +} + +// validateSpec checks what the caller controls. The name becomes an +// object name and seeds a workspace name, so it has to be a DNS label +// rather than whatever was typed. +func validateSpec(spec *tenancyv1alpha1.SelfProjectRequestSpec) field.ErrorList { + var errs field.ErrorList + path := field.NewPath("spec") + + if spec.Tenant == "" { + errs = append(errs, field.Required(path.Child("tenant"), "which tenant to create the project in")) + } + if spec.Name == "" { + errs = append(errs, field.Required(path.Child("name"), "the project's name")) + } else { + for _, msg := range validation.NameIsDNSLabel(spec.Name, false) { + errs = append(errs, field.Invalid(path.Child("name"), spec.Name, msg)) + } + } + return errs +} diff --git a/tenancy/pkg/virtual/selfprojectrequest/storage_test.go b/tenancy/pkg/virtual/selfprojectrequest/storage_test.go new file mode 100644 index 0000000..97665b3 --- /dev/null +++ b/tenancy/pkg/virtual/selfprojectrequest/storage_test.go @@ -0,0 +1,201 @@ +/* +Copyright 2026 The kcp Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package selfprojectrequest + +import ( + "context" + "testing" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apiserver/pkg/authentication/user" + genericapirequest "k8s.io/apiserver/pkg/endpoints/request" + + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/pkg/directory" + tenancyv1alpha1 "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1" +) + +// This storage holds a credential its callers do not, so what it refuses +// matters more than what it allows. The tests are mostly refusals. + +// readyDirectory: alice administers acme, bob only views one of its +// projects, and mallory is a member of nothing. +func readyDirectory() *directory.Directory { + d := directory.New() + d.UpsertTenant(directory.Key{Cluster: "platform", Name: "acme"}, + directory.Tenant{DisplayName: "Acme", WorkspaceCluster: "ws1"}) + d.UpsertProject(directory.Key{Cluster: "ws1", Name: "web"}, + directory.Project{Tenant: "acme", WorkspaceCluster: "ws-web"}) + d.UpsertMembership(directory.Key{Cluster: "ws1", Name: "m-alice"}, + directory.Membership{ + Subject: tenancyv1alpha1.Subject{Kind: tenancyv1alpha1.SubjectKindUser, Name: "alice"}, + Role: "admin", Tenant: "acme", + }) + d.UpsertMembership(directory.Key{Cluster: "ws1", Name: "m-bob"}, + directory.Membership{ + Subject: tenancyv1alpha1.Subject{Kind: tenancyv1alpha1.SubjectKindUser, Name: "bob"}, + Role: "view", Tenant: "acme", Project: "web", + }) + d.SetReady() + return d +} + +func ctxWithUser(name string) context.Context { + return genericapirequest.WithUser(context.Background(), &user.DefaultInfo{Name: name}) +} + +// recorder captures what the storage asked to have created. +type recorder struct { + cluster string + project *tenancyv1alpha1.Project + created bool + calls int +} + +func (r *recorder) create(_ context.Context, cluster string, p *tenancyv1alpha1.Project) (bool, error) { + r.calls++ + r.cluster, r.project = cluster, p + return r.created, nil +} + +func request(tenant, name string) *tenancyv1alpha1.SelfProjectRequest { + return &tenancyv1alpha1.SelfProjectRequest{ + Spec: tenancyv1alpha1.SelfProjectRequestSpec{Tenant: tenant, Name: name}, + } +} + +func TestAdminCreatesInTheTenantWorkspace(t *testing.T) { + rec := &recorder{created: true} + r := NewREST(readyDirectory(), rec.create) + + obj, err := r.Create(ctxWithUser("alice"), request("acme", "analytics"), nil, nil) + if err != nil { + t.Fatalf("Create: %v", err) + } + + // The cluster comes from the directory, never from the request: a + // caller cannot aim this credential at a workspace of their choosing. + if rec.cluster != "ws1" { + t.Errorf("created in cluster %q, want the tenant's own ws1", rec.cluster) + } + if rec.project.Name != "analytics" || rec.project.Spec.Tenant != "acme" { + t.Errorf("created %+v", rec.project) + } + // An unset display name should not reach the object empty. + if rec.project.Spec.DisplayName != "analytics" { + t.Errorf("displayName = %q, want it defaulted to the name", rec.project.Spec.DisplayName) + } + + out := obj.(*tenancyv1alpha1.SelfProjectRequest) + if !out.Status.Created || out.Status.Project != "analytics" { + t.Errorf("status = %+v", out.Status) + } +} + +func TestExistingProjectIsNotAnError(t *testing.T) { + // Asking for what already exists is the same request, answered. + rec := &recorder{created: false} + r := NewREST(readyDirectory(), rec.create) + + obj, err := r.Create(ctxWithUser("alice"), request("acme", "web"), nil, nil) + if err != nil { + t.Fatalf("Create: %v", err) + } + if out := obj.(*tenancyv1alpha1.SelfProjectRequest); out.Status.Created { + t.Errorf("status says created, want created=false for an existing project") + } +} + +func TestNonAdminMemberIsRefused(t *testing.T) { + rec := &recorder{} + r := NewREST(readyDirectory(), rec.create) + + _, err := r.Create(ctxWithUser("bob"), request("acme", "analytics"), nil, nil) + if !apierrors.IsForbidden(err) { + t.Fatalf("err = %v, want Forbidden", err) + } + if rec.calls != 0 { + t.Errorf("the credential was used %d times for a refused request", rec.calls) + } +} + +func TestStrangerIsRefused(t *testing.T) { + rec := &recorder{} + r := NewREST(readyDirectory(), rec.create) + + _, err := r.Create(ctxWithUser("mallory"), request("acme", "analytics"), nil, nil) + if !apierrors.IsForbidden(err) { + t.Fatalf("err = %v, want Forbidden", err) + } + // The refusal must not say whether the tenant exists: to a + // non-member, "no such tenant" and "not your tenant" are the same. + if got := err.Error(); !contains(got, "not an admin") { + t.Errorf("message %q reveals more than membership", got) + } + if rec.calls != 0 { + t.Errorf("the credential was used for a stranger's request") + } +} + +func TestUnknownTenantLooksLikeNonMembership(t *testing.T) { + rec := &recorder{} + r := NewREST(readyDirectory(), rec.create) + + _, err := r.Create(ctxWithUser("alice"), request("no-such-tenant", "x"), nil, nil) + if !apierrors.IsForbidden(err) { + t.Fatalf("err = %v, want Forbidden rather than NotFound", err) + } +} + +func TestNameMustBeAWorkspaceName(t *testing.T) { + rec := &recorder{} + r := NewREST(readyDirectory(), rec.create) + + // The name seeds a workspace name, so it has to be a DNS label. + _, err := r.Create(ctxWithUser("alice"), request("acme", "Not A Label"), nil, nil) + if !apierrors.IsInvalid(err) { + t.Fatalf("err = %v, want Invalid", err) + } + if rec.calls != 0 { + t.Errorf("an invalid request reached the credential") + } +} + +func TestUnconfiguredCreationIsHonest(t *testing.T) { + // A server without the writer should say so rather than refuse as if + // it were an authorization decision. + r := NewREST(readyDirectory(), nil) + + _, err := r.Create(ctxWithUser("alice"), request("acme", "analytics"), nil, nil) + if !apierrors.IsServiceUnavailable(err) { + t.Fatalf("err = %v, want ServiceUnavailable", err) + } +} + +func contains(haystack, needle string) bool { + return len(haystack) >= len(needle) && (haystack == needle || + len(needle) == 0 || + indexOf(haystack, needle) >= 0) +} + +func indexOf(haystack, needle string) int { + for i := 0; i+len(needle) <= len(haystack); i++ { + if haystack[i:i+len(needle)] == needle { + return i + } + } + return -1 +} diff --git a/tenancy/pkg/virtual/selftenancyreview/virtualworkspace.go b/tenancy/pkg/virtual/selftenancyreview/virtualworkspace.go index 0f2cdb2..21e09e6 100644 --- a/tenancy/pkg/virtual/selftenancyreview/virtualworkspace.go +++ b/tenancy/pkg/virtual/selftenancyreview/virtualworkspace.go @@ -30,23 +30,45 @@ import ( "github.com/kcp-dev/contrib-virtual-workspaces/access/pkg/virtual" "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/pkg/directory" + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/pkg/virtual/membership" + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/pkg/virtual/selfprojectrequest" + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/pkg/virtual/selftenantrequest" tenancyv1alpha1 "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1" ) const VirtualWorkspaceName = "tenancy" // RootPath is the URL prefix the front-proxy routes to this VW. The review -// is served at RootPath + /apis/tenancy.contrib.kcp.io/v1alpha1/selftenancyreviews. +// is served at RootPath + /apis/tenancy.platform.kcp.io/v1alpha1/selftenancyreviews. const RootPath = "/services/" + VirtualWorkspaceName +// Config is what the server supplies: the shared directory every answer +// is read from, how to render a workspace's URL, and the write paths — +// each one a function, because how this server reaches another workspace +// is a property of the deployment rather than of the API. +type Config struct { + Directory *directory.Directory + EndpointFor func(cluster string) string + + CreateProject selfprojectrequest.CreateProjectFunc + + Tenants selftenantrequest.Options + CreateTenant selftenantrequest.CreateTenantFunc + + Memberships membership.Options +} + // NewVirtualWorkspace builds the tenancy VW: a fixed-group-version -// delegated apiserver serving tenancy.contrib.kcp.io/v1alpha1 with the -// selftenancyreviews REST storage, answered from the shared directory. +// delegated apiserver serving tenancy.platform.kcp.io/v1alpha1, answered +// from the shared directory. // -// The authorizer only requires an authenticated caller: the review is a -// self-review, so the directory — not the authorizer — decides what the -// answer contains. -func NewVirtualWorkspace(d *directory.Directory, endpointFor func(cluster string) string) rootapiserver.NamedVirtualWorkspace { +// The authorizer only requires an authenticated caller. That is not a gap: +// every resource here decides for itself what the caller may see or do, +// from the caller's own Memberships as the directory reports them. A +// coarser authorizer would have to be told about tenants, which is exactly +// the knowledge the directory already holds. +func NewVirtualWorkspace(cfg Config) rootapiserver.NamedVirtualWorkspace { + d := cfg.Directory vw := &fixedgvs.FixedGroupVersionsVirtualWorkspace{ RootPathResolver: framework.RootPathResolverFunc(func(urlPath string, ctx context.Context) (bool, string, context.Context) { if urlPath != RootPath && !strings.HasPrefix(urlPath, RootPath+"/") { @@ -68,7 +90,28 @@ func NewVirtualWorkspace(d *directory.Directory, endpointFor func(cluster string BootstrapRestResources: func(_ genericapiserver.CompletedConfig) (map[string]fixedgvs.RestStorageBuilder, error) { return map[string]fixedgvs.RestStorageBuilder{ "selftenancyreviews": func(_ genericapiserver.CompletedConfig) (restStorage.Storage, error) { - return NewREST(d, endpointFor), nil + return NewREST(d, cfg.EndpointFor), nil + }, + // Creating a project in a tenant the caller + // administers. Authorized against the caller's own + // Membership, performed with this server's + // credential, because the tenant tier is + // deliberately closed to its own members. + "selfprojectrequests": func(_ genericapiserver.CompletedConfig) (restStorage.Storage, error) { + return selfprojectrequest.NewREST(d, cfg.CreateProject), nil + }, + // How someone with no membership at all gets + // started: there is nothing to authorize against, + // so the deployment decides whether this is + // offered. + "selftenantrequests": func(_ genericapiserver.CompletedConfig) (restStorage.Storage, error) { + return selftenantrequest.NewREST(cfg.Tenants, cfg.CreateTenant), nil + }, + // Managing who else may reach what. Mediated for + // the same reason projects are: the grants live in + // the workspace their holders may not enter. + "memberships": func(_ genericapiserver.CompletedConfig) (restStorage.Storage, error) { + return membership.NewREST(d, cfg.Memberships), nil }, }, nil }, diff --git a/tenancy/pkg/virtual/selftenantrequest/storage.go b/tenancy/pkg/virtual/selftenantrequest/storage.go new file mode 100644 index 0000000..db1bde1 --- /dev/null +++ b/tenancy/pkg/virtual/selftenantrequest/storage.go @@ -0,0 +1,185 @@ +/* +Copyright 2026 The kcp Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package selftenantrequest lets a caller with nothing get their first +// tenant. +// +// It closes the one gap that made the model unusable for a new person: +// every other self-service path here is authorized against a Membership, +// and someone who has just signed in has none. There is no login hook to +// hang this on either — the OIDC redirect goes from the browser to the +// identity provider and back, and this server only ever sees the +// resulting token on ordinary requests — so a new user has to ask for a +// tenant explicitly. That is deliberate rather than a limitation: +// provisioning as a side effect of a read would make listing tenants a +// write, and a monitoring probe would materialize workspaces. +// +// Because there is no Membership to check, the gate is configuration: +// self-service is off unless the deployment turns it on, and can be +// restricted to groups the identity provider asserts. A deployment that +// leaves it off is not broken — it has decided that handing out tenants +// is an administrator's job. +// +// The caller names the tenant and nothing else. The first admin is the +// caller, set here rather than read from the request, so nobody can ask +// for a tenant administered by someone else. +package selftenantrequest + +import ( + "context" + "fmt" + "slices" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/validation" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/util/validation/field" + genericapirequest "k8s.io/apiserver/pkg/endpoints/request" + "k8s.io/apiserver/pkg/registry/rest" + "k8s.io/klog/v2" + + tenancyv1alpha1 "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1" +) + +// CreateTenantFunc creates a Tenant in the store workspace. The server +// supplies it, because where the records live is a deployment detail. +type CreateTenantFunc func(ctx context.Context, tenant *tenancyv1alpha1.Tenant) (created bool, err error) + +// Options configures who may ask. +type Options struct { + // Enabled turns self-service on. Off means the resource answers that + // it is not offered here, which is a decision rather than a failure. + Enabled bool + // Groups, when set, restricts self-service to callers in at least one + // of them — the groups the identity provider asserts, as kcp sees + // them. Empty means any authenticated caller. + Groups []string +} + +// REST answers SelfTenantRequest creates. +type REST struct { + opts Options + create CreateTenantFunc +} + +var ( + _ rest.Storage = &REST{} + _ rest.Creater = &REST{} + _ rest.Scoper = &REST{} + _ rest.SingularNameProvider = &REST{} +) + +func NewREST(opts Options, create CreateTenantFunc) *REST { + return &REST{opts: opts, create: create} +} + +func (r *REST) New() runtime.Object { return &tenancyv1alpha1.SelfTenantRequest{} } + +func (r *REST) Destroy() {} + +func (r *REST) NamespaceScoped() bool { return false } + +func (r *REST) GetSingularName() string { return "selftenantrequest" } + +// Create makes the tenant, with the caller as its first admin. +func (r *REST) Create(ctx context.Context, obj runtime.Object, _ rest.ValidateObjectFunc, _ *metav1.CreateOptions) (runtime.Object, error) { + req, ok := obj.(*tenancyv1alpha1.SelfTenantRequest) + if !ok { + return nil, apierrors.NewBadRequest(fmt.Sprintf("not a SelfTenantRequest: %T", obj)) + } + if r.create == nil || !r.opts.Enabled { + return nil, apierrors.NewServiceUnavailable( + "self-service tenants are not enabled here; an administrator creates tenants") + } + + user, ok := genericapirequest.UserFrom(ctx) + if !ok { + return nil, apierrors.NewUnauthorized("no user present in request context") + } + + if len(r.opts.Groups) > 0 && !slices.ContainsFunc(user.GetGroups(), func(g string) bool { + return slices.Contains(r.opts.Groups, g) + }) { + return nil, apierrors.NewForbidden( + tenancyv1alpha1.Resource("selftenantrequests"), req.Spec.Name, + fmt.Errorf("self-service tenants are limited to %v", r.opts.Groups)) + } + + if errs := validateSpec(&req.Spec); len(errs) > 0 { + return nil, apierrors.NewInvalid( + tenancyv1alpha1.SchemeGroupVersion.WithKind("SelfTenantRequest").GroupKind(), + req.Spec.Name, errs) + } + + displayName := req.Spec.DisplayName + if displayName == "" { + displayName = req.Spec.Name + } + + tenant := &tenancyv1alpha1.Tenant{ + ObjectMeta: metav1.ObjectMeta{Name: req.Spec.Name}, + Spec: tenancyv1alpha1.TenantSpec{ + DisplayName: displayName, + Description: req.Spec.Description, + // The caller, never what the request asked for: a tenant you + // requested is a tenant you administer, and not one you can + // hand to somebody else on the way in. + FirstAdmin: user.GetName(), + }, + } + + created, err := r.create(ctx, tenant) + if err != nil { + return nil, err + } + + klog.FromContext(ctx).V(2).Info("answered SelfTenantRequest", + "username", user.GetName(), "tenant", req.Spec.Name, "created", created) + + out := req.DeepCopy() + out.Status = tenancyv1alpha1.SelfTenantRequestStatus{ + Created: created, + Tenant: req.Spec.Name, + Message: message(created, req.Spec.Name, user.GetName()), + } + return out, nil +} + +func message(created bool, tenant, admin string) string { + if created { + return fmt.Sprintf("tenant %q created; %s is its admin once the workspace is ready", tenant, admin) + } + // Someone else may hold it. Saying so is better than implying it is + // theirs, and the review will show whether they can reach it. + return fmt.Sprintf("tenant %q already exists", tenant) +} + +// validateSpec checks what the caller controls. The name becomes an +// object name and seeds a workspace name, so it has to be a DNS label. +func validateSpec(spec *tenancyv1alpha1.SelfTenantRequestSpec) field.ErrorList { + var errs field.ErrorList + path := field.NewPath("spec") + + if spec.Name == "" { + errs = append(errs, field.Required(path.Child("name"), "the tenant's name")) + return errs + } + for _, msg := range validation.NameIsDNSLabel(spec.Name, false) { + errs = append(errs, field.Invalid(path.Child("name"), spec.Name, msg)) + } + return errs +} diff --git a/tenancy/pkg/virtual/selftenantrequest/storage_test.go b/tenancy/pkg/virtual/selftenantrequest/storage_test.go new file mode 100644 index 0000000..7bef402 --- /dev/null +++ b/tenancy/pkg/virtual/selftenantrequest/storage_test.go @@ -0,0 +1,162 @@ +/* +Copyright 2026 The kcp Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package selftenantrequest + +import ( + "context" + "testing" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apiserver/pkg/authentication/user" + genericapirequest "k8s.io/apiserver/pkg/endpoints/request" + + tenancyv1alpha1 "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1" +) + +// This is the one endpoint with no Membership to authorize against, so +// the tests are about the gate and about what the caller cannot choose. + +type recorder struct { + tenant *tenancyv1alpha1.Tenant + created bool + calls int +} + +func (r *recorder) create(_ context.Context, t *tenancyv1alpha1.Tenant) (bool, error) { + r.calls++ + r.tenant = t + return r.created, nil +} + +func ctxWithUser(name string, groups ...string) context.Context { + return genericapirequest.WithUser(context.Background(), &user.DefaultInfo{Name: name, Groups: groups}) +} + +func request(name string) *tenancyv1alpha1.SelfTenantRequest { + return &tenancyv1alpha1.SelfTenantRequest{ + Spec: tenancyv1alpha1.SelfTenantRequestSpec{Name: name}, + } +} + +func TestDisabledByDefault(t *testing.T) { + rec := &recorder{} + r := NewREST(Options{}, rec.create) + + _, err := r.Create(ctxWithUser("alice@example.com"), request("acme"), nil, nil) + if !apierrors.IsServiceUnavailable(err) { + t.Fatalf("err = %v, want ServiceUnavailable", err) + } + if rec.calls != 0 { + t.Errorf("a tenant was created while self-service was off") + } +} + +func TestEnabledCallerBecomesFirstAdmin(t *testing.T) { + rec := &recorder{created: true} + r := NewREST(Options{Enabled: true}, rec.create) + + obj, err := r.Create(ctxWithUser("alice@example.com"), request("acme"), nil, nil) + if err != nil { + t.Fatalf("Create: %v", err) + } + // A tenant nobody administers is unusable, so the caller must come out + // of this as its admin. + if rec.tenant.Spec.FirstAdmin != "alice@example.com" { + t.Errorf("firstAdmin = %q, want the caller", rec.tenant.Spec.FirstAdmin) + } + if rec.tenant.Spec.DisplayName != "acme" { + t.Errorf("displayName = %q, want it defaulted to the name", rec.tenant.Spec.DisplayName) + } + if out := obj.(*tenancyv1alpha1.SelfTenantRequest); !out.Status.Created { + t.Errorf("status = %+v", out.Status) + } +} + +func TestCallerCannotNameSomeoneElseAsAdmin(t *testing.T) { + rec := &recorder{created: true} + r := NewREST(Options{Enabled: true}, rec.create) + + // There is no field for it, so the only way to try is to smuggle one + // in — and the server overwrites whatever arrived. + req := request("acme") + _, err := r.Create(ctxWithUser("mallory@example.com"), req, nil, nil) + if err != nil { + t.Fatalf("Create: %v", err) + } + if rec.tenant.Spec.FirstAdmin != "mallory@example.com" { + t.Errorf("firstAdmin = %q, want the authenticated caller", rec.tenant.Spec.FirstAdmin) + } +} + +func TestGroupRestriction(t *testing.T) { + rec := &recorder{created: true} + r := NewREST(Options{Enabled: true, Groups: []string{"staff"}}, rec.create) + + if _, err := r.Create(ctxWithUser("alice@example.com", "staff"), request("acme"), nil, nil); err != nil { + t.Fatalf("a caller in the group was refused: %v", err) + } + + _, err := r.Create(ctxWithUser("mallory@example.com", "others"), request("evil"), nil, nil) + if !apierrors.IsForbidden(err) { + t.Fatalf("err = %v, want Forbidden for a caller outside the groups", err) + } + if rec.calls != 1 { + t.Errorf("calls = %d, want only the permitted one", rec.calls) + } +} + +func TestExistingTenantIsNotClaimed(t *testing.T) { + // Someone else may already hold that name. The answer must not imply + // the caller now administers it. + rec := &recorder{created: false} + r := NewREST(Options{Enabled: true}, rec.create) + + obj, err := r.Create(ctxWithUser("mallory@example.com"), request("acme"), nil, nil) + if err != nil { + t.Fatalf("Create: %v", err) + } + out := obj.(*tenancyv1alpha1.SelfTenantRequest) + if out.Status.Created { + t.Errorf("status claims creation of an existing tenant") + } + if got := out.Status.Message; got != `tenant "acme" already exists` { + t.Errorf("message = %q, should not promise admin of someone else's tenant", got) + } +} + +func TestNameMustBeAWorkspaceName(t *testing.T) { + rec := &recorder{} + r := NewREST(Options{Enabled: true}, rec.create) + + _, err := r.Create(ctxWithUser("alice@example.com"), request("Not A Label"), nil, nil) + if !apierrors.IsInvalid(err) { + t.Fatalf("err = %v, want Invalid", err) + } + if rec.calls != 0 { + t.Errorf("an invalid request reached the credential") + } +} + +func TestUnauthenticatedIsRefused(t *testing.T) { + rec := &recorder{} + r := NewREST(Options{Enabled: true}, rec.create) + + _, err := r.Create(context.Background(), request("acme"), nil, nil) + if !apierrors.IsUnauthorized(err) { + t.Fatalf("err = %v, want Unauthorized", err) + } +} diff --git a/tenancy/sdk/apis/tenancy/v1alpha1/doc.go b/tenancy/sdk/apis/tenancy/v1alpha1/doc.go index cbca894..f38314b 100644 --- a/tenancy/sdk/apis/tenancy/v1alpha1/doc.go +++ b/tenancy/sdk/apis/tenancy/v1alpha1/doc.go @@ -15,7 +15,7 @@ limitations under the License. */ // Package v1alpha1 holds the API types for the tenancy component (group -// tenancy.contrib.kcp.io). +// tenancy.platform.kcp.io). // // Three persisted, cluster-scoped kinds — Tenant, Project and Membership — // are exported through an APIExport and bound into an organization @@ -25,5 +25,5 @@ limitations under the License. // identity a member of, and as what role?". // // +k8s:openapi-gen=true -// +groupName=tenancy.contrib.kcp.io +// +groupName=tenancy.platform.kcp.io package v1alpha1 diff --git a/tenancy/sdk/apis/tenancy/v1alpha1/register.go b/tenancy/sdk/apis/tenancy/v1alpha1/register.go index d9e8ee1..e7b83b2 100644 --- a/tenancy/sdk/apis/tenancy/v1alpha1/register.go +++ b/tenancy/sdk/apis/tenancy/v1alpha1/register.go @@ -22,7 +22,7 @@ import ( "k8s.io/apimachinery/pkg/runtime/schema" ) -const GroupName = "tenancy.contrib.kcp.io" +const GroupName = "tenancy.platform.kcp.io" var ( SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) @@ -48,6 +48,10 @@ func addKnownTypes(scheme *runtime.Scheme) error { &MembershipList{}, &SelfTenancyReview{}, &SelfTenancyReviewList{}, + &SelfProjectRequest{}, + &SelfProjectRequestList{}, + &SelfTenantRequest{}, + &SelfTenantRequestList{}, ) metav1.AddToGroupVersion(scheme, SchemeGroupVersion) return nil diff --git a/tenancy/sdk/apis/tenancy/v1alpha1/types.go b/tenancy/sdk/apis/tenancy/v1alpha1/types.go index b69c7cc..e6943d9 100644 --- a/tenancy/sdk/apis/tenancy/v1alpha1/types.go +++ b/tenancy/sdk/apis/tenancy/v1alpha1/types.go @@ -64,6 +64,7 @@ const ( // Subject identifies who a Membership is for. type Subject struct { // Kind is User or Group. + // +kubebuilder:validation:Enum=User;Group Kind SubjectKind `json:"kind"` // Name is the username or group name, compared verbatim against the // identity kcp authenticates. No issuer prefixes are added or stripped @@ -77,6 +78,9 @@ type Subject struct { // Tenant object lives in and reports it in Status. // // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +// +kubebuilder:object:root=true +// +kubebuilder:resource:scope=Cluster +// +kubebuilder:subresource:status type Tenant struct { metav1.TypeMeta `json:",inline"` // +optional @@ -96,6 +100,21 @@ type TenantSpec struct { // Description is free text for humans. // +optional Description string `json:"description,omitempty"` + // FirstAdmin is an identity granted the admin role on this tenant once + // its workspace is ready, as a Membership the operator creates. + // + // It exists because a tenant nobody administers is unusable, and the + // two writes cannot be one: the Membership lives in the tenant's own + // workspace, which does not exist when the Tenant is created. Naming + // the admin here lets whoever creates the tenant hand it over without + // waiting, and is what makes self-service possible — the virtual + // workspace sets it to the caller, so a caller cannot make someone + // else the admin of a tenant they asked for. + // + // Empty means nobody is seeded, which is the right answer when an + // administrator intends to grant access separately. + // +optional + FirstAdmin string `json:"firstAdmin,omitempty"` } // TenantStatus is the observed state of a Tenant. @@ -120,6 +139,7 @@ type TenantStatus struct { // TenantList is the list form of Tenant. // // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +// +kubebuilder:object:root=true type TenantList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` @@ -132,6 +152,9 @@ type TenantList struct { // project, project Memberships reach one. // // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +// +kubebuilder:object:root=true +// +kubebuilder:resource:scope=Cluster +// +kubebuilder:subresource:status type Project struct { metav1.TypeMeta `json:",inline"` // +optional @@ -177,6 +200,7 @@ type ProjectStatus struct { // ProjectList is the list form of Project. // // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +// +kubebuilder:object:root=true type ProjectList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` @@ -189,6 +213,9 @@ type ProjectList struct { // workspace; deleting the Membership removes that RBAC again. // // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +// +kubebuilder:object:root=true +// +kubebuilder:resource:scope=Cluster +// +kubebuilder:subresource:status type Membership struct { metav1.TypeMeta `json:",inline"` // +optional @@ -204,6 +231,7 @@ type MembershipSpec struct { // Subject is who the grant is for. Subject Subject `json:"subject"` // Role is the access level granted: view, edit or admin. + // +kubebuilder:validation:Enum=view;edit;admin Role Role `json:"role"` // Tenant names the Tenant (in the same workspace) the grant applies to. Tenant string `json:"tenant"` @@ -225,6 +253,7 @@ type MembershipStatus struct { // MembershipList is the list form of Membership. // // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +// +kubebuilder:object:root=true type MembershipList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` @@ -309,3 +338,131 @@ type SelfTenancyReviewList struct { Items []SelfTenancyReview `json:"items"` } + +// SelfProjectRequest asks for a project in a tenant the caller +// administers. It is the one write the tenancy virtual workspace does on +// a caller's behalf, and it exists because the alternative is worse: +// Projects live in the tenant's own workspace, which is the record store +// that decides who may reach what, so letting a tenant admin write there +// directly would hand them the Memberships governing themselves. +// +// The virtual workspace therefore holds the only credential into that +// tier. It authorizes the request against the caller's own Membership — +// admin on that tenant — and creates the Project itself. Nothing is +// relayed and no privilege is lent: a caller who is not an admin of the +// named tenant is refused, and one who is gets exactly one object +// created. +// +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +// +kubebuilder:object:root=true +type SelfProjectRequest struct { + metav1.TypeMeta `json:",inline"` + // +optional + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec SelfProjectRequestSpec `json:"spec"` + // +optional + Status SelfProjectRequestStatus `json:"status,omitempty"` +} + +// SelfProjectRequestSpec names the project to create. +type SelfProjectRequestSpec struct { + // Tenant is the tenant to create the project in. The caller must hold + // the admin role there. + Tenant string `json:"tenant"` + // Name is the project's object name, which also seeds its workspace + // name. + Name string `json:"name"` + // DisplayName is the project's human name. Defaults to Name. + // +optional + DisplayName string `json:"displayName,omitempty"` + // Description is free text for humans. + // +optional + Description string `json:"description,omitempty"` +} + +// SelfProjectRequestStatus reports what the request produced. +type SelfProjectRequestStatus struct { + // Created is true when the Project was created by this request, and + // false when it already existed — the request is idempotent, so + // asking twice is not an error. + // +optional + Created bool `json:"created,omitempty"` + // Project is the created object's name. + // +optional + Project string `json:"project,omitempty"` + // Message explains the outcome in a sentence. + // +optional + Message string `json:"message,omitempty"` +} + +// SelfProjectRequestList is the list form, which exists because the API +// machinery requires it; the resource is create-only. +// +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +// +kubebuilder:object:root=true +type SelfProjectRequestList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []SelfProjectRequest `json:"items"` +} + +// SelfTenantRequest asks for a tenant, with the caller as its first +// admin. It is how someone who is a member of nothing gets started. +// +// Unlike every other self-service path here, there is no Membership to +// authorize against — that is the point — so the gate is the +// deployment's: self-service is off unless enabled, and may be limited +// to groups the identity provider asserts. +// +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +// +kubebuilder:object:root=true +type SelfTenantRequest struct { + metav1.TypeMeta `json:",inline"` + // +optional + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec SelfTenantRequestSpec `json:"spec"` + // +optional + Status SelfTenantRequestStatus `json:"status,omitempty"` +} + +// SelfTenantRequestSpec names the tenant to create. The first admin is +// not here: it is the caller, and the server sets it. +type SelfTenantRequestSpec struct { + // Name is the tenant's object name, which also seeds its workspace + // name. + Name string `json:"name"` + // DisplayName is the tenant's human name. Defaults to Name. + // +optional + DisplayName string `json:"displayName,omitempty"` + // Description is free text for humans. + // +optional + Description string `json:"description,omitempty"` +} + +// SelfTenantRequestStatus reports what the request produced. +type SelfTenantRequestStatus struct { + // Created is true when this request created the tenant, and false + // when one of that name already existed — which does not mean the + // caller can reach it. + // +optional + Created bool `json:"created,omitempty"` + // Tenant is the tenant's name. + // +optional + Tenant string `json:"tenant,omitempty"` + // Message explains the outcome in a sentence. + // +optional + Message string `json:"message,omitempty"` +} + +// SelfTenantRequestList is the list form, which the API machinery +// requires; the resource is create-only. +// +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +// +kubebuilder:object:root=true +type SelfTenantRequestList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []SelfTenantRequest `json:"items"` +} diff --git a/tenancy/sdk/apis/tenancy/v1alpha1/zz_generated_deepcopy.go b/tenancy/sdk/apis/tenancy/v1alpha1/zz_generated_deepcopy.go index cd3370a..f0ab004 100644 --- a/tenancy/sdk/apis/tenancy/v1alpha1/zz_generated_deepcopy.go +++ b/tenancy/sdk/apis/tenancy/v1alpha1/zz_generated_deepcopy.go @@ -325,3 +325,121 @@ func (in *SelfTenancyReviewList) DeepCopyObject() runtime.Object { } return nil } + +// DeepCopyInto is a deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *SelfProjectRequest) DeepCopyInto(out *SelfProjectRequest) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + out.Spec = in.Spec + out.Status = in.Status +} + +// DeepCopy is a deepcopy function, copying the receiver, creating a new SelfProjectRequest. +func (in *SelfProjectRequest) DeepCopy() *SelfProjectRequest { + if in == nil { + return nil + } + out := new(SelfProjectRequest) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is a deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *SelfProjectRequest) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is a deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *SelfProjectRequestList) DeepCopyInto(out *SelfProjectRequestList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + l := make([]SelfProjectRequest, len(in.Items)) + for i := range in.Items { + in.Items[i].DeepCopyInto(&l[i]) + } + out.Items = l + } +} + +// DeepCopy is a deepcopy function, copying the receiver, creating a new SelfProjectRequestList. +func (in *SelfProjectRequestList) DeepCopy() *SelfProjectRequestList { + if in == nil { + return nil + } + out := new(SelfProjectRequestList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is a deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *SelfProjectRequestList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is a deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *SelfTenantRequest) DeepCopyInto(out *SelfTenantRequest) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + out.Spec = in.Spec + out.Status = in.Status +} + +// DeepCopy is a deepcopy function, copying the receiver, creating a new SelfTenantRequest. +func (in *SelfTenantRequest) DeepCopy() *SelfTenantRequest { + if in == nil { + return nil + } + out := new(SelfTenantRequest) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is a deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *SelfTenantRequest) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is a deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *SelfTenantRequestList) DeepCopyInto(out *SelfTenantRequestList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + l := make([]SelfTenantRequest, len(in.Items)) + for i := range in.Items { + in.Items[i].DeepCopyInto(&l[i]) + } + out.Items = l + } +} + +// DeepCopy is a deepcopy function, copying the receiver, creating a new SelfTenantRequestList. +func (in *SelfTenantRequestList) DeepCopy() *SelfTenantRequestList { + if in == nil { + return nil + } + out := new(SelfTenantRequestList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is a deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *SelfTenantRequestList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} diff --git a/tenancy/test/e2e/fixture_test.go b/tenancy/test/e2e/fixture_test.go index 2cdb19d..95ac4ae 100644 --- a/tenancy/test/e2e/fixture_test.go +++ b/tenancy/test/e2e/fixture_test.go @@ -349,7 +349,7 @@ func testContext(t *testing.T) context.Context { // bindingName mirrors the operator's deterministic binding naming. func bindingName(membershipName string) string { - return fmt.Sprintf("tenancy.contrib.kcp.io:membership:%s", membershipName) + return fmt.Sprintf("tenancy.platform.kcp.io:membership:%s", membershipName) } // getBinding fetches the materialized ClusterRoleBinding for a membership diff --git a/tenancy/test/e2e/scenarios_cli_test.go b/tenancy/test/e2e/scenarios_cli_test.go index e914c84..a402cdb 100644 --- a/tenancy/test/e2e/scenarios_cli_test.go +++ b/tenancy/test/e2e/scenarios_cli_test.go @@ -23,12 +23,16 @@ import ( "os" "os/exec" "path/filepath" + "sort" "strings" "testing" "time" + "k8s.io/client-go/tools/clientcmd" + clientcmdapi "k8s.io/client-go/tools/clientcmd/api" "sigs.k8s.io/controller-runtime/pkg/client" + "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/pkg/naming" tenancyv1alpha1 "github.com/kcp-dev/contrib-virtual-workspaces/tenancy/sdk/apis/tenancy/v1alpha1" ) @@ -141,7 +145,7 @@ func TestScenarioTenancyctlDrivesTheModel(t *testing.T) { projectWS := workspaceClient(t, projectObj.Status.URL) waitFor(t, ctx, "the CLI's grant to reach the project workspace", func(ctx context.Context) (bool, error) { - crb, err := getBinding(ctx, projectWS, "alice-"+tenant) + crb, err := getBinding(ctx, projectWS, naming.MembershipName(string(tenancyv1alpha1.SubjectKindUser), "alice", tenant, "")) if err != nil { return false, nil } @@ -151,7 +155,7 @@ func TestScenarioTenancyctlDrivesTheModel(t *testing.T) { // Revoking removes it again. tenancyctl(t, ctx, "revoke", "alice", "--tenant", tenant) waitFor(t, ctx, "the CLI's revoke to remove the binding", func(ctx context.Context) (bool, error) { - _, err := getBinding(ctx, projectWS, "alice-"+tenant) + _, err := getBinding(ctx, projectWS, naming.MembershipName(string(tenancyv1alpha1.SubjectKindUser), "alice", tenant, "")) return err != nil, nil }) } @@ -215,4 +219,34 @@ func TestScenarioTenancyctlWhoamiAndKubeconfig(t *testing.T) { t.Errorf("generated kubeconfig has no %q:\n%s", want, raw) } } + + // Projects only. The tenant workspace is this system's own record + // store: a Membership materializes RBAC in the tenant's projects and + // never in the tenant itself, so a context for it could only answer + // Forbidden and must not be written. + written, err := clientcmd.Load(raw) + if err != nil { + t.Fatalf("parse generated kubeconfig: %v", err) + } + if _, found := written.Contexts[tenant]; found { + t.Errorf("generated kubeconfig has a context for the tenant workspace %q, which no member can enter", tenant) + } + project := "web-" + suffix + if _, found := written.Contexts[tenant+"-"+project]; !found { + t.Errorf("generated kubeconfig has no context for project %q; got %v", + tenant+"-"+project, contextNames(written)) + } + if written.CurrentContext != tenant+"-"+project { + t.Errorf("current context is %q, want the project context %q", + written.CurrentContext, tenant+"-"+project) + } +} + +func contextNames(cfg *clientcmdapi.Config) []string { + names := make([]string, 0, len(cfg.Contexts)) + for name := range cfg.Contexts { + names = append(names, name) + } + sort.Strings(names) + return names } diff --git a/tenancy/test/e2e/scenarios_test.go b/tenancy/test/e2e/scenarios_test.go index 4a7e404..2524ac5 100644 --- a/tenancy/test/e2e/scenarios_test.go +++ b/tenancy/test/e2e/scenarios_test.go @@ -72,13 +72,23 @@ func TestScenarioInstallIsIdempotent(t *testing.T) { } } - for _, name := range []string{ - "v1alpha1.tenants.tenancy.contrib.kcp.io", - "v1alpha1.projects.tenancy.contrib.kcp.io", - "v1alpha1.memberships.tenancy.contrib.kcp.io", - } { - if _, err := dyn.Resource(apiResourceSchemaGVR).Get(ctx, name, metav1.GetOptions{}); err != nil { - t.Errorf("APIResourceSchema %s missing: %v", name, err) + // Schema names are generated (content-addressed by `make generate`), + // so assert what the exports actually reference rather than a spelling. + for _, exportName := range []string{exportPlatform, exportTenancy} { + export, err := dyn.Resource(apiExportGVR).Get(ctx, exportName, metav1.GetOptions{}) + if err != nil { + t.Fatalf("get %s: %v", exportName, err) + } + resources, _, _ := unstructured.NestedSlice(export.Object, "spec", "resources") + if len(resources) == 0 { + t.Errorf("APIExport %s serves no resources", exportName) + } + for _, r := range resources { + m, _ := r.(map[string]any) + schemaName, _ := m["schema"].(string) + if _, err := dyn.Resource(apiResourceSchemaGVR).Get(ctx, schemaName, metav1.GetOptions{}); err != nil { + t.Errorf("APIResourceSchema %s referenced by %s missing: %v", schemaName, exportName, err) + } } } @@ -280,7 +290,7 @@ func TestScenarioMembershipMaterializesInProjectsOnly(t *testing.T) { if err != nil { return false, nil } - return crb.RoleRef.Name == "tenancy.contrib.kcp.io:role:admin", nil + return crb.RoleRef.Name == "tenancy.platform.kcp.io:role:admin", nil }) } @@ -362,7 +372,7 @@ func TestScenarioChangingTheRoleReplacesTheBinding(t *testing.T) { if err != nil { return false, nil } - return crb.RoleRef.Name == "tenancy.contrib.kcp.io:role:edit", nil + return crb.RoleRef.Name == "tenancy.platform.kcp.io:role:edit", nil }) }