Skip to main content

Crate cfgd_core

Crate cfgd_core 

Source

Modules§

compliance
composition
config
daemon
errors
exit
Exit-code taxonomy for the cfgd CLI.
generate
http
Canonical ureq::Agent construction + named HTTP timeout constants.
modules
oci
output
Typed-component output system — the sole interface for terminal output across cfgd. See .claude/specs/2026-05-14-output-system-redesign-design.md for the design.
platform
providers
reconciler
retry
Shared retry-with-exponential-backoff policy.
server_client
sources
state
upgrade

Structs§

ApplyLockGuard
RAII guard that releases the apply lock when dropped.
EffectiveReconcile
Fully resolved reconcile settings for a single entity (no Options).
FileState
Captured state of a file for backup purposes.
PathPosix
Display adapter returned by PathDisplayExt::posix. On Windows, renders the path with \/ substitution; on Unix it’s indistinguishable from Path::display().
TestHomeGuard
RAII guard returned by with_test_home_guard — restores the prior override on drop. Used by test harnesses (like TestEnvBuilder) that want to install an override without wrapping the whole test in a closure.

Constants§

API_VERSION
The canonical API version string used in all cfgd YAML documents (local and CRD).
COMMAND_TIMEOUT
Default timeout for external commands (2 minutes).
COSIGN_BIN_ENV
Env-var seam name for the cosign binary path. See [tool_binary_name].
CSI_DRIVER_NAME
DURATION_BUCKETS_LONG
DURATION_BUCKETS_SHORT
Named exponential-histogram bucket presets for latency metrics. Kept in cfgd-core so the SLO-adjacent choice is auditable in one place rather than divergent inline calls in cfgd-operator and cfgd-csi. Consumers feed the triple into prometheus_client::metrics::histogram::exponential_buckets(start, factor, length).
GIT_NETWORK_TIMEOUT
Default timeout for git network operations (5 minutes).
KILL_GRACE_PERIOD
Grace period between SIGTERM and SIGKILL when a watchdog kills a child. A SIGTERM-trapping child gets a chance to clean up; if it’s still alive past this window the watchdog escalates to SIGKILL so the daemon can reclaim the slot regardless of what the child does.
LABEL_DEVICE_ID
Kubernetes label key identifying the fleet device an object belongs to.
LABEL_MACHINE_CONFIG
Kubernetes label key pointing at the MachineConfig resource an object was derived from (e.g. DriftAlert -> MachineConfig).
MODULES_ANNOTATION
OCI_ANNOTATION_PLATFORM
OCI manifest annotation key carrying the os/arch platform string that a pushed module artifact was built for (parsed by the CSI cache on pull).
PROFILE_SCRIPT_TIMEOUT
Default timeout for profile-level scripts (5 minutes).

Traits§

PathDisplayExt
Display-only extension for human-facing path output. On Windows, folds \/ so a status subject or error message shows POSIX-form paths consistently across runners. On Unix, passes through unchanged — a legitimate \ in a Unix filename survives byte-for-byte.

Functions§

acquire_apply_lock
Acquire an exclusive apply lock via flock().
atomic_write
Atomically write content to a file using temp-file-then-rename.
atomic_write_str
Atomically write string content to a file.
capture_file_resolved_state
Like capture_file_state, but follows symlinks to capture the resolved content. For symlinks, is_symlink and symlink_target are recorded AND the actual file content behind the symlink is read. This is used for post-apply snapshots where we need to know both the link target and the content that was accessible through the symlink at the time of capture.
capture_file_state
Capture a file’s content and metadata for backup.
command_available
Check if a command is available on the system via PATH lookup. On Windows, tries common executable extensions (.exe, .cmd, .bat, .ps1, .com) since executables require an extension to be found.
command_available_with_seam
Like command_available but also returns true when the env-var seam points at an existing file. Use in is_available() checks where the caller wants a bool, not a Result.
command_output_with_timeout
Run a [Command] with a timeout. On timeout the watchdog sends SIGTERM, waits KILL_GRACE_PERIOD for the child to exit cleanly, then escalates to SIGKILL (Unix) / TerminateProcess retry (Windows).
copy_dir_recursive
Recursively copy a directory from source to target. Skips symlinks to prevent symlink-following attacks and infinite loops.
cosign_cmd
Build a base cosign Command — the shared factory for signature / attestation operations across oci.rs, cli/module.rs, and upgrade.rs.
create_symlink
Create a symbolic link. On Unix, uses std::os::unix::fs::symlink. On Windows, uses symlink_file or symlink_dir based on the source type. If symlink creation fails on Windows due to insufficient privileges, returns an error with guidance to enable Developer Mode or run as admin.
deep_merge_yaml
Deep merge two YAML values. Mappings are merged recursively; all other types are replaced by the overlay value.
default_config_dir
Default config directory: ~/.config/cfgd on Unix (respects XDG_CONFIG_HOME), AppData\Roaming\cfgd on Windows.
default_runtime_dir
Per-user runtime directory for short-lived sockets and pid files.
detect_default_branch
Best-effort detection of a local git repo’s default branch.
escape_double_quoted
Escape a value for use inside bash/zsh double quotes (single pass). Escapes \, ", `, and ! — the four characters with special meaning inside double-quoted strings.
expand_tilde
Expand ~ and ~/... paths to the user’s home directory.
file_permissions_mode
Get Unix permission mode bits from file metadata. Returns None on Windows.
force_kill_process
Send an uncatchable kill signal to a process by PID after the graceful terminate window has elapsed. Unix: SIGKILL. Windows: a second TerminateProcess call (idempotent — Windows kills are already uncatchable).
from_user_input
User-input path tolerance: accept C:\foo, C:/foo, ~/foo, ./foo. Folds \/ and expands a leading ~ via expand_tilde. Use when loading config fields where a Linux author may write / and a Windows author may write \ for the same logical location.
git_cmd_local
Build a Command for git suitable for LOCAL operations (config get/set, tag verify, add, commit, log). Sets GIT_TERMINAL_PROMPT=0 to prevent any prompt-driven hang, but does NOT set GIT_SSH_COMMAND because no network is involved. Use git_cmd_safe for any operation that talks to a remote.
git_cmd_safe
Prepare a git CLI command with SSH hang protection.
git_ssh_credentials
Git credential callback for git2 — handles SSH and HTTPS authentication. Used by sources/, modules/, and daemon/ for all git operations.
hostname_string
Get the system hostname as a String. Returns “unknown” on failure.
is_executable
Check if a file is executable. Unix: checks the executable bit in mode. Windows: checks file extension against known executable types.
is_file_encrypted
Check if a file is encrypted with the given backend.
is_root
Check if the current process is running with elevated privileges. Unix: checks euid == 0. Windows: checks IsUserAnAdmin().
is_same_inode
Check if two paths refer to the same file (same inode on Unix, same file index on Windows).
iso8601_to_filename_safe
Strip filename-unsafe characters (:, -, T, Z) from an ISO 8601 timestamp so it can be used as a path segment. Helper extracted from three inline replace calls in oci/build, cli/module/keys, and gateway/api/drift.
merge_aliases
Merge shell aliases by name: later entries override earlier ones with the same name. Same semantics as merge_env.
merge_env
Merge env vars by name: later entries override earlier ones with the same name. Used by config layer merging, composition, and reconciler module merge.
normalize_for_snapshot
Composite normalizer for snapshot tests: CRLF→LF, fold \/, then substitute each (path, placeholder) pair. Substitutions are applied longest-first to handle nested temp paths correctly (e.g. when <BARE>/inner and <BARE_ROOT> both match, longest wins). Each path is posixified before substitution so the captured text and the substitution keys share the same separator convention.
normalize_line_endings
CRLF → LF, for paired use with posixify_text in snapshot normalization. Cow so unix captures stay borrowed.
parse_alias
Parse a name=command string into a ShellAlias.
parse_duration_str
Parse a duration string like “30s”, “5m”, “1h”, or a plain number (as seconds).
parse_env_var
Parse a KEY=VALUE string into an EnvVar.
parse_loose_version
Parse a potentially loose version string into a semver Version. Handles “1.28” → “1.28.0”, “1” → “1.0.0”, and a leading v/V prefix (v1.10.01.10.0) so callers can feed git/OCI tag names directly.
posixify_os_error_text
Collapse OS-specific std::io::Error text in captured snapshot output. Linux emits ... File exists (os error 17) for ErrorKind::AlreadyExists; Windows emits ... Cannot create a file when that file already exists. (os error 183) for the same kind. Both fold to a stable <os error> placeholder so a single golden file works on both.
posixify_text
Fold \/ in free-form text that may contain native-separator paths. Cow so the unix path stays borrowed; only Windows captures pay for the allocation.
require_cosign
Verify cosign is available, honoring the CFGD_COSIGN_BIN test seam. Delegates to [require_tool_with_seam] to share the env-var-override logic with every other shimmable tool in cfgd-core.
require_tool
Check that a CLI tool is available on PATH, returning a unified error string otherwise. Before this helper, six if !command_available("X") gates across oci.rs and cli/module.rs each produced a slightly different “not found” message; strings had diverged in production. Pass install_hint (a short imperative like “install it from https://…”) to make the hint specific; None falls back to a generic “install it or add it to PATH”.
require_tool_with_seam
Verify an external tool is available, honoring tool_binary_name’s env-var override.
resolve_effective_reconcile
Resolve effective reconcile settings for a module given the profile inheritance chain and any patches in the global reconcile config.
resolve_relative_path
Resolve a relative path against a base directory with traversal validation. Absolute paths are returned as-is. Relative paths are joined to base and validated with validate_no_traversal. Returns Err if the relative path contains .. components.
sanitize_k8s_name
Sanitize a string for use as a Kubernetes object name (RFC 1123 DNS label). Lowercases, replaces underscores with hyphens, filters non-alphanumeric chars, and trims leading/trailing hyphens.
set_file_permissions
Set Unix permission mode bits on a file. No-op on Windows (NTFS uses inherited ACLs).
sha256_digest
Compute an OCI-style sha256:<hex> digest string from data.
sha256_hex
Compute SHA256 hash of data and return as lowercase hex string.
shell_escape_value
Escape a value for use in shell export statements.
split_add_remove
Split a list of values into adds and removes.
stderr_lossy_trimmed
Extract stderr from a Command output as a trimmed, lossy UTF-8 string.
stdout_lossy_trimmed
Extract stdout from a Command output as a trimmed, lossy UTF-8 string.
strip_sha256_prefix
Strip the sha256: prefix from a digest string, returning the hex body. Returns the original string unchanged if no prefix is present.
terminate_process
Send a graceful termination signal to a process by PID. Unix: sends SIGTERM. Windows: calls TerminateProcess.
to_file_url
Build a file:// URL that round-trips through url::Url::parse on both unix (file:///home/foo) and Windows (file:///C:/Users/foo). Replaces every hand-rolled format!("file://{}", path.display()) callsite that silently emits backslashes and a missing third slash on Windows.
to_posix_string
Always-fold POSIX form of a path. Use anywhere a path crosses into JSON, YAML, SQLite, gateway API, OCI annotations, file:// URLs, or snapshot goldens. Backslash is treated as a separator; legitimate backslash-in- filename on POSIX is sacrificed for cross-OS state portability (see the path-handling consolidation spec for the fold-policy rationale).
tool_binary_name
Resolve an external tool’s binary path, honoring a per-tool env-var test seam. Production code reads no env var and gets default (which Command resolves via PATH); tests set env_var to an absolute path of a shim binary. This is the SOLE supported override pattern for external CLIs.
tool_cmd
Build a Command for an external tool, honoring tool_binary_name’s env-var override. Sets stderr to piped so callers can surface the tool’s stderr in error messages without spamming the user’s terminal.
tracing_env_filter
Build a tracing_subscriber::EnvFilter from RUST_LOG if set, falling back to default. Consolidates the four identical EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(..)) scaffolds in cfgd/main.rs, cfgd/cli/plugin.rs, cfgd-operator/main.rs, and cfgd-csi/main.rs.
try_git_cmd
Try a git CLI command via git_cmd_safe, returning true on success. On failure, logs the stderr via tracing::debug and returns false.
union_extend
Extend a Vec<String> with items from source, skipping duplicates.
unix_secs_now
Returns the current time as seconds since the Unix epoch.
unix_secs_to_iso8601
Converts a Unix timestamp (seconds since epoch) to an ISO 8601 UTC string.
utc_now_filename_safe
Convenience: current UTC time as a filename-safe string.
utc_now_iso8601
Returns the current UTC time as an ISO 8601 / RFC 3339 string.
validate_alias_name
Validate that a shell alias name is safe for shell interpolation. Accepts names matching [A-Za-z0-9_.-]+.
validate_env_var_name
Validate that an environment variable name is safe for shell interpolation. Accepts names matching [A-Za-z_][A-Za-z0-9_]*.
validate_env_var_user_name
Validate that an environment variable name is safe for shell interpolation and is not in the reserved CFGD_* namespace.
validate_no_traversal
Validate that a path contains no .. components (pre-canonicalization check).
validate_path_within
Validate that a resolved path does not escape a root directory.
version_satisfies
Check whether version_str satisfies requirement_str (semver range).
with_test_home
Scope a HOME override for the duration of f. The prior value (including None) is restored when f returns, whether normally or via panic.
with_test_home_guard
Install a HOME override for the current thread and return a guard that restores the prior value on drop. Use in test builders that need the override to outlive a single closure call.
xml_escape
Escape a string for safe inclusion in XML/plist content (single pass).