api

package
v1.22.0 Latest Latest
Warning

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

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

Documentation

Overview

Package api provides the Kubernetes client and configuration for the nine.ch API.

Index

Constants

View Source
const (
	// ManagedByAnnotation is the annotation key marking objects that nctl created or updated.
	ManagedByAnnotation = "app.kubernetes.io/managed-by"
	// Name is the name of the CLI and the value of ManagedByAnnotation on objects managed by it.
	Name = cli.Name
	// RotateCredentialsAnnotation is the annotation key nctl sets to the time
	// it reset the credentials of a resource,
	// which makes the controller reconcile the resource.
	RotateCredentialsAnnotation = "nine.ch/rotate-credentials"
)
View Source
const (
	IssuerURLArg             = "--issuer-url="
	ClientIDArg              = "--client-id="
	ClientSecretArg          = "--client-secret="
	TokenURLArg              = "--token-url="
	UsePKCEArg               = "--use-pkce"
	InsecureStorageArg       = "--insecure-storage"
	CustomersPrefix          = "/Customers/"
	AuthCmdName              = "auth"
	ClientCredentialsCmdName = "client-credentials"
	OIDCCmdName              = "oidc"
)
View Source
const ClientSecretEnv = "NCTL_API_CLIENT_SECRET"

ClientSecretEnv is the environment variable providing the client secret of an APIServiceAccount. It takes precedence over a stored client secret. The client-credentials and login commands read it through their --client-secret flag.

View Source
const DefaultTokenCachePath = ".kube/cache/oidc-login"

DefaultTokenCachePath is the directory below the home directory holding the token cache of kubelogin.

Variables

This section is empty.

Functions

func ClientSecretKey added in v1.22.0

func ClientSecretKey(clientID, tokenURL string) string

ClientSecretKey returns the key of the client secret of clientID at tokenURL in the store of Credentials.ClientSecrets.

func GetToken added in v1.1.0

func GetToken(ctx context.Context, login OIDCLogin, credentials Credentials, out io.Writer) error

GetToken executes the OIDC login flow using kubelogin and writes the raw JSON ExecCredential result to out. The tokens are cached in credentials.Tokens(login.Storage).

func GetTokenFromConfig added in v1.1.0

func GetTokenFromConfig(ctx context.Context, cfg *rest.Config, credentials Credentials) (string, error)

GetTokenFromConfig takes a rest.Config and returns a valid OIDC access token or the static bearer token if it's set in the config. The tokens and client secrets of the login are kept in credentials.

func GetTokenFromExecConfig added in v1.1.0

func GetTokenFromExecConfig(ctx context.Context, execConfig *api.ExecConfig, credentials Credentials) (string, error)

GetTokenFromExecConfig runs the login of the exec plugin of execConfig in process and returns its token. The tokens and client secrets of the login are kept in credentials. A client secret in ClientSecretEnv takes precedence over a stored one.

func IsManagedBy added in v1.21.0

func IsManagedBy(annotations map[string]string) bool

IsManagedBy reports whether the annotations mark an object as managed by nctl.

func LoadingRules

func LoadingRules() (*clientcmd.ClientConfigLoadingRules, error)

func LookupClientSecret added in v1.22.0

func LookupClientSecret(ctx context.Context, store SecretStore, clientID, tokenURL string) (string, error)

LookupClientSecret returns the client secret of clientID at tokenURL from store. Without a stored secret, the error explains how to provide one.

func NamespacedName added in v1.1.0

func NamespacedName(name, project string) types.NamespacedName

func NewScheme

func NewScheme() (*runtime.Scheme, error)

NewScheme returns a *runtime.Scheme with all the relevant types registered.

func ObjectName added in v1.0.1

func ObjectName(obj runtimeclient.Object) types.NamespacedName

func TokenCacheConfig added in v1.22.0

func TokenCacheConfig() tokencache.Config

TokenCacheConfig returns the token cache configuration of nctl. Its directory holds the locks of the token cache and the files kubelogin cached tokens in.

func TokenCacheKey added in v1.22.0

func TokenCacheKey(issuerURL, clientID string) tokencache.Key

TokenCacheKey returns the key under which kubelogin caches the tokens of the OIDC client clientID at issuerURL.

Types

type ApplyResult added in v1.21.0

type ApplyResult string

ApplyResult tells what Client.ApplyManifest did with the object of the manifest.

const (
	ApplyResultCreated ApplyResult = "created"
	ApplyResultUpdated ApplyResult = "updated"
)

type Client

type Client struct {
	runtimeclient.WithWatch
	Config            *rest.Config
	KubeconfigPath    string
	Project           string
	Log               *log.Client
	KubeconfigContext string
	// contains filtered or unexported fields
}

func New

func New(ctx context.Context, apiClusterContext, project string, opts ...ClientOpt) (*Client, error)

New returns a new Client by loading a kubeconfig with the supplied context and project. The kubeconfig is discovered like this: * KUBECONFIG environment variable pointing at a file * $HOME/.kube/config if exists

The tokens and client secrets of the login are kept in KeyringCredentials unless WithCredentials is set.

func (*Client) ApplyManifest added in v1.21.0

func (c *Client) ApplyManifest(ctx context.Context, r io.Reader) (*unstructured.Unstructured, ApplyResult, error)

ApplyManifest creates the object described by the YAML or JSON manifest read from r, or updates it if it already exists, and returns it along with what happened.

func (*Client) ConnectionSecretData added in v1.21.0

func (c *Client) ConnectionSecretData(ctx context.Context, mg resource.Managed) (map[string][]byte, error)

ConnectionSecretData returns the data of the connection secret referenced by mg.

func (*Client) Create added in v1.14.0

func (c *Client) Create(ctx context.Context, obj client.Object, opts ...client.CreateOption) error

Create saves the object obj in the Kubernetes cluster. obj must be a struct pointer so that obj can be updated with the content returned by the Server.

func (*Client) CreateManifest added in v1.21.0

func (c *Client) CreateManifest(ctx context.Context, r io.Reader) (*unstructured.Unstructured, error)

CreateManifest creates the object described by the YAML or JSON manifest read from r and returns it.

func (*Client) Credentials added in v1.22.0

func (c *Client) Credentials() Credentials

Credentials returns the stores of the tokens and client secrets of the login.

func (*Client) DeleteManifest added in v1.21.0

func (c *Client) DeleteManifest(ctx context.Context, r io.Reader) (*unstructured.Unstructured, error)

DeleteManifest deletes the object described by the YAML or JSON manifest read from r and returns it.

func (*Client) DeploioRuntimeClient added in v1.8.0

func (c *Client) DeploioRuntimeClient(ctx context.Context, scheme *runtime.Scheme) (runtimeclient.Client, error)

func (*Client) DeploioRuntimeConfig added in v1.8.0

func (c *Client) DeploioRuntimeConfig(ctx context.Context) (*rest.Config, error)

func (*Client) GetConnectionSecret

func (c *Client) GetConnectionSecret(ctx context.Context, mg resource.Managed) (*corev1.Secret, error)

func (*Client) GetObject added in v1.8.4

func (c *Client) GetObject(ctx context.Context, name string, obj runtimeclient.Object) error

GetObject gets the object in the current client project with some ux-improvements like hinting when the object has been found in a different project of the same organization.

func (*Client) ListObjects added in v1.8.4

func (c *Client) ListObjects(ctx context.Context, list runtimeclient.ObjectList, options ...ListOpt) error

ListObjects lists objects in the current client project with some ux-improvements like hinting when a resource has been found in a different project of the same organization.

func (*Client) Name

func (c *Client) Name(name string) types.NamespacedName

func (*Client) Organization added in v1.8.2

func (c *Client) Organization() (string, error)

func (*Client) Projects added in v1.8.4

func (c *Client) Projects(ctx context.Context, onlyName string) ([]management.Project, error)

Projects returns either all existing Projects or only the specific project identified by the "onlyName" parameter

func (*Client) RotateCredentials added in v1.21.0

func (c *Client) RotateCredentials(ctx context.Context, mg resource.Managed) (types.UID, error)

RotateCredentials makes the controller of mg generate new credentials and write them to a new connection secret. It deletes the connection secret of mg and then sets RotateCredentialsAnnotation on mg to the current time, like kubectl rollout restart does.

It returns the UID of the deleted secret, which is empty if the secret was missing already.

func (*Client) Token added in v1.1.0

func (c *Client) Token(ctx context.Context) string

func (*Client) Update added in v1.14.0

func (c *Client) Update(ctx context.Context, obj client.Object, opts ...client.UpdateOption) error

Update updates the given obj in the Kubernetes cluster. obj must be a struct pointer so that obj can be updated with the content returned by the Server.

type ClientOpt added in v1.1.0

type ClientOpt func(c *Client) error

func DefaultAnnotations added in v1.14.0

func DefaultAnnotations(k, v string) ClientOpt

DefaultAnnotations configures the client to set default annotations on all resources created or updated.

func LogClient added in v1.1.0

func LogClient(ctx context.Context, address string, insecure bool) ClientOpt

LogClient sets up a log client connected to the provided address.

func StaticToken added in v1.7.1

func StaticToken() ClientOpt

StaticToken configures the client to get a bearer token once and then set it statically in the client config. This means the client will not automatically renew the token when it expires. The token is obtained after all options are applied, so it uses the store of WithCredentials.

func WithCredentials added in v1.22.0

func WithCredentials(credentials Credentials) ClientOpt

WithCredentials keeps the tokens and client secrets of the login in credentials instead of KeyringCredentials.

type Credentials added in v1.22.0

type Credentials interface {
	// Tokens returns the store caching the OIDC tokens under the keys of [TokenCache].
	Tokens(Storage) SecretStore
	// ClientSecrets returns the store of the client secrets of APIServiceAccounts
	// under the keys of [ClientSecretKey].
	ClientSecrets(Storage) SecretStore
}

Credentials provides the stores of the tokens and client secrets of the logins.

type ExecArgs added in v1.22.0

type ExecArgs struct {
	// Command is [OIDCCmdName] or [ClientCredentialsCmdName].
	Command string
	// IssuerURL and UsePKCE configure the OIDC login.
	IssuerURL string
	UsePKCE   bool
	// Storage is where the OIDC login caches its tokens
	// and the client-credentials login stores its client secret.
	Storage  Storage
	ClientID string
	// TokenURL is the token endpoint of the client-credentials login.
	TokenURL string
	// ClientSecret is only set by kubeconfigs written before the client secret was stored,
	// newer ones leave it to [LookupClientSecret].
	ClientSecret string
}

ExecArgs are the arguments of the exec plugins nctl writes to the kubeconfig, which run the OIDCCmdName or ClientCredentialsCmdName login of nctl.

func ParseExecArgs added in v1.22.0

func ParseExecArgs(args []string) (ExecArgs, error)

ParseExecArgs parses the arguments of an exec plugin written by ExecArgs.Args. It ignores arguments it does not know.

func (ExecArgs) Args added in v1.22.0

func (a ExecArgs) Args() []string

Args returns the arguments of the exec plugin. It panics if Command is neither OIDCCmdName nor ClientCredentialsCmdName.

func (ExecArgs) OIDCLogin added in v1.22.0

func (a ExecArgs) OIDCLogin() OIDCLogin

OIDCLogin returns the OIDC login the exec plugin runs.

type KeyringCredentials added in v1.22.0

type KeyringCredentials struct {
	// OnFallback, if set, is called when a client secret or token is written to the file at path
	// because the keyring failed with err.
	// It is called on every such write of a client secret, which only a login writes,
	// but only on the first of a token, which every refresh writes.
	OnFallback func(path string, err error)
}

KeyringCredentials stores the tokens and client secrets of the logins in the keyring of the operating system, falling back to files only the user can read. Its token files are those of kubelogin, so sessions kubelogin cached keep working. The zero value is ready to use and is the default of New.

func (KeyringCredentials) ClientSecrets added in v1.22.0

func (c KeyringCredentials) ClientSecrets(storage Storage) SecretStore

ClientSecrets returns the store of the client secrets, whose files are below the user configuration directory, see os.UserConfigDir. If there is none, every operation of the store fails.

func (KeyringCredentials) Tokens added in v1.22.0

func (c KeyringCredentials) Tokens(storage Storage) SecretStore

Tokens returns the store of the OIDC tokens.

type ListOpt added in v1.8.4

type ListOpt func(opts *ListOpts)

func AllNamespaces added in v1.8.4

func AllNamespaces() ListOpt

func AllProjects added in v1.8.4

func AllProjects() ListOpt

func MatchLabel added in v1.8.4

func MatchLabel(k, v string) ListOpt

func MatchName added in v1.8.4

func MatchName(name string) ListOpt

func Watch added in v1.11.0

func Watch(f WatchFunc) ListOpt

type ListOpts added in v1.8.4

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

type OIDCLogin added in v1.22.0

type OIDCLogin struct {
	IssuerURL string
	ClientID  string
	UsePKCE   bool
	// Storage is where the login caches its tokens.
	Storage Storage
}

OIDCLogin configures an OIDC login.

type SecretStore added in v1.22.0

type SecretStore interface {
	Get(ctx context.Context, key string) (string, error)
	Set(ctx context.Context, key, secret string) error
	Delete(ctx context.Context, key string) error
}

SecretStore keeps secrets by key. Get and Delete return an error matching io/fs.ErrNotExist if the store holds no secret for the key.

type Storage added in v1.22.0

type Storage int

Storage selects where a SecretStore writes its secrets. Stores of every Storage read the secrets written with StorageFile.

const (
	// StorageKeyring writes secrets to the keyring of the operating system.
	StorageKeyring Storage = iota
	// StorageFile writes secrets to plain text files only the user can read.
	StorageFile
)

func (Storage) String added in v1.22.0

func (s Storage) String() string

type TokenCache added in v1.22.0

type TokenCache struct {
	Store SecretStore
}

TokenCache keeps OIDC tokens in a SecretStore. Its keys and values are the file names and contents kubelogin uses for its token cache, so a store whose files are those below the directory of TokenCacheConfig keeps the sessions kubelogin cached.

func (TokenCache) Delete added in v1.22.0

func (c TokenCache) Delete(ctx context.Context, key tokencache.Key) error

Delete removes the cached token set of key. It returns an error matching io/fs.ErrNotExist if there is none.

func (TokenCache) Find added in v1.22.0

func (c TokenCache) Find(ctx context.Context, key tokencache.Key) (*oidc.TokenSet, error)

Find returns the cached token set of key. It returns an error matching io/fs.ErrNotExist if there is none.

func (TokenCache) Save added in v1.22.0

func (c TokenCache) Save(ctx context.Context, key tokencache.Key, tokenSet oidc.TokenSet) error

Save caches tokenSet under key.

type TokenGetter added in v1.2.0

type TokenGetter interface {
	GetTokenString(ctx context.Context, login OIDCLogin) (string, error)
}

TokenGetter gets the token of an OIDC login.

func NewTokenGetter added in v1.22.0

func NewTokenGetter(credentials Credentials) TokenGetter

NewTokenGetter returns a TokenGetter running GetToken with the tokens cached in credentials.

type UserInfo added in v1.2.0

type UserInfo struct {
	User    string
	Orgs    []string
	Project string
}

func GetUserInfoFromToken added in v1.2.0

func GetUserInfoFromToken(tokenString string) (*UserInfo, error)

type WatchFunc added in v1.11.0

type WatchFunc func(list runtimeclient.ObjectList) error

Directories

Path Synopsis
Package config provides the nctl specific configuration stored in the kubeconfig.
Package config provides the nctl specific configuration stored in the kubeconfig.
Package gitinfo provides a client to interact with the git information service to retrieve metadata about git repositories.
Package gitinfo provides a client to interact with the git information service to retrieve metadata about git repositories.
internal
credential
Package credential stores secrets in the keyring of the operating system and falls back to files only the user can read where the keyring is unavailable.
Package credential stores secrets in the keyring of the operating system and falls back to files only the user can read where the keyring is unavailable.
Package log provides functionality to interact with the Nine logging API.
Package log provides functionality to interact with the Nine logging API.
login module

Jump to

Keyboard shortcuts

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