Documentation
¶
Overview ¶
Package util provides shared utilities for the CLI.
Shared command lifecycle ¶
WithClient(cmd, fn) wraps context creation, login, session-key persistence + logout, and SilenceUsage so command RunE functions don't repeat that plumbing. Read flags first (so flag errors still print usage), then run the API calls and rendering inside fn, which receives the context and a logged-in *api.Client.
Shared output helpers ¶
Entity commands render results as JSON or pterm tables. These helpers keep that output consistent and remove the per-entity duplication; the typed JSON output structs (one per entity) stay in their packages and are passed in generically:
- PrintJSON / FprintJSON marshal a value as indented JSON (single object or array), to Out or an explicit io.Writer.
- PrintJSONColumnFiltered keeps only the requested keys when the user passed an explicit --column subset.
- PrintTable renders a pterm table from a column list and a per-cell value function; it is generic over the item type.
- RenderTable is the single pterm render path, for callers that build their own TableData. It is the only place table cells are sanitized, so callers pass raw values, and it writes to Out.
- PermissionsToJSONOutput / PrintPermissionTable render the permission output shared by the resource and folder commands.
Terminal safety ¶
Passbolt stores names, usernames and URIs verbatim, so anything rendered for a human is server-controlled text. Every such write goes through Out or Err, which replace control sequences with U+FFFD, and single-line values are narrowed further with Sanitize (\n and \t survive the stream writer by design, so a multi-line value such as a description is printed without it). Table cells are sanitized once, in RenderTable. JSON output escapes those runes instead of replacing them, so the document still parses.
Replacing keeps the change visible: "ad\u200bmin" and "admin" used to render identically. Execute then flushes and warns, on one line, after the output. forbidigo enforces the rule; the exceptions are completions and the exec child's stdio, which are machine-facing, and the keepass progressbar, which needs cursor control and renders no server text. The SDK's own debug log writes raw server responses straight to os.Stdout, so --debug output is not sanitized; it is opt-in and for diagnosis, not normal use.
Config and output files ¶
The config file holds secrets in cleartext; it is written and checked through the securefile subpackage, and WarnIfExposed warns on stderr about a secret file someone else owns or others can still read.
Index ¶
- Constants
- Variables
- func ApproveResource(ctx context.Context, id, name string) error
- func ApproveResourceRead(ctx context.Context, client *api.Client, id string) error
- func CELExpressionReferencesFields(celCmd string, fieldNames []string, options ...cel.EnvOption) (bool, error)
- func Confirm(prompt string) (bool, error)
- func CurrentDialog() agent.Dialog
- func Eprint(args ...any)
- func Eprintf(format string, args ...any)
- func Eprintln(args ...any)
- func Exit(code int)
- func ExplainAPIError(op string, err error) error
- func ExplainReadError(op, slug string, err error) error
- func ExplainWriteError(op, slug string, err error) error
- func FlushOutputs()
- func FprintJSON(w io.Writer, v any) error
- func GetClient(ctx context.Context) (*api.Client, error)
- func GetClientCertificate() (tls.Certificate, error)
- func GetContext() (context.Context, context.CancelFunc)
- func GetHTTPClient() (*http.Client, error)
- func InitCELProgram(celCmd string, options ...cel.EnvOption) (*cel.Program, error)
- func IsInteractive() bool
- func NewClient(ctx context.Context) (*api.Client, error)
- func NewClientWithHTTP(ctx context.Context, httpClient *http.Client) (*api.Client, error)
- func NewSanitizingWriter(dest io.Writer) io.Writer
- func NoColumnsError(valid []string) error
- func Print(args ...any)
- func PrintJSON(v any) error
- func PrintJSONColumnFiltered[T any](items []T, columns []string) error
- func PrintPermissionTable(columns []string, permissions []api.Permission) error
- func PrintTable[T any](columns []string, items []T, ...) error
- func Printf(format string, args ...any)
- func Println(args ...any)
- func ReadPassword(prompt string) (string, error)
- func RenderTable(data pterm.TableData)
- func Sanitize(text string) string
- func SaveSessionKeysAndLogout(ctx context.Context, client *api.Client)
- func SessionKeyWarning(err error)
- func WarnIfExposed(path, holds string)
- func WarnReplacements()
- func WithClient(cmd *cobra.Command, fn func(ctx context.Context, client *api.Client) error) error
- func WithMachineClient(cmd *cobra.Command, fn func(context.Context, *api.Client) error) error
- func WriteViperConfig(path string) error
- type ColumnAlias
- type ColumnAliasResolver
- type ColumnRegistry
- func (r *ColumnRegistry[T]) CelEnvOptions() []cel.EnvOption
- func (r *ColumnRegistry[T]) DefaultTableColumns() []string
- func (r *ColumnRegistry[T]) Filter(ctx context.Context, items []T, celCmd string) ([]T, error)
- func (r *ColumnRegistry[T]) RequiresSecrets(columns []string) bool
- func (r *ColumnRegistry[T]) Resolver() *ColumnAliasResolver
- func (r *ColumnRegistry[T]) SecretCelNames() []string
- func (r *ColumnRegistry[T]) TableValue(item T, col string) (string, bool)
- type ColumnSpec
- type PermissionJSONOutput
Constants ¶
const ConfigExposure = "If it is a passbolt config it holds your private key and passphrase in cleartext"
ConfigExposure is what WarnIfExposed says a config file holds.
Variables ¶
var ( // ErrNoID is returned by commands that require an --id flag when none is provided. ErrNoID = errors.New("no ID provided") // ErrNoColumns is returned by list/get commands when no output column is selected. ErrNoColumns = errors.New("no columns specified") )
Sentinel errors for recurring CLI input-validation failures. They are returned (optionally wrapped with extra context via fmt.Errorf and %w) so callers and tests can match them with errors.Is rather than comparing message strings.
var ( // DataOut carries validated machine protocols without terminal sanitization. DataOut io.Writer = os.Stdout Out io.Writer = NewSanitizingWriter(os.Stdout) Err io.Writer = NewSanitizingWriter(os.Stderr) )
Out and Err wrap stdout and stderr, so anything printed to the terminal is cleaned on the way out. Raw output (--json, completions, subprocess stdio) skips them.
GetClient gets a Logged in Passbolt Client ClientProvider, ClientRelease and PasswordPrompt are scoped to a serialized agent invocation. They remain nil in ordinary CLI execution.
var ClientRelease func(context.Context, *api.Client)
var ConfirmationPrompt func(string) (bool, error)
Confirm asks a yes/no question on stderr; a non-terminal gets ErrNotInteractive.
var ErrNotInteractive = errors.New("stdin is not a terminal")
ErrNotInteractive is returned by Confirm when there is no terminal to ask.
var InvocationContext = context.Background()
var InvocationDialog *agent.Dialog
InvocationDialog is scoped to a serialized agent request so stdin can remain a machine protocol while authentication and selection use the caller's terminal.
var PasswordPrompt func(string) (string, error)
var PermissionColumns = []string{
"ID", "Aco", "AcoForeignKey", "Aro", "AroForeignKey", "Type", "CreatedTimestamp", "ModifiedTimestamp",
}
PermissionColumns lists the column names accepted by the permission table commands (resource/folder permission). Used to build "valid columns" guidance.
var ProxyEnvironment []string
ProxyEnvironment is nil for ordinary commands and a request-local environment for agent calls. A fresh proxy function avoids net/http's global env cache.
var RedactServerErrors bool
ResourceApproval is scoped to a serialized agent invocation and called before requesting a resource secret. Names are metadata, not decrypted passwords.
Functions ¶
func ApproveResource ¶ added in v0.6.0
func ApproveResourceRead ¶ added in v0.6.0
func CELExpressionReferencesFields ¶
func CELExpressionReferencesFields(celCmd string, fieldNames []string, options ...cel.EnvOption) (bool, error)
CELExpressionReferencesFields checks if a CEL expression references any of the given field names. Returns true if the expression references at least one of the specified fields.
func CurrentDialog ¶ added in v0.6.0
func Exit ¶
func Exit(code int)
Exit ends the process the way Execute does. Every exit goes through here, or output printed just before it leaves without its warning.
func ExplainAPIError ¶
ExplainAPIError wraps err with operation-level context and, when err carries an *api.APIError, prepends a human-friendly explanation of the HTTP status code so users get actionable guidance instead of a bare status. The original error chain is preserved for errors.Is / errors.As.
func ExplainReadError ¶
ExplainReadError is the read-path counterpart: no schema for the type, or a stored document the bundled schema rejects. Both mean "update the CLI", so say so.
func ExplainWriteError ¶
ExplainWriteError wraps a write failure, adding guidance for a schema mismatch, any other schema validation failure, or an unsupported Resource type; slug may be "". Other errors go through ExplainAPIError. ErrSchemaMismatch is checked first because it also matches ErrSchemaValidation.
func FlushOutputs ¶
func FlushOutputs()
FlushOutputs releases what Out and Err held back mid-character. By assertion: both are typed io.Writer.
func FprintJSON ¶
FprintJSON marshals v with two-space indent and writes it to w followed by a newline. Control runes are escaped rather than replaced, so the document still parses into the original values.
func GetClientCertificate ¶
func GetClientCertificate() (tls.Certificate, error)
func GetContext ¶
func GetContext() (context.Context, context.CancelFunc)
func GetHTTPClient ¶
func InitCELProgram ¶
InitCELProgram - Initialize a CEL program with given CEL command and a set of environments
func IsInteractive ¶
func IsInteractive() bool
IsInteractive reports whether there is a user at the other end of stdin.
func NewClient ¶ added in v0.6.0
NewClient performs fresh authentication without consulting an agent provider.
func NewClientWithHTTP ¶ added in v0.6.0
NewClientWithHTTP allows the agent to own the transport for session cleanup.
func NewSanitizingWriter ¶
NewSanitizingWriter wraps dest to filter what is written to it. Out and Err are built with it, so nothing reaches stdout or stderr unfiltered.
func NoColumnsError ¶
NoColumnsError wraps ErrNoColumns with the set of valid column names so the user knows what to choose from. The result stays matchable with errors.Is(err, ErrNoColumns).
func PrintJSON ¶
PrintJSON marshals v with two-space indent and prints it to Out followed by a newline. Use for single-entity get output and for full (unfiltered) list output.
func PrintJSONColumnFiltered ¶
PrintJSONColumnFiltered marshals each item, re-decodes it into a map, keeps only the requested column keys, and prints the indented array to stdout. Use when the caller requested an explicit subset of columns; otherwise use PrintJSON(items).
func PrintPermissionTable ¶
func PrintPermissionTable(columns []string, permissions []api.Permission) error
PrintPermissionTable renders the permission table using the legacy lowercased-column switch shared by the resource and folder permission commands. An unknown column yields an "unknown Column: %v" error (capitalized, preserving the historical message).
func PrintTable ¶
func PrintTable[T any](columns []string, items []T, valueFn func(item T, column string) (string, bool)) error
PrintTable renders a header row of column names followed by one row per item. valueFn returns the rendered cell string for (item, column) and reports whether the column is known; an unknown column yields an "unknown column: %q" error. It is generic over the item type so it serves both the api.* entity types and the resource package's decryptedResource.
func ReadPassword ¶
ReadPassword reads a Password interactively or via Pipe
func RenderTable ¶
RenderTable is the one path a table takes to the terminal, so callers pass raw values. Every cell is sanitized, header included: the stream writer keeps \n and \t, and either would forge a row or a column.
func Sanitize ¶
Sanitize prepares a server value for a single line of output. On top of what the writer does, it replaces \n and \t, which could fake a line or break a table row.
func SaveSessionKeysAndLogout ¶
SaveSessionKeysAndLogout saves any pending session keys to the server and then logs out. This should be used instead of client.Logout() to ensure session keys are persisted.
func SessionKeyWarning ¶ added in v0.6.0
func SessionKeyWarning(err error)
SessionKeyWarning avoids echoing server-controlled response bodies while a machine credential command is running, including its deferred cleanup.
func WarnIfExposed ¶
func WarnIfExposed(path, holds string)
WarnIfExposed prints a warning to stderr if other users can read path or it is not yours. holds describes what the file contains. Each path is warned about once.
func WarnReplacements ¶
func WarnReplacements()
WarnReplacements says, once, that this is not the text as stored. Execute calls it after the command; from Write it would land between two table rows.
func WithClient ¶
WithClient runs fn with a logged-in client, handling context, login, session-key persistence + logout, and SilenceUsage. SilenceUsage is set after login, so flag and login errors still print usage while runtime errors do not.
func WithMachineClient ¶ added in v0.6.0
WithMachineClient reserves stdout for data, including during login and cleanup. Authentication never consumes the command's stdin stream.
func WriteViperConfig ¶
WriteViperConfig writes viper's settings to path with mode 0600.
Types ¶
type ColumnAlias ¶
ColumnAlias declares a canonical column name together with the legacy input forms that should resolve to it. Used by list commands to accept snake_case (canonical), PascalCase, and lowercased-concat forms uniformly in --column and --filter flags.
type ColumnAliasResolver ¶
type ColumnAliasResolver struct {
// contains filtered or unexported fields
}
ColumnAliasResolver normalizes user-supplied column names to their canonical form via case-insensitive lookup against name+aliases.
func NewColumnAliasResolver ¶
func NewColumnAliasResolver(specs []ColumnAlias) *ColumnAliasResolver
func (*ColumnAliasResolver) Canonical ¶
func (r *ColumnAliasResolver) Canonical() []string
Canonical returns the canonical column names in declaration order. Useful for building --column flag help text and default value slices.
func (*ColumnAliasResolver) Normalize ¶
func (r *ColumnAliasResolver) Normalize(input string) (string, error)
Normalize maps an input column name to its canonical form. Returns an error listing the valid canonical names if the input matches nothing.
func (*ColumnAliasResolver) NormalizeAll ¶
func (r *ColumnAliasResolver) NormalizeAll(inputs []string) ([]string, error)
NormalizeAll normalizes a slice of input column names, returning the canonical-name slice or the first error encountered.
type ColumnRegistry ¶
type ColumnRegistry[T any] struct { // contains filtered or unexported fields }
ColumnRegistry holds the column specs for one entity type and precomputes the lookups and CEL options derived from them. It owns the shared CEL filter loop, so each entity package only declares its columns once.
func NewColumnRegistry ¶
func NewColumnRegistry[T any](noun string, columns []ColumnSpec[T]) *ColumnRegistry[T]
NewColumnRegistry builds a registry from the given column specs. noun is the plural entity word used in the "no such <noun> found with filter" error returned by Filter when nothing matches. Each canonical name and every alias is registered as a CEL variable so legacy and canonical filter expressions both compile.
func (*ColumnRegistry[T]) CelEnvOptions ¶
func (r *ColumnRegistry[T]) CelEnvOptions() []cel.EnvOption
CelEnvOptions returns the CEL environment options registering every canonical name and alias as a variable. Pass to util.CELExpressionReferencesFields.
func (*ColumnRegistry[T]) DefaultTableColumns ¶
func (r *ColumnRegistry[T]) DefaultTableColumns() []string
DefaultTableColumns returns the canonical names of columns shown in the default table output, in declaration order.
func (*ColumnRegistry[T]) Filter ¶
func (r *ColumnRegistry[T]) Filter(ctx context.Context, items []T, celCmd string) ([]T, error)
Filter evaluates celCmd against each item and returns the matching subset. An empty celCmd returns items unchanged; a valid expression matching nothing returns an error naming the entity.
func (*ColumnRegistry[T]) RequiresSecrets ¶
func (r *ColumnRegistry[T]) RequiresSecrets(columns []string) bool
RequiresSecrets reports whether any of the (already-normalized, canonical) columns demands secret decryption.
func (*ColumnRegistry[T]) Resolver ¶
func (r *ColumnRegistry[T]) Resolver() *ColumnAliasResolver
Resolver returns the alias resolver for normalizing --column / --filter input to canonical names and for building flag help text.
func (*ColumnRegistry[T]) SecretCelNames ¶
func (r *ColumnRegistry[T]) SecretCelNames() []string
SecretCelNames returns all CEL variable names (canonical and alias) whose value comes from secret decryption — used to detect whether a --filter expression forces secret fetching.
func (*ColumnRegistry[T]) TableValue ¶
func (r *ColumnRegistry[T]) TableValue(item T, col string) (string, bool)
TableValue resolves a canonical column name to the item's rendered table cell. Suitable as the valueFn for PrintTable; returns false for unknown columns.
type ColumnSpec ¶
type ColumnSpec[T any] struct { Name string Aliases []string DefaultTable bool RequiresSecrets bool // value depends on the expensive secret-decryption path CelType *cel.Type CelValue func(item T) any TableValue func(item T) string }
ColumnSpec describes one --column / --filter attribute on an entity of type T. The canonical Name is snake_case (matching JSON tags and Passbolt API conventions); Aliases keep legacy PascalCase and lowercased-concat forms working for backwards compatibility, both as CEL variables and as eval-map keys.
type PermissionJSONOutput ¶
type PermissionJSONOutput struct {
ID *string `json:"id,omitempty"`
Aco *string `json:"aco,omitempty"`
AcoForeignKey *string `json:"aco_foreign_key,omitempty"`
Aro *string `json:"aro,omitempty"`
AroForeignKey *string `json:"aro_foreign_key,omitempty"`
Type *int `json:"type,omitempty"`
CreatedTimestamp *time.Time `json:"created_timestamp,omitempty"`
ModifiedTimestamp *time.Time `json:"modified_timestamp,omitempty"`
}
func PermissionsToJSONOutput ¶
func PermissionsToJSONOutput(permissions []api.Permission) []PermissionJSONOutput
PermissionsToJSONOutput maps API permissions to the wire output struct shared by the resource and folder permission commands.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package securefile creates and checks files that hold secrets: the CLI config, which holds the private key and passphrase in cleartext, and the KeePass export.
|
Package securefile creates and checks files that hold secrets: the CLI config, which holds the private key and passphrase in cleartext, and the KeePass export. |
|
posixmode
Package posixmode holds the permission-bit helpers behind securefile on Unix.
|
Package posixmode holds the permission-bit helpers behind securefile on Unix. |
|
winacl
Package winacl holds the Windows ACL helpers behind securefile: the caller's SIDs, the private descriptor that stands in for 0600, and the check that a DACL exposes nobody else, which reads the DACL through the SDDL parser in sddl.go.
|
Package winacl holds the Windows ACL helpers behind securefile: the caller's SIDs, the private descriptor that stands in for 0600, and the check that a DACL exposes nobody else, which reads the DACL through the SDDL parser in sddl.go. |