cloud

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2026 License: Apache-2.0 Imports: 18 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AWSProfileFields

func AWSProfileFields(name string) (map[string]string, error)

AWSProfileFields returns a profile's stored settings, merged across both files, for pre-filling an edit form.

func Clear

func Clear(scope string) *shellcfg.Script

Clear removes cx's overrides for one provider or all of them. Afterwards the shell falls back to whatever the machine-wide defaults are, which for gcloud means the shared active_config file again.

func ConfigPath added in v0.1.2

func ConfigPath() string

ConfigPath returns cx's own configuration file, which is separate from any vendor's. CX_CONFIG overrides it, chiefly so tests never read the file belonging to whoever is running them.

func DeleteAWSProfile

func DeleteAWSProfile(name string) error

DeleteAWSProfile removes a profile from both AWS files.

It deliberately does not touch any sso-session block the profile referred to: those are shared, and removing one would break every other profile using it.

func DeleteGCPConfig

func DeleteGCPConfig(name string) error

DeleteGCPConfig removes a gcloud configuration.

func GCPConfigFields

func GCPConfigFields(name string) (map[string]string, error)

GCPConfigFields returns a gcloud configuration's properties, flattened to the names the forms use.

func HasDanger

func HasDanger(alerts []Alert) bool

HasDanger reports whether any alert describes state that can misdirect a command. Callers use it to decide an exit code.

func LoadGCP

func LoadGCP() ([]Target, GCPState, error)

LoadGCP reads gcloud configurations straight from disk. It deliberately does not invoke the gcloud CLI: gcloud is a Python program that takes on the order of a second to start, which makes a per-configuration shell loop painfully slow, and its config files are a stable documented format.

func LoadK8s added in v0.2.0

func LoadK8s() ([]Target, K8sState, error)

LoadK8s reads the Kubernetes contexts available to this shell.

Unlike the AWS and gcloud loaders this shells out, which is a deliberate exception to the rule that reading configuration does not. kubeconfig is YAML, and the alternatives are worse than the subprocess: a YAML dependency would be a third-party parser running against a file that holds client certificates and bearer tokens, and a hand-rolled one would be a YAML subset parser, which is a bug factory. `kubectl config view -o json` costs about 28ms here against gcloud's 400ms, it is a Go binary rather than a Python one, and it redacts every credential before cx ever sees the bytes. The prompt segment does not call this; see PromptK8s.

func MarkProduction added in v0.1.2

func MarkProduction(targets []Target, p Production, provider string)

MarkProduction sets Sensitive on every target whose name is flagged.

It is applied after loading rather than inside it, so the loaders stay concerned only with what the vendor's files say.

func ProbeADC

func ProbeADC(ctx context.Context, a *ADC)

ProbeADC resolves who ADC actually authenticates as. For a user credential the file holds only a refresh token, so the identity can be discovered only by minting an access token and asking Google who it belongs to.

func ProbeAWS

func ProbeAWS(ctx context.Context, targets []Target, concurrency int)

ProbeAWS resolves each profile's real identity by calling STS, concurrently and with a hard timeout. Probing serially -- as a shell loop must -- costs seconds per profile on a slow link, which is the main reason this tool is not a shell script.

It shells out to the AWS CLI rather than using the SDK so that SSO token caches, credential_process helpers, and every other resolution mechanism the user has already configured work identically here and in their terminal.

func ProbeGCP

func ProbeGCP(ctx context.Context, targets []Target, concurrency int)

ProbeGCP checks whether each configuration's account still holds a usable refresh token, concurrently.

func PromptK8s added in v0.2.0

func PromptK8s() (name string, unsafe bool)

PromptK8s resolves this shell's context cheaply enough to run before every prompt: one small file read and no subprocess.

LoadK8s costs a kubectl invocation, which is fine for the dashboard and far too slow here. The merge rule it reproduces is kubectl's own: current-context comes from the first file on the search path that sets one. unsafe reports that the file which decided it is shared with every other terminal.

func ShortWarnings

func ShortWarnings(gcp []Target, state GCPState, adc ADC) []string

ShortWarnings returns terse codes for hazards worth putting in a shell prompt. It is deliberately narrow: a prompt has room for a nudge, not an explanation, and `cx status` is where the full reasoning lives.

Only locally-determinable hazards appear here. Anything needing a network round trip is excluded, because this runs before every prompt.

func SwitchAWS

func SwitchAWS(profile string) *shellcfg.Script

SwitchAWS builds the environment changes that point a shell at an AWS profile.

func SwitchGCP

func SwitchGCP(config string) *shellcfg.Script

SwitchGCP builds the environment changes that point a shell at a gcloud configuration.

It deliberately does not run `gcloud config configurations activate`. That command writes a file shared by every shell on the machine, so it would retarget terminals the user is not looking at. Setting the environment variable affects this shell and only this shell.

func SwitchK8s added in v0.2.0

func SwitchK8s(contextName string) (*shellcfg.Script, error)

SwitchK8s points this shell, and only this shell, at a Kubernetes context.

It writes a kubeconfig carrying nothing but current-context and puts it at the front of KUBECONFIG. kubectl merges the files on the search path and takes current-context from the first that sets one, so this shell is retargeted while the shared kubeconfig is never written to.

Copying the whole kubeconfig is the obvious alternative and a worse one: the copy goes stale the moment a cluster is added, and it duplicates every bearer token and client certificate into a second file on disk. The overlay holds one context name and no credentials at all.

It also makes `kubectl config use-context` shell-local as a side effect, because kubectl writes current-context to the first file on the search path, which is now this one. The habit cx is trying to make safe stops being dangerous, rather than being reported forever.

func ValidateName

func ValidateName(name string) error

ValidateName reports why a name is unusable, or nil if it is fine.

func WriteAWSSSO

func WriteAWSSSO(s AWSSSOSpec) error

WriteAWSSSO creates or updates an SSO profile plus the sso-session block it refers to. This is the credential kind worth steering people towards: the CLI refreshes its tokens, so the profile does not silently go stale.

func WriteAWSStatic

func WriteAWSStatic(s AWSStaticSpec) error

WriteAWSStatic creates or updates a key-based profile. Keys go to the credentials file and settings to the config file, matching where the AWS CLI itself puts them.

func WriteGCPConfig

func WriteGCPConfig(s GCPConfigSpec) error

WriteGCPConfig creates or updates a gcloud configuration by writing its file directly.

gcloud stores configurations as plain INI files, and shelling out to `gcloud config configurations create` would cost about a second per call for something that is three lines of text.

Types

type ADC

type ADC struct {
	// Present reports whether an ADC file exists.
	Present bool
	// Path is where it was found.
	Path string
	// Kind is the credential type recorded in the file.
	Kind CredKind
	// QuotaProject is the project billed for API calls made with ADC. When it
	// disagrees with the active gcloud project, that is worth flagging.
	QuotaProject string
	// Identity is the resolved principal.
	Identity string
	// Health is the probe result.
	Health Health
	// Detail explains a non-Valid health.
	Detail string
}

ADC describes Application Default Credentials: the credential set used by Terraform, the Google client libraries, and essentially everything that is not the gcloud binary itself.

ADC is entirely independent of the active gcloud configuration. A shell can have `gcloud config` pointing at a staging project while ADC authenticates as a different principal entirely, and nothing in the standard tooling shows both at once.

Note what ADC does and does not decide. It supplies the identity Terraform and the client libraries authenticate as. Its quota project decides who is billed for API calls made by the client libraries -- but not by Terraform, whose google provider has its own billing_project and does not read the ADC file's quota project at all.

func LoadADC

func LoadADC() ADC

LoadADC reads the ADC file without contacting the network.

type AWSSSOSpec

type AWSSSOSpec struct {
	Name        string
	SessionName string
	StartURL    string
	SSORegion   string
	AccountID   string
	RoleName    string
	Region      string
}

AWSSSOSpec describes a profile authenticated through IAM Identity Center.

type AWSStaticSpec

type AWSStaticSpec struct {
	Name            string
	Region          string
	AccessKeyID     string
	SecretAccessKey string
	// SessionToken is optional, and when set makes the profile one that expires.
	SessionToken string
}

AWSStaticSpec describes a profile authenticated with long-lived or pasted keys.

type Action

type Action struct {
	// Label is what the menu shows.
	Label string
	// Key is the single keystroke that selects it.
	Key string
	// Cmd and Args are the command to run.
	Cmd  string
	Args []string
	// Hint explains what the flow does, for the menu.
	Hint string
}

Action is an external command cx runs on the user's behalf, by suspending the dashboard and handing the terminal over. cx never reimplements these flows: they are interactive, they change over time, and the vendor CLIs already do them correctly.

func LoginAction

func LoginAction(t Target) Action

LoginAction returns the command that re-authenticates an AWS profile.

The right command depends on how the profile gets its credentials: an SSO profile needs a new SSO session, while a static profile has no login flow at all and can only be re-entered by hand.

func LoginActionGCP

func LoginActionGCP(t Target) Action

LoginActionGCP returns the command that re-authenticates a gcloud configuration's account.

type ActiveSource

type ActiveSource int

ActiveSource records how the current gcloud configuration was selected. The distinction is the whole reason this tool exists: an env-var selection is private to one shell, while the on-disk selection is shared by every shell on the machine and changes under you when another terminal switches.

const (
	// SourceNone means no configuration is selected at all.
	SourceNone ActiveSource = iota
	// SourceShell means CLOUDSDK_ACTIVE_CONFIG_NAME is set: safe, shell-local.
	SourceShell
	// SourceGlobal means the selection comes from ~/.config/gcloud/active_config,
	// which is machine-wide mutable state.
	SourceGlobal
)

func (ActiveSource) String

func (s ActiveSource) String() string

type Alert

type Alert struct {
	Severity Severity
	// Title states what is wrong.
	Title string
	// Fix states what to do about it.
	Fix string
}

Alert is a hazard that spans more than one target, and so cannot be expressed by any single row of the dashboard.

func Audit

func Audit(gcp []Target, state GCPState, adc ADC) []Alert

Audit inspects the whole resolved picture for the ways a shell can end up pointed somewhere other than where its operator believes.

This lives in the domain layer rather than the UI because both the dashboard and the scriptable --plain mode need it, and because a non-zero exit from the latter is the thing that can gate a `terraform apply`.

func AuditK8s added in v0.2.0

func AuditK8s(contexts []Target, state K8sState) []Alert

AuditK8s reports the ways a shell's Kubernetes context can be wrong.

It is separate from Audit rather than another parameter because Kubernetes is optional: most shells have no kubectl at all, and a caller with nothing to report should not have to say so.

type CredKind

type CredKind string

CredKind describes how a target obtains credentials. This matters more than it looks: static long-lived keys and hand-pasted session tokens rot, while SSO and credential_process refresh themselves. Surfacing the distinction is the point of the dashboard.

const (
	KindStatic     CredKind = "static"          // access key + secret, long-lived
	KindStaticTemp CredKind = "static+token"    // access key + secret + pasted session token
	KindSSO        CredKind = "sso"             // legacy inline sso_* keys
	KindSSOSession CredKind = "sso-session"     // modern sso_session reference
	KindAssumeRole CredKind = "assume-role"     // role_arn + source_profile
	KindProcess    CredKind = "process"         // credential_process
	KindUser       CredKind = "user"            // GCP: an authorized user account
	KindServiceAcc CredKind = "service-account" // GCP: a service account key
	KindContext    CredKind = "context"         // Kubernetes: a kubeconfig context
	KindNone       CredKind = "none"            // nothing configured
)

func (CredKind) Rots

func (k CredKind) Rots() bool

Rots reports whether this credential kind expires without a way to refresh itself. These are the targets that produce the "it worked yesterday" class of failure, so the UI calls them out.

type GCPConfigSpec

type GCPConfigSpec struct {
	Name    string
	Account string
	Project string
	Region  string
}

GCPConfigSpec describes a gcloud configuration.

type GCPState

type GCPState struct {
	// Active is the configuration name in effect for this shell.
	Active string
	// Source is how Active was chosen.
	Source ActiveSource
	// Global is the machine-wide selection from the active_config file.
	Global string
	// GlobalMissing reports that active_config names a configuration that does
	// not exist, which makes gcloud silently fall back to built-in defaults.
	GlobalMissing bool
	// ProjectOverride and AccountOverride hold CLOUDSDK_CORE_* values, which
	// beat the configuration's own properties and are easy to forget about.
	ProjectOverride string
	AccountOverride string
}

GCPState describes how the current shell resolves gcloud configuration, and where that resolution disagrees with the machine-wide default.

func (GCPState) Unsafe

func (s GCPState) Unsafe() bool

Unsafe reports whether the current shell's project is determined by state that another terminal can change without warning.

type Health

type Health int

Health is the result of probing a target's credentials.

const (
	// Unknown means the target has not been probed yet this refresh.
	Unknown Health = iota
	// Probing means a probe is currently in flight.
	Probing
	// Valid means the credentials resolved to a real identity.
	Valid
	// Expired means credentials exist but the provider rejected them. For AWS
	// this is the common case for a hand-pasted session token; for GCP it means
	// no unexpired refresh token for the account.
	Expired
	// Missing means the target names credentials that are not present at all.
	Missing
)

func (Health) String

func (h Health) String() string

type K8sState added in v0.2.0

type K8sState struct {
	// Active is the context in effect for this shell.
	Active string
	// Source is how Active was chosen.
	Source ActiveSource
	// Shared is the context selected in the kubeconfig every terminal reads.
	Shared string
	// Available reports whether the context could be read at all.
	Available bool
	// Detail explains a false Available, for the pane to show instead of rows.
	Detail string
}

K8sState describes how this shell resolves its Kubernetes context, and whether that resolution is one another terminal can change.

func (K8sState) Unsafe added in v0.2.0

func (s K8sState) Unsafe() bool

Unsafe reports whether this shell's context comes from a file another terminal can rewrite. Identical in spirit to GCPState.Unsafe: the hazard is shared mutable selection, not anything specific to gcloud.

type Production added in v0.1.2

type Production struct {
	AWS []string
	GCP []string
	K8s []string
}

Production holds the name patterns a user has flagged as production:

[production]
aws = client-prod, *-prod
gcp = acme-prod, prod-*

Matching is by name rather than by account or project id, because the prompt segment and `cx status --no-probe` must answer without touching the network, and for several credential kinds the account is known only after a probe. A name is what the user types, so it is also what a confirmation can meaningfully quote back at them.

func LoadProduction added in v0.1.2

func LoadProduction() (Production, error)

LoadProduction reads the flagged patterns. A missing configuration file means nothing is flagged, which is not an error.

func (Production) Matches added in v0.1.2

func (p Production) Matches(provider, name string) bool

Matches reports whether a target name is flagged as production.

path.Match rather than filepath.Match: the subject is a target name, not a path, and filepath.Match gives the separator a meaning on some platforms that has no bearing here.

func (Production) Patterns added in v0.1.2

func (p Production) Patterns(provider string) []string

Patterns returns the patterns for a provider, "aws" or "gcp".

type Severity

type Severity int

Severity ranks an audit finding.

const (
	// Warn marks state that is merely surprising.
	Warn Severity = iota
	// Danger marks state that can send a command to the wrong account or
	// project without the user noticing.
	Danger
)

type Target

type Target struct {
	// Name is the identifier the user switches to.
	Name string
	// Kind is how credentials are obtained.
	Kind CredKind
	// Account is the human-facing owner: an AWS account ID, or a GCP account
	// email. Populated by a probe where it is not known statically.
	Account string
	// Scope is the blast radius: an AWS region, or a GCP project. For the
	// active GCP target it is the effective value, with any environment
	// override already applied.
	Scope string
	// ConfiguredScope is what the configuration file itself says, before any
	// environment override. Scope carries the effective value, so once an
	// override is in force the original is gone -- and comparing the two is
	// exactly what the audit needs in order to tell a silent retarget from an
	// override that merely restates the configuration.
	ConfiguredScope string
	// Identity is the resolved principal (an AWS ARN, a GCP email).
	Identity string
	// Active reports whether this target applies to the current shell.
	Active bool
	// Health is the probe result.
	Health Health
	// Detail carries a short explanation for a non-Valid health, shown inline.
	Detail string
	// Sensitive marks a target the user has flagged as production.
	Sensitive bool
	// ProbedAt records when Health was last established.
	ProbedAt time.Time
}

Target is one switchable destination: an AWS profile, a GCP configuration, or the ADC slot. The zero value is not useful; construct via the provider loaders.

func LoadAWS

func LoadAWS() ([]Target, error)

LoadAWS reads the AWS profiles from disk without contacting the network. Health is left Unknown; call ProbeAWS to fill it in.

Jump to

Keyboard shortcuts

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