fix(gateway): delete temp cert file on persist failure

Wrap the WriteAllBytes/Move/HardenPermissions sequence in a try/catch so
that any failure best-effort deletes the hardened .tmp file (which may
already hold PFX/private-key bytes) before rethrowing.  Add a test that
induces a persist failure by pointing SelfSignedCertPath inside a
regular file and asserts no .tmp is left on disk.
This commit is contained in:
Joseph Doherty
2026-06-01 07:45:15 -04:00
parent 2eb81379e4
commit 4e520f9c0c
2 changed files with 44 additions and 3 deletions
@@ -146,9 +146,19 @@ public sealed class SelfSignedCertificateProvider
HardenPermissions(temp);
// Writing into an existing file truncates content but preserves its ACL/mode.
File.WriteAllBytes(temp, pfx);
File.Move(temp, path, overwrite: true);
HardenPermissions(path);
// If the write or move fails the hardened temp file (which may contain private-key
// material) must not be left on disk; delete it best-effort before rethrowing.
try
{
File.WriteAllBytes(temp, pfx);
File.Move(temp, path, overwrite: true);
HardenPermissions(path);
}
catch (Exception)
{
try { File.Delete(temp); } catch { /* best effort */ }
throw;
}
X509Certificate2 loaded = X509CertificateLoader.LoadPkcs12FromFile(path, password: null, KeyStorageFlags());
Log("Generated", loaded);