restapi

package
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 13, 2026 License: Apache-2.0 Imports: 23 Imported by: 0

Documentation

Overview

Package restapi implements roadmap step 10: the hub-mediated REST surface for Org / Workspace / Membership / User CRUD per docs/organizations.md decision O-10 ("Org workspaces are hub-mediated only"), plus the undelete actions wired to PR #212's soft-delete reconciler, the self-leave / role PATCH from O-12, and the ?cascade=true shortcut from O-9.

Endpoints mount at /api/* and run behind two middlewares from pkg/hub/tenant:

  • tenant.UserOnlyMiddleware on /api/users + /api/orgs (the org-list / org-create surface, plus any User self-service endpoint that doesn't claim an active Org). The handler only needs the caller's User identity.
  • tenant.Middleware on /api/orgs/{org}* and /api/orgs/{org}/workspaces/{ws}*. The header-bound TenantContext carries (User, OrgUUID, WorkspaceUUID, Role); the handler additionally enforces path/header consistency and any role requirement.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AcceptedClaim

type AcceptedClaim struct {
	Group    string `json:"group,omitempty"`
	Resource string `json:"resource"`
}

AcceptedClaim identifies one permission claim the user accepted in the confirmation dialog by its declared (group, resource) tuple. Verbs come from the provider's CatalogEntry — the user only chooses whether to grant them, not which verbs.

type CreateOrgRequest

type CreateOrgRequest struct {
	DisplayName          string `json:"displayName"`
	WorkspaceCreation    string `json:"workspaceCreation,omitempty"`    // "members" | "admin"; default "members"
	CatalogEntryCreation string `json:"catalogEntryCreation,omitempty"` // "members" | "admin"; default "members"
}

CreateOrgRequest is the POST /api/orgs body.

type CreateWorkspaceRequest

type CreateWorkspaceRequest struct {
	DisplayName string `json:"displayName"`
}

CreateWorkspaceRequest is the POST body for creating a Workspace.

type EnableProviderRequest

type EnableProviderRequest struct {
	AcceptedClaims []AcceptedClaim `json:"acceptedClaims"`
}

EnableProviderRequest is the body of POST .../providers/{name}/enable. Mirrors the dialog state — for each declared permission claim, whether the user accepted it. Claims the user didn't tick are sent through to kcp as state=Rejected, which prevents the binding from going Bound and surfaces the mismatch to the user.

type EnableProviderResponse

type EnableProviderResponse struct {
	BindingName string `json:"bindingName"`
}

EnableProviderResponse is the success body. Mirrors what the portal would have learned from a direct kcp POST so the existing UI code can use it unchanged.

type Handler

type Handler struct {
	// contains filtered or unexported fields
}

Handler is the HTTP surface. One handler instance registers all /api/* endpoints across the two middlewares.

func NewHandler

func NewHandler(mgr *Manager) *Handler

NewHandler constructs a Handler.

func (*Handler) RegisterTenantScoped

func (h *Handler) RegisterTenantScoped(r *mux.Router)

RegisterTenantScoped attaches the routes that require an active Org (and optionally Workspace) context. r is the subrouter wrapped in tenant.Middleware.

Effective routes:

GET    /api/orgs/{org}                                                  get one Org
PATCH  /api/orgs/{org}                                                  patch Org metadata
DELETE /api/orgs/{org}                                                  soft-delete Org
POST   /api/orgs/{org}/undelete                                         undelete Org

GET    /api/orgs/{org}/memberships                                      list org-scope members
POST   /api/orgs/{org}/memberships                                      add an org-scope member
DELETE /api/orgs/{org}/memberships/me                                   self-leave (O-12)
PATCH  /api/orgs/{org}/memberships/{user}                               role patch (O-12)
DELETE /api/orgs/{org}/memberships/{user}                               remove an org-scope member

GET    /api/orgs/{org}/workspaces                                       list workspaces in this Org
POST   /api/orgs/{org}/workspaces                                       create a workspace
GET    /api/orgs/{org}/workspaces/{ws}                                  get one Workspace
PATCH  /api/orgs/{org}/workspaces/{ws}                                  patch Workspace metadata
DELETE /api/orgs/{org}/workspaces/{ws}                                  soft-delete Workspace
POST   /api/orgs/{org}/workspaces/{ws}/undelete                         undelete Workspace

GET    /api/orgs/{org}/workspaces/{ws}/memberships                      list workspace-scope members
POST   /api/orgs/{org}/workspaces/{ws}/memberships                      add workspace-scope member
DELETE /api/orgs/{org}/workspaces/{ws}/memberships/me                   self-leave Workspace
PATCH  /api/orgs/{org}/workspaces/{ws}/memberships/{user}               role patch
DELETE /api/orgs/{org}/workspaces/{ws}/memberships/{user}               remove a member

GET    /api/orgs/{org}/workspaces/{ws}/kubeconfig                       download a workspace-scoped kubeconfig

func (*Handler) RegisterUserOnly

func (h *Handler) RegisterUserOnly(r *mux.Router)

RegisterUserOnly attaches the routes that only need the caller's User identity (no active Org / Workspace yet). r is the subrouter wrapped in tenant.UserOnlyMiddleware.

Effective routes:

GET    /api/orgs                       list orgs the caller is in
POST   /api/orgs                       create a new Org
DELETE /api/users/me                   soft-delete self (O-8)
POST   /api/users/me/undelete          undelete self (O-8)

type KubeconfigConfig

type KubeconfigConfig struct {
	HubExternalURL string
	DevMode        bool
	OIDCIssuerURL  string
	OIDCClientID   string
}

KubeconfigConfig configures the workspace-scoped kubeconfig download endpoint. When OIDCIssuerURL is set, the generator emits an exec credential plugin entry that runs `faros get-token` against the issuer — the same shape the OIDC login flow produces. When unset, the handler embeds the caller's bearer token directly (static-token mode).

HubExternalURL is required either way; the kubeconfig server URL is HubExternalURL + /clusters/<clusterName>. DevMode toggles insecure-skip-tls-verify so the file works against self-signed dev hubs without extra flags.

type ListAppAccessGrantsResponse

type ListAppAccessGrantsResponse struct {
	Items []kcp.AppAccessGrant `json:"items"`
}

ListAppAccessGrantsResponse is the body of GET .../app-access.

type ListEnabledProvidersResponse

type ListEnabledProvidersResponse struct {
	BindingNamesByProvider map[string]string `json:"bindingNamesByProvider"`
}

ListEnabledProvidersResponse is the body of GET .../providers/enabled. Items are keyed by provider name (the binding's metadata.name matches the provider name by existing convention), value is the binding name — kept as a map so the portal can do "is provider X enabled" lookups in O(1) without indexing client-side.

type ListResponse

type ListResponse[T any] struct {
	Items []T `json:"items"`
}

ListResponse wraps a list payload so we can add pagination metadata later without breaking clients.

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager holds the dependencies every handler needs: the faros typed client (for Org / User / UMI CR access in root:faros:users) and the WorkspaceOps (kcp Bootstrapper in production; fake in tests).

func NewManager

func NewManager(client *farosclient.Client, bootstrapper WorkspaceOps) *Manager

NewManager builds a Manager from the userClient (typed faros client against root:faros:users) and the WorkspaceOps. Production callers pass a kcp.Bootstrapper; tests pass a fake.

func (*Manager) WithKubeconfig

func (m *Manager) WithKubeconfig(cfg KubeconfigConfig) *Manager

WithKubeconfig sets the kubeconfig-download configuration. Optional — when unset (the zero value) the download endpoint returns 503 so the route registration stays independent of OIDC wiring.

func (*Manager) WithProviderRegistry

func (m *Manager) WithProviderRegistry(p ProviderLookup) *Manager

WithProviderRegistry installs the lookup used by the enableProvider handler. Wired from the hub's in-memory providers.Registry. When unset, POST .../providers/{name}/enable returns 501 — keeping the route registration independent of provider wiring for tests / minimal hubs.

type MembershipAddRequest

type MembershipAddRequest struct {
	User string `json:"user"`
	Role string `json:"role"` // admin | member
	// Invite pre-provisions a pending User when the identifier is an email
	// with no matching account. The pending User carries the email-derived
	// RBAC identity immediately (so memberships and app grants written now
	// apply on arrival) and is adopted by the first OIDC sign-in with that
	// email. Without this flag an unknown identifier stays a clean 404 so
	// typos cannot mint ghost users.
	Invite bool `json:"invite,omitempty"`
}

MembershipAddRequest is the POST body for adding a Membership.

type MembershipPatchRequest

type MembershipPatchRequest struct {
	Role string `json:"role"`
}

MembershipPatchRequest is the PATCH body for role changes (O-12).

type MembershipView

type MembershipView struct {
	User string `json:"user"`
	// RBACIdentity is the member's kcp username (User.Spec.RBACIdentity,
	// "faros:<email>") — the subject string every tenant-workspace RBAC
	// binding uses. Consumers writing RBAC (e.g. App Studio's app-access
	// grants) must bind this, never the User CR name.
	RBACIdentity         string `json:"rbacIdentity,omitempty"`
	Role                 string `json:"role"`
	OrgUUID              string `json:"orgUUID"`
	WorkspaceUUID        string `json:"workspaceUUID,omitempty"`
	OrgDisplayName       string `json:"orgDisplayName,omitempty"`
	WorkspaceDisplayName string `json:"workspaceDisplayName,omitempty"`
}

MembershipView is the REST projection of a single org-or-workspace scope membership.

type OrgView

type OrgView struct {
	UUID                 string     `json:"uuid"`
	DisplayName          string     `json:"displayName"`
	Personal             bool       `json:"personal"`
	WorkspaceCreation    string     `json:"workspaceCreation"`
	CatalogEntryCreation string     `json:"catalogEntryCreation"`
	WorkspaceQuota       int32      `json:"workspaceQuota,omitempty"`
	CreatedAt            time.Time  `json:"createdAt"`
	DeletionRequestedAt  *time.Time `json:"deletionRequestedAt,omitempty"`
}

OrgView is the REST projection of an Organization.

type PatchOrgRequest

type PatchOrgRequest struct {
	DisplayName          string `json:"displayName,omitempty"`
	WorkspaceCreation    string `json:"workspaceCreation,omitempty"`
	CatalogEntryCreation string `json:"catalogEntryCreation,omitempty"`
	WorkspaceQuota       *int32 `json:"workspaceQuota,omitempty"`
}

PatchOrgRequest is the PATCH /api/orgs/{org} body. Empty fields are ignored.

type PatchWorkspaceRequest

type PatchWorkspaceRequest struct {
	DisplayName string `json:"displayName,omitempty"`
}

PatchWorkspaceRequest is the PATCH body. Currently only displayName is editable.

type ProviderLookup

type ProviderLookup interface {
	Get(name string) (providers.Provider, bool)
}

ProviderLookup is the slice of pkg/hub/providers.Registry the enableProvider handler needs — just a name-keyed Get. Pulled out as an interface so tests can swap in a fake without depending on the in-memory registry package.

type ValidationError

type ValidationError struct{ Msg string }

ValidationError is the sentinel for handler-side input validation failures. writeError translates it into 400. Use newValidationError to construct.

func (*ValidationError) Error

func (e *ValidationError) Error() string

type WorkspaceOps

type WorkspaceOps interface {
	// Org workspace lifecycle
	EnsureOrgWorkspace(ctx context.Context, orgUUID string) error

	// Org Membership CRUD (CRs in the Org workspace)
	EnsureOrgMembership(ctx context.Context, orgUUID, userName, role string) error
	ListOrgMemberships(ctx context.Context, orgUUID string) ([]string, error)
	GetOrgMembershipRole(ctx context.Context, orgUUID, userName string) (string, error)
	PatchOrgMembershipRole(ctx context.Context, orgUUID, userName, role string) error
	DeleteOrgMembership(ctx context.Context, orgUUID, userName string) error

	// Child Workspace lifecycle + projections
	EnsureChildWorkspace(ctx context.Context, orgUUID, wsUUID string) error
	EnsureChildWorkspaceFarosBinding(ctx context.Context, orgUUID, wsUUID string) error
	EnsureChildWorkspaceDefaultMCPServer(ctx context.Context, orgUUID, wsUUID string) error
	// EnsureChildWorkspaceAdmin grants cluster-admin in the child team
	// Workspace to the given rbacIdentity. Idempotent. Used at workspace
	// create time and when adding a member, since the kcp-side CRB is
	// otherwise only seeded by the org bootstrap controller for the
	// user's default workspace — every other workspace would 403 from
	// the GraphQL gateway without this call.
	EnsureChildWorkspaceAdmin(ctx context.Context, orgUUID, wsUUID, rbacIdentity string) error
	ListChildWorkspaces(ctx context.Context, orgUUID string) ([]string, error)
	GetWorkspaceDisplayName(ctx context.Context, orgUUID, wsUUID string) (string, error)
	SetWorkspaceDisplayName(ctx context.Context, orgUUID, wsUUID, displayName string) error
	GetWorkspaceDeletionRequestedAt(ctx context.Context, orgUUID, wsUUID string) (*time.Time, bool, error)
	SetWorkspaceDeletionAnnotation(ctx context.Context, orgUUID, wsUUID string, at time.Time) error
	ClearWorkspaceDeletionAnnotation(ctx context.Context, orgUUID, wsUUID string) error

	// GetChildWorkspaceClusterName returns the kcp logical-cluster name
	// (the /clusters/<name> hash) for a child workspace. Used to build
	// per-workspace kubeconfigs for the download endpoint.
	GetChildWorkspaceClusterName(ctx context.Context, orgUUID, wsUUID string) (string, error)

	// MCPServer CRUD in the tenant workspace. The in-core reconciler provisions
	// each server's identity; GetMCPServerToken follows status.tokenSecretRef
	// (empty string = not provisioned yet).
	ListMCPServers(ctx context.Context, clusterName string) ([]kcp.MCPServerInfo, error)
	CreateMCPServer(ctx context.Context, clusterName, name, displayName, instructions string, readOnly bool) error
	UpdateMCPServer(ctx context.Context, clusterName, name, displayName, instructions string, readOnly bool) error
	DeleteMCPServer(ctx context.Context, clusterName, name string) error
	GetMCPServerToken(ctx context.Context, clusterName, name string) (string, error)

	// EnsureProviderAPIBinding creates an APIBinding in the target
	// child workspace, owned by the hub's kcp-admin identity. Used by
	// the POST .../providers/{name}/enable handler — see
	// pkg/hub/kcp/bootstrap.go for the rationale (proxy's
	// defaultCluster pre-check would 403 any user attempt against a
	// non-default workspace, even with valid RBAC).
	EnsureProviderAPIBinding(ctx context.Context, orgUUID, wsUUID, bindingName, exportPath, exportName string, claims []kcp.ProviderClaim) error

	// ListProviderAPIBindings returns the set of provider APIBindings
	// (those referencing root:faros:providers:*) in the target
	// workspace, keyed by provider name. Used by the
	// GET .../providers/enabled handler so the portal can refresh the
	// "enabled providers" sidebar set on every workspace switch
	// without 403'ing through the kcp user-proxy.
	ListProviderAPIBindings(ctx context.Context, orgUUID, wsUUID string) (map[string]string, error)

	// DeleteProviderAPIBinding removes a provider APIBinding from the
	// target workspace. Used by the POST .../providers/{name}/disable
	// handler. NotFound is a no-op.
	DeleteProviderAPIBinding(ctx context.Context, orgUUID, wsUUID, bindingName string) error

	// EnsureProviderEdgeProxyGrant / RemoveProviderEdgeProxyGrant manage
	// the ClusterRole/ClusterRoleBinding pair that lets a provider's SA
	// (under its cluster-qualified identity) use the "proxy" verb on
	// edges in the tenant workspace. Applied on Enable when the provider
	// declares spec.edgeProxyAccess; removed on Disable.
	EnsureProviderEdgeProxyGrant(ctx context.Context, orgUUID, wsUUID, providerName, subject string) error
	RemoveProviderEdgeProxyGrant(ctx context.Context, orgUUID, wsUUID, providerName string) error

	// ListAppAccessGrants / RemoveAppAccessGrant surface the published-app
	// invitations (labeled ClusterRoleBindings, plain workspace RBAC) so
	// tenant settings can show and revoke them. See app_access.go.
	ListAppAccessGrants(ctx context.Context, orgUUID, wsUUID string) ([]kcp.AppAccessGrant, error)
	RemoveAppAccessGrant(ctx context.Context, orgUUID, wsUUID, bindingName string) error
}

WorkspaceOps is the slice of *kcp.Bootstrapper the REST handlers need to materialise / inspect / mutate workspaces, memberships, and soft-delete state. Pulled out as an interface so unit tests can use a fake without standing up embedded kcp.

Implemented by *pkg/hub/kcp.Bootstrapper.

type WorkspaceView

type WorkspaceView struct {
	UUID                string     `json:"uuid"`
	OrgUUID             string     `json:"orgUUID"`
	DisplayName         string     `json:"displayName,omitempty"`
	ClusterName         string     `json:"clusterName,omitempty"`
	DeletionRequestedAt *time.Time `json:"deletionRequestedAt,omitempty"`
}

WorkspaceView is the REST projection of a child Workspace.

ClusterName is the kcp logical-cluster short hash backing this workspace (Workspace.spec.cluster). The portal uses it to address the GraphQL endpoint `/graphql/{clusterName}` for the active workspace; without it, a workspace switch in the UI cannot retarget per-workspace queries (MCP, edges, …) to the new cluster. May be empty when the workspace has not yet reached Ready and kcp has not assigned a cluster hash — callers should treat it as "not switchable yet" rather than an error.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL