Skip to content

feat: [#243] introduce SecretString-based secret types for sensitive data - #245

Merged
josecelano merged 5 commits into
mainfrom
243-introduce-secret-type-for-sensitive-data
Dec 18, 2025
Merged

josecelano merged 5 commits into
mainfrom
243-introduce-secret-type-for-sensitive-data

Conversation

@josecelano

@josecelano josecelano commented Dec 18, 2025 •

Copy link
Copy Markdown
Member

Summary

This PR implements issue #243, introducing type-safe wrappers for sensitive data (API tokens, passwords) using the secrecy crate. This prevents accidental exposure of secrets in logs, debug output, and error messages while maintaining code clarity with explicit expose_secret() calls.

Changes

Core Implementation

  • Added secrecy crate dependency (v0.10.3)
  • Created src/shared/secrets/ module with:
    • ApiToken - wrapper for API tokens
    • Password - wrapper for passwords
    • PlainApiToken and PlainPassword type aliases for DTO boundaries

Security Features

  • Memory Protection: Automatic memory zeroing when secrets are dropped
  • Debug Redaction: Secrets display as "[REDACTED SecretString]" in logs/debug
  • Development Tracing: Debug builds log secret access with caller location (TRACE level)
  • Zero Production Cost: Tracing completely removed in release builds via #[cfg(debug_assertions)]

Integration Points

  • Provider Config: Updated Hetzner provider to use ApiToken
  • Database Config: Updated MySQL config to use Password
  • JSON Schema: Verified schema generation works correctly (18 tests passing)

Documentation

  • Created comprehensive guide in docs/contributing/secret-handling.md
  • Updated AGENTS.md with Rule 18 for future development
  • Added ADR documenting the decision and rationale

Testing

  • All 1538 unit tests passing
  • Added 18+ new tests for secret type behavior
  • E2E tests verified (infrastructure lifecycle + deployment workflow)
  • JSON schema generation confirmed working

Breaking Changes

⚠️ API Changes:

  • HetznerConfig::api_token() now returns &ApiToken instead of &String
  • DatabaseConfig::password() now returns &Password instead of &String
  • Callers must use .expose_secret() to access the actual string values

Migration Guide

Replace direct string access with expose_secret():

// Before
let token = config.api_token();

// After
let token = config.api_token().expose_secret();

Related

Checklist

  • All tests pass
  • Documentation updated
  • Pre-commit checks pass
  • ADR created
  • Breaking changes documented

@josecelano josecelano self-assigned this Dec 18, 2025
@josecelano
josecelano requested a review from da2ce7 December 18, 2025 10:55
@josecelano
josecelano marked this pull request as draft December 18, 2025 11:01
@josecelano
josecelano marked this pull request as ready for review December 18, 2025 11:27
@josecelano

Copy link
Copy Markdown
Member Author

ACK fa24387

@josecelano
josecelano merged commit e114867 into main Dec 18, 2025

@da2ce7 da2ce7 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a post-merge review of the change from #245 as it stands at f782b40b5 on the default branch.

What still runs: the ApiToken and Password wrappers, moved to packages/deployer-types/src/secrets/ by 82b7409 and unchanged since apart from a doctest import path, and the use sites that keep HetznerConfig.api_token, HttpApiConfig.admin_token and the MySQL passwords wrapped in the domain, converting them from the plain PlainApiToken/PlainPassword fields of HetznerProviderSection, HttpApiSection and DatabaseSection. The tofu Hetzner variables context keeps the token wrapped until rendering; the Prometheus context and EnvironmentContext::admin_token() unwrap it. The predictable MySQL root password the change carried over (format!("{password}_root")) was replaced by a generated one in 81ed6d1, and the tracker template context no longer carries the MySQL password; both are history. Two statements in the description do not match the code: it lists HetznerConfig::api_token() and DatabaseConfig::password() accessors, which did not exist (the fields are public), and it gives the redacted form as [REDACTED SecretString], whereas secrecy 0.10 prints SecretBox<str>([REDACTED]).

[Minor] Secrets are written unescaped into quoted values of generated files, so a user-chosen secret containing the quote character breaks the file. templates/docker-compose/.env.tera:35 renders TORRUST_TRACKER_CONFIG_OVERRIDE_HTTP_API__ACCESS_TOKENS__ADMIN='{{ tracker.api_admin_token }}', and lines 51, 54 and 65 do the same for the MySQL root and user passwords and the Grafana admin password; the engine is Tera::default() (src/domain/template/engine.rs:68), which escapes nothing for these file names. An admin_token of it's-a-token or a MySQL password of pa'ss closes the single-quoted value early and leaves the rest of the line as a stray entry, so the .env either fails to parse or carries a truncated value, and a line break in the JSON string adds a line of its own. The MySQL DSN at line 42 breaks the same way, because USERINFO_ENCODE (src/infrastructure/templating/docker_compose/template/wrappers/env/context.rs:28) does not encode '. templates/prometheus/prometheus.yml.tera:29 has the double-quoted form of the problem for an admin_token containing " or \. The generated root password avoids ' (src/shared/secrets/random.rs:15), so only user-supplied values are affected. Smallest fix: when the DTOs convert to domain types (src/application/command_handlers/create/config/tracker/http_api_section.rs:171, src/application/command_handlers/create/config/tracker/tracker_core_section.rs:97 and :103, and the Grafana section), reject the characters the targets cannot carry, that is ' and line breaks for every value written to .env, and additionally " and \ for admin_token, with an error naming the field.

[Minor] Empty secrets are accepted. HttpApiConfig::new (src/domain/tracker/config/http_api.rs:243) checks the port and TLS invariants but not the token, and the Hetzner conversion (src/application/command_handlers/create/config/provider/mod.rs:134-136) passes api_token through with a note that validation is future work. With "admin_token": "" the deployer renders ACCESS_TOKENS__ADMIN='' into .env and token: [""] into prometheus.yml and deploys a tracker whose admin API is guarded by an empty token; whether the tracker then refuses every request or accepts ?token= depends on the tracker, and neither is what the operator meant. With an empty Hetzner api_token, create succeeds and the failure appears only at provisioning. Smallest fix: reject empty and whitespace-only values in HttpApiConfig::new and in the Hetzner conversion, returning a CreateConfigError that names the field.

[Minor] The DTOs that hold secrets in plain text derive Debug, so the redaction this change introduced stops at the domain boundary. HetznerProviderSection (src/application/command_handlers/create/config/provider/hetzner.rs:29, field at line 35), HttpApiSection (src/application/command_handlers/create/config/tracker/http_api_section.rs:77, field at line 87), DatabaseSection (src/application/command_handlers/create/config/tracker/tracker_core_section.rs:45, fields at lines 69 and 75) and GrafanaSection (src/application/command_handlers/create/config/grafana.rs:52) all derive it, and so does EnvironmentCreationConfig (src/application/command_handlers/create/config/environment_config.rs:90), which the SDK accepts at src/presentation/sdk/deployer.rs:137. format!("{config:?}") on a loaded creation config prints the Hetzner token, the admin token and the MySQL and Grafana passwords; the test at src/application/command_handlers/create/config/provider/hetzner.rs:88-96 checks that api_token appears in the debug output but not that its value is hidden. No CLI path formats these values today, so the exposure waits for the first debug!(?config) or #[instrument] without skip, or for an SDK caller that logs its input. Smallest fix: hand-written Debug impls for these sections that print [REDACTED] for the secret fields, with a test asserting the value is absent.

[Minor] EnvironmentContext::admin_token() (src/domain/environment/context.rs:369), delegated by Environment::admin_token() (src/domain/environment/mod.rs:466), returns the admin token as &str. Its two consumers, src/application/steps/rendering/docker_compose_templates.rs:111 and src/application/command_handlers/render/handler.rs:347, receive the plain value with no expose_secret() at their call site, so a search for expose_secret does not find them; and because the accessor is not #[track_caller], the debug-build trace that the description presents as an audit of secret access records a location inside context.rs for every such access instead of the consumer. Smallest fix: return &ApiToken from both accessors and call expose_secret() where the token is placed into the .env context.

[Nit] The template contexts turn the secrets back into String inside types that derive Debug: PrometheusContext.api_token (src/infrastructure/templating/prometheus/template/wrapper/prometheus_config/context.rs:57, filled at src/infrastructure/templating/prometheus/template/renderer/project_generator.rs:168-172) and the docker-compose context fields api_admin_token, root_password, password and admin_password (src/infrastructure/templating/docker_compose/template/wrappers/env/context.rs:44, :64, :70, :82). The skip lists of the renderers' #[instrument] attributes are what keeps these values out of traces now. The tofu Hetzner context already holds an ApiToken (src/infrastructure/templating/tofu/template/providers/hetzner/wrappers/variables/context.rs:90) and renders it through the wrapper's Serialize; the same field types work for these contexts.

[Nit] Zeroing on drop covers only the wrapper's own buffer, and two conversions copy where they could move: section.admin_token.clone().into() (src/application/command_handlers/create/config/tracker/http_api_section.rs:171) and Password::from(password.as_str()) / Password::from(p.as_str()) (src/application/command_handlers/create/config/tracker/tracker_core_section.rs:103 and :97) each leave a second copy that is freed without zeroing. The section and the destructured strings are owned at those points, so section.admin_token.into(), Password::from(password) and Password::from(p) move the buffer into the wrapper instead. The comment at packages/deployer-types/src/secrets/api_token.rs:67 (and password.rs:67) gives the redacted form as Secret([REDACTED]); the crate prints SecretBox<str>([REDACTED]).

Checked and found sound: the wrapper types themselves (redacting Debug, Serialize and Deserialize through the plain value as the persisted state requires, value equality used only to compare configurations and never to authenticate input, and the debug-only trace that logs the call site and not the value); the conversions of the Hetzner token, the admin token and the MySQL passwords into their wrappers; the tofu Hetzner context, which keeps the token wrapped until rendering; plain-text persistence in data/ and build/, which docs/decisions/configuration-directories-as-secrets.md accepts; and src/testing/integration/ssh_server/config.rs, where PlainPassword only labels a test password.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Introduce Secret Type for Sensitive Data

2 participants