@@ -369,3 +369,82 @@ func newTestDirectory(t *testing.T) (string, string, string) {
369369
370370 return tempDir , certPath , keyPath
371371}
372+
373+ // TestGenerateCertPairWithPartialFiles tests that generateCertPair regenerates
374+ // a cert/key pair when only one file exists.
375+ func TestGenerateCertPairWithPartialFiles (t * testing.T ) {
376+ t .Parallel ()
377+
378+ keyRing := & mock.SecretKeyRing {
379+ RootKey : privKey ,
380+ }
381+
382+ tempDir := t .TempDir ()
383+ certPath := tempDir + "/tls.cert"
384+ keyPath := tempDir + "/tls.key"
385+
386+ // Create only a key file (simulating leftover from previous run).
387+ _ , keyBytes := genCertPair (t , false )
388+ keyBuf := & bytes.Buffer {}
389+ err := pem .Encode (
390+ keyBuf , & pem.Block {
391+ Type : "EC PRIVATE KEY" ,
392+ Bytes : keyBytes ,
393+ },
394+ )
395+ require .NoError (t , err )
396+
397+ err = os .WriteFile (keyPath , keyBuf .Bytes (), 0600 )
398+ require .NoError (t , err )
399+
400+ // Configure TLS manager - cert doesn't exist, but key does.
401+ cfg := & TLSManagerCfg {
402+ TLSCertPath : certPath ,
403+ TLSKeyPath : keyPath ,
404+ TLSCertDuration : testTLSCertDuration ,
405+ }
406+ tlsManager := NewTLSManager (cfg )
407+
408+ err = tlsManager .generateCertPair (keyRing )
409+ require .NoError (
410+ t , err , "should generate new cert pair when only key exists" ,
411+ )
412+
413+ // Verify both files now exist and form a valid pair.
414+ _ , _ , err = cert .GetCertBytesFromPath (certPath , keyPath )
415+ require .NoError (t , err , "should be able to load cert pair" )
416+
417+ // Test when only cert exists, key missing.
418+ tempDir2 := t .TempDir ()
419+ certPath2 := tempDir2 + "/tls.cert"
420+ keyPath2 := tempDir2 + "/tls.key"
421+
422+ // Create only a cert file.
423+ certBytes , _ := genCertPair (t , false )
424+ certBuf := & bytes.Buffer {}
425+ err = pem .Encode (
426+ certBuf , & pem.Block {
427+ Type : "CERTIFICATE" ,
428+ Bytes : certBytes ,
429+ },
430+ )
431+ require .NoError (t , err )
432+
433+ err = os .WriteFile (certPath2 , certBuf .Bytes (), 0644 )
434+ require .NoError (t , err )
435+
436+ cfg2 := & TLSManagerCfg {
437+ TLSCertPath : certPath2 ,
438+ TLSKeyPath : keyPath2 ,
439+ TLSCertDuration : testTLSCertDuration ,
440+ }
441+ tlsManager2 := NewTLSManager (cfg2 )
442+
443+ err = tlsManager2 .generateCertPair (keyRing )
444+ require .NoError (
445+ t , err , "should generate new cert pair when only cert exists" ,
446+ )
447+
448+ _ , _ , err = cert .GetCertBytesFromPath (certPath2 , keyPath2 )
449+ require .NoError (t , err , "should be able to load cert pair" )
450+ }
0 commit comments