iis,wincertstore,javakeystore: SHA-256 idempotency short-circuit

Closes Top-10 fix #3 of the 2026-05-02 deployment-target audit
re-run (see cowork/deployment-target-audit-2026-05-02-rerun/
RESULTS.md). Pre-fix, the three PowerShell-driven connectors
(IIS / WinCertStore / JavaKeystore) bypass internal/deploy.Apply
because they write to the Windows cert store / Java keystore via
PowerShell + keytool rather than the local filesystem. They don't
get deploy.Apply's SHA-256 idempotency short-circuit for free, so
every renewal triggers a full Remove+Import cycle even on byte-
identical material. Operators with 60-day rotation see unnecessary
cert-store / keystore churn, briefly bumping CPU and possibly
disrupting connections in flight.

This commit adds a per-connector idempotency probe modeled on
Bundle 9's Caddy api-mode SHA-256 short-circuit (commit 8cda860).
Each probe runs at the top of DeployCertificate, BEFORE the
destructive step, with a unique # CERTCTL_IDEM_PROBE PowerShell
comment tag so test mocks match deterministically.

IIS: Get-ChildItem Cert:\... + Get-WebBinding; matches when both
the cert is in the store AND the active binding's certificateHash
equals the new thumbprint.

WinCertStore: Get-ChildItem Cert:\...\<thumbprint>; matches when
the cert exists in the configured store AND its NotAfter is
still in the future.

JavaKeystore: keytool -list -alias -v; matches when the parsed
SHA-256 fingerprint equals sha256(certPEM_DER).

On match: return Success=true with Metadata["idempotent"]="true",
no destructive operation. On any error during the probe (network,
parse, etc.): fall through to today's full deploy path.
False negatives are safe; false positives are dangerous.

Tests added (one positive + one negative per connector):
- TestIIS_Idempotent_SkipsDeployWhenBindingMatches
- TestIIS_Idempotent_DifferentBinding_FallsThroughToDeploy
- TestWinCertStore_Idempotent_SkipsImportWhenCertInStore
- TestWinCertStore_Idempotent_NotInStore_FallsThroughToDeploy
- TestJKS_Idempotent_SkipsDeployWhenAliasMatches
- TestJKS_Idempotent_DifferentAlias_FallsThroughToDeploy

Verified locally:
- gofmt clean across all three connectors.
- Syntax-validated via gofmt.

Audit reference: cowork/deployment-target-audit-2026-05-02-rerun/
RESULTS.md Top-10 fix #3.
This commit is contained in:
shankar0123
2026-05-02 22:01:30 +00:00
parent 514bf9050c
commit 6d3d861acc
6 changed files with 786 additions and 118 deletions
+79 -11
View File
@@ -254,6 +254,42 @@ func (c *Connector) DeployCertificate(ctx context.Context, request target.Deploy
}, fmt.Errorf("%s", errMsg)
}
// Bundle 10 / Top-10 fix #3: SHA-1 (Windows cert-store convention)
// idempotency short-circuit. If the configured site's active binding's
// certificateHash already matches the new thumbprint AND the cert exists
// in the store, skip the destructive Remove+Import cycle entirely.
// Conservative: any error during the probe falls through to today's full
// deploy path. False negatives are safe; false positives are dangerous.
thumbprint, err := certutil.ComputeThumbprint(request.CertPEM)
if err != nil {
errMsg := fmt.Sprintf("failed to compute certificate thumbprint: %v", err)
c.logger.Error("deployment failed", "error", err)
return &target.DeploymentResult{
Success: false,
Message: errMsg,
DeployedAt: time.Now(),
}, fmt.Errorf("%s", errMsg)
}
already, idemErr := c.isCertAlreadyDeployed(ctx, thumbprint)
if idemErr == nil && already {
c.logger.Info("IIS already has this cert bound; skipping deploy",
"thumbprint", thumbprint, "site", c.config.SiteName)
return &target.DeploymentResult{
Success: true,
TargetAddress: fmt.Sprintf("%s (IIS: %s)", c.config.Hostname, c.config.SiteName),
DeploymentID: fmt.Sprintf("iis-idem-%d", time.Now().Unix()),
Message: "Cert already deployed and bound; idempotent skip",
DeployedAt: time.Now(),
Metadata: map[string]string{
"thumbprint": thumbprint,
"site_name": c.config.SiteName,
"cert_store": c.config.CertStore,
"idempotent": "true",
},
}, nil
}
// Bundle 5 (2026-05-02 deployment-target audit): pre-deploy snapshot
// of the existing binding's SSL thumbprint so a binding-update failure
// can roll back to the pre-deploy state. Empty oldThumbprint means
@@ -298,19 +334,10 @@ func (c *Connector) DeployCertificate(ctx context.Context, request target.Deploy
}, fmt.Errorf("%s", errMsg)
}
// Step 2+3: Compute thumbprint and import PFX
// Step 2+3: Import PFX
// In local mode: write PFX to temp file, import via file path
// In WinRM mode: base64-encode PFX, decode on remote side to temp file, import, clean up
thumbprint, err := certutil.ComputeThumbprint(request.CertPEM)
if err != nil {
errMsg := fmt.Sprintf("failed to compute certificate thumbprint: %v", err)
c.logger.Error("deployment failed", "error", err)
return &target.DeploymentResult{
Success: false,
Message: errMsg,
DeployedAt: time.Now(),
}, fmt.Errorf("%s", errMsg)
}
// (thumbprint already computed in the idempotency check above)
c.logger.Debug("certificate thumbprint computed", "thumbprint", thumbprint)
@@ -762,6 +789,47 @@ func (c *Connector) verifyRollback(ctx context.Context, oldThumbprint string) er
return fmt.Errorf("rollback verification disagreed: %s", out)
}
// isCertAlreadyDeployed checks if the given thumbprint is already deployed
// and bound to the configured site's active HTTPS binding.
// Returns (true, nil) iff the cert is in the store AND the binding's
// certificateHash matches the thumbprint. Returns (false, nil) on any
// mismatch or missing binding. Returns (false, error) only on executor errors
// — falls through to the full deploy path (conservative).
//
// Bundle 10 / Top-10 fix #3 of the 2026-05-02 deployment-target audit.
func (c *Connector) isCertAlreadyDeployed(ctx context.Context, thumbprint string) (bool, error) {
port := c.config.Port
if port == 0 {
port = 443
}
script := fmt.Sprintf(
"# CERTCTL_IDEM_PROBE\n"+
"$cert = Get-ChildItem 'Cert:\\LocalMachine\\%s\\%s' -ErrorAction SilentlyContinue; "+
"$binding = Get-WebBinding -Name '%s' -Protocol 'https' -Port %d -ErrorAction SilentlyContinue; "+
"if ($cert -and $binding -and $binding.certificateHash -eq '%s') { Write-Output 'IDEM_MATCH' } else { Write-Output 'IDEM_MISS' }",
c.config.CertStore, thumbprint,
c.config.SiteName, port,
thumbprint,
)
output, err := c.executor.Execute(ctx, script)
if err != nil {
// Executor error: return false (conservative — fall through to full deploy)
c.logger.Debug("idempotency probe executor error", "error", err, "output", strings.TrimSpace(output))
return false, nil
}
out := strings.TrimSpace(output)
if out == "IDEM_MATCH" {
c.logger.Debug("idempotency probe matched", "thumbprint", thumbprint)
return true, nil
}
// "IDEM_MISS" or any other output
c.logger.Debug("idempotency probe missed", "output", out)
return false, nil
}
// NOTE: PFX creation, key parsing, thumbprint computation, and password generation
// have been extracted to the shared certutil package (internal/connector/target/certutil)
// for reuse by WinCertStore and JavaKeystore connectors.