fix(secrets): malformed ${secret:} references fail closed; README sample validates (scadaproj#45)

Secrets-009: SecretReferenceExpander.ExpandAsync throws FormatException when a value holds a
${secret: marker that is not a complete reference with a non-blank name (${secret:}, an
unterminated ${secret:name, a nested marker), instead of passing the literal text through as the
credential. ExpandConfigurationAsync names the offending key (never the value) and writes nothing.
The README wiring sample drops the relative "SqlitePath": "secrets.db" (which failed validation)
for the per-user default and shows an absolute example; a test validates the sample.

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
This commit is contained in:
Joseph Doherty
2026-11-09 15:13:49 -05:00
parent 262e11feaf
commit 5e2d3dd1bc
4 changed files with 110 additions and 3 deletions
@@ -129,4 +129,47 @@ public sealed class SecretReferenceExpanderTests
// Real key still expanded.
Assert.Equal("Server=.;Password=hunter2", config["ConnectionStrings:Db"]);
}
// ---------- Secrets-009: malformed references are fail-closed ----------
[Theory]
[InlineData("pw=${secret:}")]
[InlineData("pw=${secret: }")]
[InlineData("pw=${secret:sql/foo")]
[InlineData("pw=${secret:sql/foo};x=${secret:")]
[InlineData("pw=${secret:a${secret:sql/foo}")]
public async Task ExpandAsync_rejects_a_malformed_reference_instead_of_passing_it_through(string raw)
{
SecretReferenceExpander expander = Expander(("sql/foo", "hunter2"));
var ex = await Assert.ThrowsAsync<FormatException>(() => expander.ExpandAsync(raw, CancellationToken.None));
Assert.DoesNotContain("hunter2", ex.Message);
}
[Fact]
public async Task ExpandConfigurationAsync_names_the_key_holding_a_malformed_reference_and_writes_nothing()
{
IConfigurationRoot config = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?>
{
["Db:Good"] = "pw=${secret:sql/foo}",
["Db:Typo"] = "Password=${secret:}",
})
.Build();
var ex = await Assert.ThrowsAsync<FormatException>(
() => Expander(("sql/foo", "hunter2")).ExpandConfigurationAsync(config, CancellationToken.None));
Assert.Contains("Db:Typo", ex.Message);
Assert.DoesNotContain("Password", ex.Message);
Assert.Equal("pw=${secret:sql/foo}", config["Db:Good"]); // nothing half-expanded
}
[Fact]
public async Task ExpandAsync_text_without_a_marker_is_still_returned_unchanged()
{
// Positive control: the guard is about the marker, not about braces or dollar signs.
string raw = "a=${env:X};b={secret};c=$secret:";
Assert.Equal(raw, await Expander().ExpandAsync(raw, CancellationToken.None));
}
}