k8shell

package module
v0.2.4 Latest Latest
Warning

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

Go to latest
Published: Aug 6, 2026 License: AGPL-3.0 Imports: 15 Imported by: 0

README

k8shell-go

Go SDK for the k8shell API.

Installation

go get github.com/k8shell-io/k8shell-go

Usage

import "github.com/k8shell-io/k8shell-go"

c := k8shell.New("https://k8shell.example.com", token)

// List workspaces
workspaces, err := c.ListWorkspaces(ctx, "", false)

// Create a workspace from a blueprint
resp, err := c.CreateWorkspace(ctx, k8shell.WorkspaceCreateRequest{
    Username:  "alice",
    Blueprint: "go-dev",
})

// Stream creation progress (SSE)
stream, err := c.MonitorWorkspace(ctx, resp.MonitorURL)
defer stream.Close()

Client options

Option Description
WithDebug() Log request/response headers to stderr
WithDebugWriter(w) Log to a custom io.Writer (implies WithDebug)
WithInsecure() Skip TLS certificate verification

Browser login flow

Use NewAnonymous to acquire a PAT without a pre-existing token:

anon := k8shell.NewAnonymous("https://k8shell.example.com")

providers, err := anon.ListProviders(ctx)
// redirect user to the provider login URL, then poll:
for {
    token, err := anon.PollToken(ctx, oauthState)
    if err != nil { /* handle */ }
    if token != nil {
        c := k8shell.New("https://k8shell.example.com", token.Token)
        break
    }
    time.Sleep(2 * time.Second)
}

Error handling

Non-2xx responses return *APIError with the HTTP status code and an optional message from the response body:

var apiErr *k8shell.APIError
if errors.As(err, &apiErr) {
    fmt.Println(apiErr.StatusCode, apiErr.Message)
}

API reference

Method Description
ListProviders(ctx) Identity providers that support browser login
PollToken(ctx, state) Poll for a PAT after browser login
GetProfile(ctx) Authenticated user's profile
ListUsers(ctx) All users visible to the token
GetUserProfile(ctx, username) A user's profile by username
UpdateUserProfile(ctx, username, req) Partially replace fields on a user's profile
GetUserBlueprints(ctx, username) Blueprint names a user is allowed to use
AddUserRoles(ctx, username, roles) / RemoveUserRoles(...) Grant/revoke roles without touching the rest
AddUserBlueprints(ctx, username, blueprints) / RemoveUserBlueprints(...) Grant/revoke blueprints without touching the rest
AddUserKeys(ctx, username, keys) / RemoveUserKeys(...) Add/remove SSH public keys without touching the rest
ListUserCredentials(ctx, username) External service credentials stored for a user
GetUserCredential(ctx, username, serviceName) A user's credential for one external service
ListSessions(ctx, username, workspace, limit, all) SSH sessions visible to the token, optionally filtered by username/workspace and capped to the last limit
ListWorkspaces(ctx, username, all) Workspaces visible to the token
CreateWorkspace(ctx, req) Submit a workspace creation request
GetWorkspace(ctx, name) Workspace details by name
DeleteWorkspace(ctx, name, deleteData) Stop (and optionally delete) a workspace
MonitorWorkspace(ctx, monitorURL) Open SSE stream for a workspace job

License

AGPL-3.0-only

Documentation

Overview

Package k8shell provides a Go client for the k8shell API.

Create an authenticated client with a server URL and personal access token:

c := k8shell.New("https://k8shell.example.com", token)
ws, err := c.ListWorkspaces(ctx, "", false)

For browser-based login, use NewAnonymous to perform the OAuth web flow without a token, then construct an authenticated client from the returned PAT.

Index

Constants

View Source
const CapabilityOnboardUserWebFlow = "OnboardUserWebFlow"

CapabilityOnboardUserWebFlow is the provider capability required for browser-based login.

Variables

View Source
var ErrDryRun = errors.New("dry run: request not sent (--curl)")

ErrDryRun is returned by request methods instead of performing the HTTP call when the client was constructed with WithCurl: the equivalent curl command has already been printed and the request is intentionally not sent, so no response data is available. Callers should propagate this error rather than act on zero-value results.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	StatusCode int
	Message    string
	// contains filtered or unexported fields
}

APIError is returned for non-2xx responses and carries the HTTP status code and an optional message from the response body.

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Unwrap added in v0.1.0

func (e *APIError) Unwrap() error

Unwrap returns the underlying cause, enabling errors.Is/errors.As traversal.

type Client

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

Client is an authenticated HTTP client for the k8shell API.

func New

func New(server, token string, opts ...Option) *Client

New creates an authenticated Client for the given server URL and PAT token.

func NewAnonymous

func NewAnonymous(server string, opts ...Option) *Client

NewAnonymous creates an unauthenticated Client, useful for the browser login flow.

func (*Client) AddGitUserCredential added in v0.2.0

func (c *Client) AddGitUserCredential(ctx context.Context, username string, req models.UserGitCredentialRequest) (*models.UserCredential, error)

AddGitUserCredential stores a Git credential for the named user and returns the stored record.

func (*Client) AddKubernetesUserCredential added in v0.2.0

func (c *Client) AddKubernetesUserCredential(ctx context.Context, username string, req models.UserKubernetesCredentialRequest) (*models.UserCredential, error)

AddKubernetesUserCredential provisions a Kubernetes service-account credential for the named user and returns the stored record.

func (*Client) AddRegistryUserCredential added in v0.2.0

func (c *Client) AddRegistryUserCredential(ctx context.Context, username string, req models.UserRegistryCredentialRequest) (*models.UserCredential, error)

AddRegistryUserCredential stores a container registry credential for the named user and returns the stored record.

func (*Client) AddRoleBlueprints added in v0.2.4

func (c *Client) AddRoleBlueprints(ctx context.Context, org, name string, blueprints []string) error

AddRoleBlueprints grants a role one or more blueprints, in addition to any existing ones; every user holding the role gains access to them.

func (*Client) AddUserKeys added in v0.2.0

func (c *Client) AddUserKeys(ctx context.Context, username string, keys []string) error

AddUserKeys adds the given SSH public keys to the named user, in addition to any existing keys.

func (*Client) AddUserRoles added in v0.2.0

func (c *Client) AddUserRoles(ctx context.Context, username string, roles []models.Role) error

AddUserRoles grants the given roles to the named user, in addition to any existing roles.

func (*Client) ApproveOnboardRule added in v0.2.4

func (c *Client) ApproveOnboardRule(ctx context.Context, org string, id int32) (*models.User, error)

ApproveOnboardRule approves a pending ("waitlist") onboard rule, flipping its action to "allow", and immediately onboards the user it names rather than waiting for their next login attempt.

func (*Client) ClearUserPasswordLockout added in v0.2.0

func (c *Client) ClearUserPasswordLockout(ctx context.Context, username string) error

ClearUserPasswordLockout clears the named user's transient brute-force lockout on password auth (UserProfile.PasswordLocked), leaving any admin-set account lock (UserProfile.AccountLocked) untouched.

func (*Client) ComposeBlueprint added in v0.2.1

func (c *Client) ComposeBlueprint(ctx context.Context, username string, k8shellFile *models.K8shellFile) (*models.Blueprint, error)

ComposeBlueprint submits a k8shell file for the named user and returns the blueprint composed by merging it with the user's assigned blueprints. Only admin tokens, or the user themself, may compose their own file.

func (*Client) CreateOnboardRule added in v0.2.4

func (c *Client) CreateOnboardRule(ctx context.Context, org string, req models.OnboardRuleCreateRequest) (*models.OnboardRule, error)

CreateOnboardRule registers a new onboard rule scoped to org — a standing pattern policy, or a one-off decision for a specific username — and returns it.

func (*Client) CreateOrganization added in v0.2.4

func (c *Client) CreateOrganization(ctx context.Context, req models.OrganizationCreateRequest) (*models.Organization, error)

CreateOrganization registers a new organization and returns it.

func (*Client) CreateRole added in v0.2.4

func (c *Client) CreateRole(ctx context.Context, org string, req models.RoleCreateRequest) (*models.RoleInfo, error)

CreateRole registers a new assignable role scoped to org and returns it. Global roles cannot be created through this method.

func (*Client) CreateUser added in v0.2.0

func (c *Client) CreateUser(ctx context.Context, req models.UserCreateRequest) (*models.User, error)

CreateUser creates a new local user record with no backing identity provider and returns it. Only admin tokens can create users.

func (*Client) CreateUserToken added in v0.2.2

func (c *Client) CreateUserToken(ctx context.Context, username string, req models.AccessTokenCreateRequest) (*models.AccessTokenCreated, error)

CreateUserToken issues a new personal access token for the named user and returns its ID and raw secret value. The secret is returned exactly once — it cannot be retrieved again after this call.

func (*Client) CreateWorkspace

func (c *Client) CreateWorkspace(ctx context.Context, req WorkspaceCreateRequest) (*WorkspaceCreateResponse, error)

CreateWorkspace submits a workspace creation request and returns the 202 response containing the workspace name, job ID, and SSE monitor URL.

func (*Client) DeleteOnboardRule added in v0.2.4

func (c *Client) DeleteOnboardRule(ctx context.Context, org string, id int32) error

DeleteOnboardRule removes an onboard rule from the registry.

func (*Client) DeleteOrganization added in v0.2.4

func (c *Client) DeleteOrganization(ctx context.Context, name string, req models.OrganizationDeleteRequest) error

DeleteOrganization removes an organization from the registry. req controls what happens to the organization's users and their workspaces — see models.OrganizationDeleteRequest.

func (*Client) DeleteRole added in v0.2.4

func (c *Client) DeleteRole(ctx context.Context, org, name string) error

DeleteRole removes a role from the registry. Fails if any user still holds the role. Global roles cannot be removed through this method.

func (*Client) DeleteUser added in v0.2.0

func (c *Client) DeleteUser(ctx context.Context, username string, preserveWorkspaces bool) error

DeleteUser permanently deletes the named user. When preserveWorkspaces is true, the user's workspaces are kept instead of being deleted along with the account. Only admin tokens can delete users.

func (*Client) DeleteUserCredential added in v0.2.0

func (c *Client) DeleteUserCredential(ctx context.Context, username string, id uint32) error

DeleteUserCredential deletes the named user's credential with the given ID.

func (*Client) DeleteUserToken added in v0.2.2

func (c *Client) DeleteUserToken(ctx context.Context, username string, id int64) error

DeleteUserToken revokes the named user's personal access token with the given ID.

func (*Client) DeleteWorkspace

func (c *Client) DeleteWorkspace(ctx context.Context, name string, deleteData bool) error

DeleteWorkspace shuts down the named workspace. When deleteData is true, workspace storage is permanently deleted.

func (*Client) GetCapabilities added in v0.2.0

func (c *Client) GetCapabilities(ctx context.Context, username, resourceOwner string) ([]models.Capability, error)

GetCapabilities returns the named user's policy capabilities: which actions they are allowed or denied, why, and any obligations attached. Pass an empty username for the authenticated user's own capabilities. resourceOwner, if non-empty, checks capabilities as they'd apply to resources owned by that user (e.g. an org-scoped policy obligation) rather than the caller's own.

func (*Client) GetOrganization added in v0.2.4

func (c *Client) GetOrganization(ctx context.Context, name string) (*models.Organization, error)

GetOrganization returns a single organization by name.

func (*Client) GetProfile

func (c *Client) GetProfile(ctx context.Context) (*models.UserProfile, error)

GetProfile returns the profile of the authenticated user.

func (*Client) GetRole added in v0.2.4

func (c *Client) GetRole(ctx context.Context, org, name string) (*models.RoleInfo, error)

GetRole returns the named role scoped to org (or a global role visible within it). The server has no single-role lookup endpoint, so this filters the result of ListRoles client-side.

func (*Client) GetUserBlueprints added in v0.2.0

func (c *Client) GetUserBlueprints(ctx context.Context, username string) ([]string, error)

GetUserBlueprints returns the blueprint names the named user is allowed to use.

func (*Client) GetUserCredential added in v0.2.0

func (c *Client) GetUserCredential(ctx context.Context, username string, id uint32) (*models.UserCredential, error)

GetUserCredential returns the named user's credential with the given ID.

func (*Client) GetUserProfile added in v0.2.0

func (c *Client) GetUserProfile(ctx context.Context, username string) (*models.UserProfile, error)

GetUserProfile returns the profile of the named user.

func (*Client) GetUserToken added in v0.2.2

func (c *Client) GetUserToken(ctx context.Context, username string, id int64) (*models.AccessToken, error)

GetUserToken returns the named user's personal access token with the given ID. The server has no single-token lookup endpoint, so this filters the result of ListUserTokens client-side.

func (*Client) GetWorkspace

func (c *Client) GetWorkspace(ctx context.Context, name string) (*models.WorkspaceDetails, error)

GetWorkspace returns the details of the named workspace.

func (*Client) ListOnboardRules added in v0.2.4

func (c *Client) ListOnboardRules(ctx context.Context, org string, filter OnboardRuleFilter) ([]models.OnboardRule, error)

ListOnboardRules returns the onboard rules scoped to org, optionally narrowed by filter, via the resource's _query endpoint (there is no plain list endpoint for onboard rules). Passing action="waitlist" via filter is how a caller renders the pending approval queue — there is no separate endpoint for that.

func (*Client) ListOrganizations added in v0.2.4

func (c *Client) ListOrganizations(ctx context.Context) ([]models.Organization, error)

ListOrganizations returns the registered organizations.

func (*Client) ListProviders

func (c *Client) ListProviders(ctx context.Context) ([]string, error)

ListProviders returns the names of identity providers that support the OnboardUserWebFlow capability (i.e. browser-based login).

func (*Client) ListRoles added in v0.2.4

func (c *Client) ListRoles(ctx context.Context, org string) ([]models.RoleInfo, error)

ListRoles returns the roles assignable within org: those scoped to it plus all global roles.

func (*Client) ListSessions

func (c *Client) ListSessions(ctx context.Context, username, workspace string, limit int, all bool) ([]models.SSHSession, error)

ListSessions returns SSH sessions visible to the authenticated token. When username or workspace is non-empty, results are filtered accordingly. When limit is greater than zero, results are capped to the last limit sessions. When all is true, all sessions (including ended ones) are returned.

func (*Client) ListUserAuthKeys added in v0.2.0

func (c *Client) ListUserAuthKeys(ctx context.Context, username string) ([]models.UserAuthKey, error)

ListUserAuthKeys returns the SSH public keys registered for the named user, in digest (fingerprint) form. Each key's Index identifies its position for use with RemoveUserAuthKey.

func (*Client) ListUserCredentials added in v0.2.0

func (c *Client) ListUserCredentials(ctx context.Context, username string) ([]models.UserCredential, error)

ListUserCredentials returns the external service credentials stored for the named user.

func (*Client) ListUserTokens added in v0.2.2

func (c *Client) ListUserTokens(ctx context.Context, username string) ([]models.AccessToken, error)

ListUserTokens returns the personal access tokens issued for the named user. The raw token values are never returned, only metadata (name, scopes, preview, etc).

func (*Client) ListUsers

func (c *Client) ListUsers(ctx context.Context) ([]models.UserProfile, error)

ListUsers returns the profiles of all users visible to the authenticated token.

func (*Client) ListWorkspaces

func (c *Client) ListWorkspaces(ctx context.Context, username string, all bool) ([]models.WorkspaceDetails, error)

ListWorkspaces returns workspaces visible to the authenticated token. When username is non-empty the results are filtered by owner. When all is true, workspaces in all states are included.

func (*Client) MonitorWorkspace

func (c *Client) MonitorWorkspace(ctx context.Context, monitorURL string) (io.ReadCloser, error)

MonitorWorkspace opens an SSE stream at monitorURL and returns the response body for the caller to consume. monitorURL may be a full URL or a path relative to the client's server. The caller is responsible for closing the returned ReadCloser.

func (*Client) PollToken

func (c *Client) PollToken(ctx context.Context, state string) (*models.UserToken, error)

PollToken checks whether the PAT for the given OAuth state is ready. Returns (nil, nil) when the login is still pending (202 Accepted), or (token, nil) once the token is issued (200 OK).

func (*Client) RejectOnboardRule added in v0.2.4

func (c *Client) RejectOnboardRule(ctx context.Context, org string, id int32, req models.OnboardRuleRejectRequest) (*models.OnboardRule, error)

RejectOnboardRule rejects a pending ("waitlist") onboard rule, flipping its action to "reject" so the user cannot re-trigger a new waitlist entry by trying again, and returns the updated rule.

func (*Client) RemoveRoleBlueprints added in v0.2.4

func (c *Client) RemoveRoleBlueprints(ctx context.Context, org, name string, blueprints []string) error

RemoveRoleBlueprints revokes one or more blueprints from a role, leaving others untouched.

func (*Client) RemoveUserAuthKey added in v0.2.0

func (c *Client) RemoveUserAuthKey(ctx context.Context, username string, index int) error

RemoveUserAuthKey removes a single SSH public key from the named user, identified by its index in the list returned by ListUserAuthKeys. The authenticated token identifies who is performing the removal; username identifies whose key it is.

func (*Client) RemoveUserRoles added in v0.2.0

func (c *Client) RemoveUserRoles(ctx context.Context, username string, roles []models.Role) error

RemoveUserRoles revokes the given roles from the named user, leaving other roles untouched.

func (*Client) ResolveUserCredential added in v0.2.1

func (c *Client) ResolveUserCredential(ctx context.Context, username, serviceName, scope string) (*models.UserCredential, error)

ResolveUserCredential returns the named user's credential for the given service name and scope, as resolved by the server (e.g. narrowest matching scope wins). Unlike GetUserCredential, which looks a credential up by its stored ID, this mirrors the server's /credentials/{service_name}?scope= resolution endpoint used by credential helpers (git, docker, kubernetes).

func (*Client) SetUserPassword added in v0.2.0

func (c *Client) SetUserPassword(ctx context.Context, username, password, currentPassword string) (*models.User, error)

SetUserPassword sets or replaces the named user's local password and returns the updated record. Pass an empty username to set the authenticated user's own password. currentPassword is required by the server when a non-sudo user is changing their own password, and ignored otherwise; pass "" when not needed. The server bcrypt-hashes the password before persisting it.

func (*Client) StartWorkspace added in v0.2.2

func (c *Client) StartWorkspace(ctx context.Context, name string) (*WorkspaceCreateResponse, error)

StartWorkspace starts a previously stopped workspace and returns the 202 response containing the workspace name, job ID, and SSE monitor URL — starting is a streamed provisioning operation on the server, the same as CreateWorkspace.

func (*Client) UpdateOnboardRule added in v0.2.4

func (c *Client) UpdateOnboardRule(ctx context.Context, org string, id int32, req models.OnboardRuleUpdateRequest) (*models.OnboardRule, error)

UpdateOnboardRule fully replaces the mutable fields of an onboard rule and returns the updated record. idp/usernamePattern/org are immutable — delete and recreate the rule to change them.

func (*Client) UpdateOrganization added in v0.2.4

func (c *Client) UpdateOrganization(ctx context.Context, name string, req models.OrganizationUpdateRequest) (*models.Organization, error)

UpdateOrganization applies a partial update to an organization's description and returns the updated record. The name is immutable and cannot be changed.

func (*Client) UpdateRole added in v0.2.4

func (c *Client) UpdateRole(ctx context.Context, org, name string, req models.RoleUpdateRequest) (*models.RoleInfo, error)

UpdateRole updates a role's description and returns the updated record. Name and org are immutable. Global roles cannot be updated through this method.

func (*Client) UpdateUserCredential added in v0.2.0

func (c *Client) UpdateUserCredential(ctx context.Context, username string, id uint32, req models.UserCredentialUpdateRequest) (*models.UserCredential, error)

UpdateUserCredential partially updates the named user's credential with the given ID and returns the updated record. Only non-nil fields in req are applied.

func (*Client) UpdateUserProfile added in v0.2.0

func (c *Client) UpdateUserProfile(ctx context.Context, username string, req models.UserUpdateRequest) (*models.User, error)

UpdateUserProfile applies a partial update to the named user's profile and returns the updated record. Only admin tokens can update other users; a token updating itself may be limited to a subset of fields by the server.

func (*Client) UpdateUserToken added in v0.2.2

func (c *Client) UpdateUserToken(ctx context.Context, username string, id int64, req models.AccessTokenUpdateRequest) (*models.AccessToken, error)

UpdateUserToken partially updates the named user's personal access token with the given ID — its active state and/or scopes — and returns the updated record. Name and expiry are immutable after creation.

type OnboardRuleFilter added in v0.2.4

type OnboardRuleFilter struct {
	IDP    string
	Status string
	Action string
}

OnboardRuleFilter narrows the results of ListOnboardRules. Zero values impose no restriction on that field.

type Option

type Option func(*Client)

Option configures a Client.

func WithCurl added in v0.2.0

func WithCurl() Option

WithCurl enables printing an equivalent curl command — including the unmasked bearer token — for every request instead of debug header output. Callers are responsible for not combining this with WithDebug.

func WithCurlLocation added in v0.2.0

func WithCurlLocation() Option

WithCurlLocation adds curl's own -L flag to the command printed by WithCurl, so curl follows redirects the same way c.http does by default. Has no effect unless WithCurl is also set.

func WithCurlVerbose added in v0.2.0

func WithCurlVerbose() Option

WithCurlVerbose adds curl's own -v flag to the command printed by WithCurl, so curl prints its own verbose connection/handshake details when the command is run. Has no effect unless WithCurl is also set.

func WithDebug

func WithDebug() Option

WithDebug enables request/response header logging.

func WithDebugWriter added in v0.1.0

func WithDebugWriter(w io.Writer) Option

WithDebugWriter sets the writer used for debug output and implies WithDebug.

func WithInsecure

func WithInsecure() Option

WithInsecure disables TLS certificate verification.

type WorkspaceCreateRequest

type WorkspaceCreateRequest struct {
	Username  string `json:"username"`
	Blueprint string `json:"blueprint,omitempty"`
	RepoOwner string `json:"repoOwner,omitempty"`
	RepoName  string `json:"repoName,omitempty"`
	RepoRef   string `json:"repoRef,omitempty"`
}

WorkspaceCreateRequest is the payload for creating a workspace. Either Blueprint or (RepoOwner + RepoName) must be set.

type WorkspaceCreateResponse

type WorkspaceCreateResponse struct {
	Workspace  string `json:"workspace"`
	JobID      string `json:"jobId"`
	MonitorURL string `json:"monitorUrl"`
}

WorkspaceCreateResponse is the 202 Accepted body returned by CreateWorkspace.

Jump to

Keyboard shortcuts

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