Skip to content

Commit

Permalink
Make sure replaced files have different modification times.
Browse files Browse the repository at this point in the history
Depending on filesystem time resolution, the modified certificates could
have the same timestamp in tests, causing the reload to fail.
  • Loading branch information
fancycode committed Jul 8, 2022
1 parent 75e5013 commit 8704bc3
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
30 changes: 30 additions & 0 deletions grpc_common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"io/fs"
"math/big"
"net"
"os"
Expand Down Expand Up @@ -86,3 +87,32 @@ func WritePublicKey(key *rsa.PublicKey, filename string) error {

return os.WriteFile(filename, data, 0755)
}

func replaceFile(t *testing.T, filename string, data []byte, perm fs.FileMode) {
t.Helper()
oldStat, err := os.Stat(filename)
if err != nil {
t.Fatalf("can't stat old file %s: %s", filename, err)
return
}

for {
if err := os.WriteFile(filename, data, perm); err != nil {
t.Fatalf("can't write file %s: %s", filename, err)
return
}

newStat, err := os.Stat(filename)
if err != nil {
t.Fatalf("can't stat new file %s: %s", filename, err)
return
}

// We need different modification times.
if !newStat.ModTime().Equal(oldStat.ModTime()) {
break
}

time.Sleep(time.Millisecond)
}
}
4 changes: 2 additions & 2 deletions grpc_server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ func Test_GrpcServer_ReloadCerts(t *testing.T) {

org2 := "Updated certificate"
cert2 := GenerateSelfSignedCertificateForTesting(t, 1024, org2, key)
os.WriteFile(certFile, cert2, 0755) // nolint
replaceFile(t, certFile, cert2, 0755)

cp2 := x509.NewCertPool()
if !cp2.AppendCertsFromPEM(cert2) {
Expand Down Expand Up @@ -215,7 +215,7 @@ func Test_GrpcServer_ReloadCA(t *testing.T) {

org2 := "Updated client"
clientCert2 := GenerateSelfSignedCertificateForTesting(t, 1024, org2, clientKey)
os.WriteFile(caFile, clientCert2, 0755) // nolint
replaceFile(t, caFile, clientCert2, 0755)

pair2, err := tls.X509KeyPair(clientCert2, pem.EncodeToMemory(&pem.Block{
Type: "RSA PRIVATE KEY",
Expand Down

0 comments on commit 8704bc3

Please sign in to comment.