k8sconn

package
v1.5.4 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

Documentation

Overview

Package k8sconn is a small Kubernetes API client built on net/http. It avoids client-go and kubectl so no exec plugin or control plane file is ever read on behalf of an uploaded kubeconfig.

Index

Constants

View Source
const (
	LabelManagedBy = "app.kubernetes.io/managed-by"
	LabelApp       = "levelrail.dev/app"
	LabelInstance  = "levelrail.dev/instance"
	ManagedByValue = "levelrail"
)

Label keys let remove delete only objects Levelrail created.

View Source
const ClusterAdminRefusal = "this credential is effectively cluster-admin (wildcard verbs on all resources and api groups) and is refused; " +
	"create a namespaced Role and a limited service account with `levelrail clusters rbac --namespace NS`, then connect that token. " +
	"To accept the risk, set allow_cluster_admin on the request (--allow-cluster-admin) and turn on the runtime setting k8s.allow_cluster_admin"

ClusterAdminRefusal explains the default refusal and the namespaced alternative.

View Source
const FieldManager = "levelrail"

FieldManager owns every field Levelrail applies.

View Source
const SecretTypeDockerConfig = "kubernetes.io/dockerconfigjson"

SecretTypeDockerConfig is the Secret type the kubelet reads image pull credentials from.

Variables

View Source
var ErrAdminCheckUnverified = errors.New("could not verify the credential is not cluster-admin")

ErrAdminCheckUnverified means the rules review failed or was incomplete, so the credential cannot be proven non-admin.

View Source
var ErrHostTaken = errors.New("k8sconn: the ingress host is already used by an ingress levelrail does not own")

ErrHostTaken means another Ingress we do not own already claims the host.

View Source
var ErrHostUnverified = errors.New("k8sconn: ingress hosts could not be listed, so the host cannot be verified")

ErrHostUnverified means Ingresses could not be listed, so host ownership is unknown.

View Source
var ErrLogTarget = errors.New("k8sconn: no such pod or container for this app")

ErrLogTarget means the deployment, pod or container is not one of ours.

View Source
var ErrNamespaceCreateForbidden = errors.New("k8sconn: the credential cannot create the namespace")

ErrNamespaceCreateForbidden means the namespace is missing and the credential may not create it.

View Source
var ErrNamespaceNotManaged = errors.New("k8sconn: the namespace exists and is not managed by levelrail")

ErrNamespaceNotManaged means the namespace exists without our label and is not allowed.

View Source
var ErrNotManaged = errors.New("k8sconn: an object with this name exists and is not managed by levelrail")

ErrNotManaged means an object with this name exists but lacks our labels.

View Source
var ErrRefused = errors.New("k8sconn: kubeconfig field refused")

ErrRefused marks a kubeconfig field Levelrail will not honour.

View Source
var ErrRegistryMismatch = errors.New("k8sconn: the image registry does not match the pull secret registry")

ErrRegistryMismatch means the image is hosted on another registry than the pull secret.

Functions

func AllowPrivateAPI

func AllowPrivateAPI(ctx context.Context, s SettingsReader) bool

AllowPrivateAPI reports whether private and loopback API servers may be dialed.

func BuildPullSecret

func BuildPullSecret(spec AppSpec, registry, username, password string) (map[string]any, error)

BuildPullSecret renders the dockerconfigjson Secret for an app. The credential lives only in the returned object and is never part of Rendered.YAML.

func ImageRegistryHost

func ImageRegistryHost(image string) string

ImageRegistryHost returns the registry an image reference is pulled from, using the same rule as the container runtime: a first segment with a dot, a port or localhost is a host.

func Labels

func Labels(app, instance string) map[string]string

Labels returns the ownership labels for an app. A non-empty instance adds the install id.

func NormalizeRegistryHost

func NormalizeRegistryHost(s string) string

NormalizeRegistryHost lowercases a registry and drops any scheme or path, and folds the Docker Hub aliases into one name. It returns "" when the result is not a host.

func ParseServer

func ParseServer(raw string) (*url.URL, error)

ParseServer accepts a plain https API server URL. Credentials, query and fragment are refused so a secret can never be stored, audited or returned.

func PullSecretName

func PullSecretName(app string) string

PullSecretName is the in-cluster Secret name for an app. One per app keeps removal exact.

Types

type AppSpec

type AppSpec struct {
	Name      string
	Namespace string
	// InstanceID is the install id stamped on labels and the Service selector; empty skips it.
	InstanceID string
	Image      string
	Port       int
	Replicas   int
	Env        map[string]string
	// Host empty means no Ingress is rendered.
	Host         string
	IngressClass string
	// TLSIssuer, when set, adds a cert-manager cluster-issuer annotation.
	TLSIssuer string
	Resources Resources
	// RunAsUser is set only when the caller knows the image runs non-root.
	RunAsUser *int64
	// PullSecretName, when set, is the Secret the pods use to pull a private image.
	PullSecretName string
	// AllowRoot adds back the minimal capabilities root-start images need after drop ALL.
	AllowRoot bool
	// AllowUnmanagedNamespace lets Apply use an existing namespace without our label.
	AllowUnmanagedNamespace bool
	// AllowUnverifiedHost lets Apply proceed when Ingresses cannot be listed.
	AllowUnverifiedHost bool
}

AppSpec is the subset of a Levelrail app that maps to a cluster workload.

type Client

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

Client talks to one API server through a pinned, guard-checked address.

func NewClient

func NewClient(ctx context.Context, cfg Config) (*Client, error)

NewClient checks the server address once and pins every dial to it, so a DNS answer that changes later cannot redirect traffic to a refused host.

func (*Client) Apply

func (c *Client) Apply(ctx context.Context, spec AppSpec, r Rendered) ([]string, error)

Apply checks the namespace, the host and every object first, so one foreign object stops the whole deploy before anything changes. Objects that were absent are created with POST (409 if one appeared meanwhile); ours are forced. Names applied so far return with an error.

func (*Client) CredentialIsClusterAdmin

func (c *Client) CredentialIsClusterAdmin(ctx context.Context) (bool, error)

CredentialIsClusterAdmin asks the API server whether this credential holds a wildcard rule. It fails closed: an errored or incomplete review returns ErrAdminCheckUnverified.

func (*Client) DeletePullSecret

func (c *Client) DeletePullSecret(ctx context.Context, namespace, name, app, instance string) error

DeletePullSecret deletes a Secret only when it carries this app's labels, so a Secret of the same name that we did not create is never touched. A missing Secret is success.

func (*Client) DeploymentStatus

func (c *Client) DeploymentStatus(ctx context.Context, namespace, app, instance string) (Status, error)

DeploymentStatus reads the deployment, its pods and its ingress. It only reads objects that carry our labels and this install's instance id, so a foreign object of the same name looks missing. An empty instance skips the instance check.

func (*Client) Do

func (c *Client) Do(ctx context.Context, method, path string, body []byte) ([]byte, error)

Do sends one request and returns the body of a 2xx response.

func (*Client) EnsureNamespace

func (c *Client) EnsureNamespace(ctx context.Context, name string, allowUnmanaged bool) error

EnsureNamespace creates the namespace with our label when it is missing and never patches one that already exists. An existing unlabelled one needs allowUnmanaged.

func (*Client) ListNamespaces

func (c *Client) ListNamespaces(ctx context.Context) ([]Namespace, error)

ListNamespaces returns every namespace with its phase.

func (*Client) ListNodes

func (c *Client) ListNodes(ctx context.Context) ([]Node, error)

ListNodes returns every node with readiness and role labels.

func (*Client) PodLogs

func (c *Client) PodLogs(ctx context.Context, namespace, app, instance, pod, container string, tail int, maxBytes int64) (LogResult, error)

PodLogs reads the tail of one pod of an app we own. The pod must come from our own label selector, so an arbitrary pod name cannot be read. maxBytes bounds the text returned.

func (*Client) Remove

func (c *Client) Remove(ctx context.Context, namespace, app, instance string, pullSecrets ...string) (RemoveResult, error)

Remove deletes the Deployment, Service and Ingress of one app, and nothing else. Every object must carry our managed-by, app and instance labels or the call refuses before the first delete. A missing object counts as success so a retry is safe. The namespace stays. pullSecrets names Secrets we created for the app, deleted last under the same label rule.

func (*Client) ReviewRules

func (c *Client) ReviewRules(ctx context.Context, namespace string) (RulesReview, error)

ReviewRules asks the API server what the credential may do in a namespace.

type Condition

type Condition struct {
	Type    string
	Status  string
	Reason  string
	Message string
}

Condition is one Deployment condition, trimmed.

type Config

type Config struct {
	Creds    Credentials
	Guard    trafficpolicy.EgressGuard
	Resolver trafficpolicy.Resolver
	Timeout  time.Duration
	MaxBody  int64
}

Config describes one cluster connection.

type Credentials

type Credentials struct {
	Server     string
	ServerName string
	CA         []byte
	Token      string
	ClientCert []byte
	ClientKey  []byte
}

Credentials is one kubeconfig context reduced to inline material.

func ParseKubeconfig

func ParseKubeconfig(data []byte, contextName string, maxBytes int) (Credentials, error)

ParseKubeconfig reduces one context (empty means current-context) to inline credentials. Only the chosen context is validated, so merged files that carry exec users for other clusters still import.

type Limits

type Limits struct {
	Timeout       time.Duration
	MaxBody       int64
	KubeconfigMax int
}

Limits are the live runtime settings that bound one cluster call.

func LoadLimits

func LoadLimits(ctx context.Context, s SettingsReader) Limits

LoadLimits reads the limits live, so a settings change applies to the next call.

type LogResult

type LogResult struct {
	Pod       string
	Container string
	Text      string
	Truncated bool
}

LogResult is one bounded log read.

type Namespace

type Namespace struct {
	Name  string
	Phase string
}

Namespace is the trimmed view of a core/v1 Namespace.

type Node

type Node struct {
	Name    string
	Ready   bool
	Roles   []string
	Kubelet string
}

Node is the trimmed view of a core/v1 Node.

type ObjectRef

type ObjectRef struct {
	Kind string
	Name string
	Path string // collection path, without the name
}

ObjectRef names one namespaced or cluster scoped object by its API path.

type PodState

type PodState struct {
	Name   string
	Phase  string
	Reason string
	// Message is the last terminated or waiting message, truncated; never env values.
	Message string
}

PodState is the phase of one pod plus the reason a container is stuck, if any.

type RemoveResult

type RemoveResult struct {
	Deleted []string
	Absent  []string
}

RemoveResult lists what Remove deleted and what was already gone.

type Rendered

type Rendered struct {
	Deployment map[string]any
	Service    map[string]any
	Ingress    map[string]any // nil when no host
	// Secret is the pull secret, nil when none. It carries a credential, so YAML never prints it.
	Secret map[string]any
}

Rendered holds the objects as maps ready for YAML or JSON.

func Render

func Render(s AppSpec) (Rendered, error)

Render builds the Deployment, Service and optional Ingress.

func (Rendered) Refs

func (r Rendered) Refs(namespace string) []ObjectRef

Refs returns the API paths of every rendered object, namespace first.

func (Rendered) YAML

func (r Rendered) YAML() ([]byte, error)

YAML returns the objects as one multi-document stream, keys sorted.

type ResourceRule

type ResourceRule struct {
	Verbs     []string `json:"verbs"`
	APIGroups []string `json:"apiGroups"`
	Resources []string `json:"resources"`
}

ResourceRule mirrors authorization/v1 ResourceRule.

type Resources

type Resources struct {
	CPURequest    string
	MemoryRequest string
	CPULimit      string
	MemoryLimit   string
}

Resources carries values the caller reads from runtime settings, so the renderer holds no thresholds of its own.

type RulesReview

type RulesReview struct {
	Rules      []ResourceRule
	Incomplete bool
}

RulesReview is the decoded SelfSubjectRulesReview status.

func (RulesReview) IsClusterAdmin

func (r RulesReview) IsClusterAdmin() bool

IsClusterAdmin reports a wildcard rule over every group, resource and verb.

type SettingsReader

type SettingsReader interface {
	Limit(ctx context.Context, key string) int
	Duration(ctx context.Context, key string) time.Duration
	Bool(ctx context.Context, key string) bool
}

SettingsReader is the slice of the runtime settings service k8sconn needs.

type Status

type Status struct {
	Found           bool
	Replicas        int
	ReadyReplicas   int
	UpdatedReplicas int
	Conditions      []Condition
	Pods            []PodState
	IngressAddress  string
	// Reason is the first readable problem, empty when healthy.
	Reason string
}

Status is what a deployment looks like right now.

type StatusError

type StatusError struct{ Code int }

StatusError carries a non-2xx status without echoing the response body.

func (*StatusError) Error

func (e *StatusError) Error() string

Jump to

Keyboard shortcuts

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