k8shell

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Jul 11, 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) AddUserBlueprints added in v0.2.0

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

AddUserBlueprints grants the given blueprints to the named user, in addition to any existing ones.

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) 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) 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) 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) DeleteUser added in v0.2.0

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

DeleteUser permanently deletes the named user. 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) 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) GetProfile

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

GetProfile returns the profile of the authenticated user.

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) GetWorkspace

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

GetWorkspace returns the details of the named workspace.

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) 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) 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) 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) RemoveUserBlueprints added in v0.2.0

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

RemoveUserBlueprints revokes the given blueprints from the named user, leaving others untouched.

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) 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.

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