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
- Variables
- func AllowPrivateAPI(ctx context.Context, s SettingsReader) bool
- func BuildPullSecret(spec AppSpec, registry, username, password string) (map[string]any, error)
- func ImageRegistryHost(image string) string
- func Labels(app, instance string) map[string]string
- func NormalizeRegistryHost(s string) string
- func ParseServer(raw string) (*url.URL, error)
- func PullSecretName(app string) string
- type AppSpec
- type Client
- func (c *Client) Apply(ctx context.Context, spec AppSpec, r Rendered) ([]string, error)
- func (c *Client) CredentialIsClusterAdmin(ctx context.Context) (bool, error)
- func (c *Client) DeletePullSecret(ctx context.Context, namespace, name, app, instance string) error
- func (c *Client) DeploymentStatus(ctx context.Context, namespace, app, instance string) (Status, error)
- func (c *Client) Do(ctx context.Context, method, path string, body []byte) ([]byte, error)
- func (c *Client) EnsureNamespace(ctx context.Context, name string, allowUnmanaged bool) error
- func (c *Client) ListNamespaces(ctx context.Context) ([]Namespace, error)
- func (c *Client) ListNodes(ctx context.Context) ([]Node, error)
- func (c *Client) PodLogs(ctx context.Context, namespace, app, instance, pod, container string, tail int, ...) (LogResult, error)
- func (c *Client) Remove(ctx context.Context, namespace, app, instance string, pullSecrets ...string) (RemoveResult, error)
- func (c *Client) ReviewRules(ctx context.Context, namespace string) (RulesReview, error)
- type Condition
- type Config
- type Credentials
- type Limits
- type LogResult
- type Namespace
- type Node
- type ObjectRef
- type PodState
- type RemoveResult
- type Rendered
- type ResourceRule
- type Resources
- type RulesReview
- type SettingsReader
- type Status
- type StatusError
Constants ¶
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.
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.
const FieldManager = "levelrail"
FieldManager owns every field Levelrail applies.
const SecretTypeDockerConfig = "kubernetes.io/dockerconfigjson"
SecretTypeDockerConfig is the Secret type the kubelet reads image pull credentials from.
Variables ¶
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.
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.
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.
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.
var ErrNamespaceCreateForbidden = errors.New("k8sconn: the credential cannot create the namespace")
ErrNamespaceCreateForbidden means the namespace is missing and the credential may not create it.
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.
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.
var ErrRefused = errors.New("k8sconn: kubeconfig field refused")
ErrRefused marks a kubeconfig field Levelrail will not honour.
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 ¶
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 ¶
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 ¶
Labels returns the ownership labels for an app. A non-empty instance adds the install id.
func NormalizeRegistryHost ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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) EnsureNamespace ¶
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 ¶
ListNamespaces returns every namespace with its phase.
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 ¶
ReviewRules asks the API server what the credential may do in a namespace.
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 ¶
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 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 ¶
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.
type ResourceRule ¶
type ResourceRule struct {
Verbs []string `json:"verbs"`
APIGroups []string `json:"apiGroups"`
Resources []string `json:"resources"`
}
ResourceRule mirrors authorization/v1 ResourceRule.
type Resources ¶
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