nvflare.recipe.secrets module
Public helpers for keeping secrets out of recipe parameters.
Recipe parameters (train_args, task_args, eval_args, per_site_config,
add_client_config / add_server_config dicts, exec params, and other nested recipe
values) can be written in clear text into generated job configuration. They must never
contain actual secret values.
Instead, either read secrets from environment variables or mounted secret files inside your
training code, or put a secret_ref() or secret_file_ref() placeholder in a supported
runtime parameter:
from nvflare.recipe.secrets import secret_file_ref, secret_ref
recipe = FedAvgRecipe(
...,
train_args=f"--epochs 5 --api-key {secret_ref('MY_API_KEY')}",
)
recipe.add_client_config(
{"service_password": secret_file_ref("/var/run/secrets/service/password")}
)
Only the placeholders appear in the exported job. Secret references are supported at two explicit runtime boundaries:
command arguments consumed by NVFlare’s task script runner or subprocess launcher (including recipe
train_args,task_args, andeval_argsthat use those runners); these resolve after argument tokenization, immediately before the script or process starts. The subprocess launcher rejects references in command strings for directly invoked or leading-env-wrappedsh/bashand PowerShell. This is a targeted safeguard, not a general code-interpreter detector: never put a reference in any argument another program will parse as code, including another shell, a shell hidden behind a different wrapper, orpython -c. Read those secrets from the child environment or a mounted file instead;values explicitly read from a runtime job JSON file with
nvflare.utils.configs.get_job_config_value()or itsnvflare.utils.configs.get_client_config_value()andnvflare.utils.configs.get_server_config_value()wrappers. A typical recipe adds a top-level value withadd_client_configoradd_server_config; nested strings resolve when that value is read. Internal client-launcher timeout/count overrides are written into a subprocess runtime config and therefore reject references instead of resolving them.
Environment references are read from the executing process’s environment; file references are read from that site’s filesystem. Resolved values stay in runtime memory and are not written back to generated configuration. Dictionary keys are not resolved. Arbitrary component constructor arguments, metadata, custom files, and other job artifacts do not resolve references. Read secrets inside user code for those cases. Mounted-file reference paths cannot contain whitespace or braces.
Recipes automatically scan their parameters before export or run and emit
PotentialSecretWarning when a value looks like an actual secret. Detection is
best-effort and does not make a supplied value safe. A valid reference in an explicitly
unsupported parameter emits
UnsupportedSecretRefWarning. See
nvflare.fuel.utils.secret_utils.find_potential_secrets() for the heuristics.
- exception PotentialSecretWarning[source]
Bases:
UserWarningWarning category emitted when a job parameter looks like it contains an actual secret value.
- class SecretFinding(location: str, reason: str, preview: str)[source]
Bases:
NamedTupleOne potential secret found by
find_potential_secrets().- location
where the value was found, e.g.
"train_args (secret-named flag)".- Type:
str
- reason
why it was flagged, e.g.
"GitHub token".- Type:
str
- preview
masked preview of the value, safe to log and share.
- Type:
str
Create new instance of SecretFinding(location, reason, preview)
- location: str
Alias for field number 0
- preview: str
Alias for field number 2
- reason: str
Alias for field number 1
- exception UnsupportedSecretRefWarning[source]
Bases:
UserWarningWarning emitted when a secret reference appears outside a supported runtime boundary.
- find_potential_secrets(value: Any, location: str = 'value') List[SecretFinding][source]
Scan a parameter value for anything that looks like an actual secret.
Strings are checked for well-known credential formats, secret-named command-line flags with inline values, credentials embedded in URLs, and high-entropy tokens. Dicts and lists are scanned recursively; dict entries whose key names suggest a credential (password, token, api_key, …) are flagged when their value looks like actual secret material. Stand-alone, valid secret references (
${secret:NAME}), env-var/config placeholders, and file paths are not flagged – those are the recommended ways to hand secrets to a job.This is a heuristic intended to catch mistakes, not a guarantee: absence of findings does not prove a value is safe.
- Parameters:
value – the parameter value to scan (str, dict, list, or any nesting of them).
location – human-readable description of where the value came from; used in findings.
- Returns:
List of
SecretFinding, deduplicated by location and preview. Findings contain only masked previews and are safe to log.
- has_secret_refs(value: Any) bool[source]
Return whether a string contains an environment or mounted-file secret reference.
- resolve_secret_refs(value: Any, env: Mapping[str, str] | None = None) Any[source]
Resolve secret references recursively without changing mapping keys.
Intended to be called at runtime on the executing site, as late as possible and only on the in-memory value handed to user code. Environment references use
${secret:NAME}; mounted-file references use${secret:file:/path/to/key}. Resolved values must never be logged or written back into config files.- Parameters:
value – string or nested mapping/list/tuple whose string values should be resolved.
env – source of secret values; defaults to
os.environ.
- Returns:
A resolved value. Containers are copied; mapping keys are preserved unchanged.
- Raises:
ValueError – if reference syntax is invalid, a referenced environment variable is not set, or a referenced file cannot be read. Errors never include a resolved value, so they are safe to log.
- secret_file_ref(path: str) str[source]
Build a reference to a secret stored in a mounted text file on the executing site.
This is intended for secrets projected as files, including Kubernetes Secret volume keys. The path itself is stored in the generated job config; the file content is read only on the executing site at runtime. One trailing newline commonly added by secret-file tooling is removed before injection.
- Parameters:
path – runtime path of the mounted secret file. Absolute paths are strongly recommended; whitespace and brace characters are not supported.
- Returns:
The placeholder string
${secret:file:<path>}.
- secret_ref(env_var: str) str[source]
Build a secret reference placeholder for use in job parameters.
The returned string carries no secret value and is safe to store in job configs. A supported runtime consumer on the executing site replaces it with the value of the named environment variable. See
nvflare.recipe.secretsfor supported parameter locations.- Parameters:
env_var – name of the environment variable that holds the secret on the executing site.
- Returns:
The placeholder string
${secret:<env_var>}.
Example
train_args=f”–api-key {secret_ref(‘MY_API_KEY’)}”
- warn_on_potential_secrets(value: Any, context: str) List[SecretFinding][source]
Scan a parameter value and emit a
PotentialSecretWarningfor each finding.Warning messages contain only masked previews, never the flagged values, so they are safe to appear in logs that get shared.
- Parameters:
value – the parameter value to scan.
context – where the value came from, e.g.
"recipe parameter 'train_args'".
- Returns:
The list of findings (empty if nothing was flagged).
- warn_on_unsupported_secret_ref_keys(value: Any, context: str) bool[source]
Warn when nested mapping keys contain references, since keys are never resolved.
- warn_on_unsupported_secret_refs(value: Any, context: str) bool[source]
Warn when a value contains references that its runtime consumer will not resolve.
- warn_on_unsupported_secret_refs_outside_keys(value: Any, supported_value_keys: set[str], context: str, supported_value_depth: int = 1) bool[source]
Warn when references occur outside explicitly supported mapping values.
supported_value_depthcontrols the mapping depth at which supported keys are exempted. Per-site configuration uses depth 2 for its site key and immediate field values.