Skip to content
This repository has been archived by the owner on Feb 7, 2020. It is now read-only.

Commit

Permalink
Merge pull request #37 from ripienaar/36
Browse files Browse the repository at this point in the history
(#36) only write certs when they change when always overwrite is set
  • Loading branch information
ripienaar authored May 22, 2019
2 parents b259ec5 + fab33dd commit 4937268
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 4 deletions.
19 changes: 16 additions & 3 deletions filesec/file_security.go
Original file line number Diff line number Diff line change
Expand Up @@ -338,12 +338,25 @@ func (s *FileSecurity) CachePublicData(data []byte, identity string) error {
return err
}

if !s.conf.AlwaysOverwriteCache {
_, err = os.Stat(certfile)
if err == nil {
_, err = os.Stat(certfile)
if err == nil {
if !s.conf.AlwaysOverwriteCache {
s.log.Debugf("Already have a certificate in %s, refusing to overwrite with a new one", certfile)
return nil
}

// it exists, lets check if its required to update it, quicker to just update it but that
// risks failing when disks are full etc this attempts that risky step only when needed
rsum := sha256.Sum256([]byte(data))
fsum, err := fsha256(certfile)
if err != nil {
return fmt.Errorf("could not determine sha256 of current certificate in %s: %s", certfile, err)
}

if fmt.Sprintf("%x", fsum) == fmt.Sprintf("%x", rsum) {
s.log.Debugf("Received certificate is the same as cached certificate %s, not updating cache", certfile)
return nil
}
}

err = ioutil.WriteFile(certfile, []byte(data), os.FileMode(int(0644)))
Expand Down
2 changes: 1 addition & 1 deletion filesec/file_security_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -529,7 +529,7 @@ var _ = Describe("FileSSL", func() {
Expect(err).ToNot(HaveOccurred())
defer os.Remove(cpath)

// deliberatly change the file so that we can figure out if its being changed
// deliberately change the file so that we can figure out if its being changed
// I'd check time stamps but they are per second so not much use
err = ioutil.WriteFile(cpath, []byte("too many secrets"), os.FileMode(int(0644)))
Expect(err).ToNot(HaveOccurred())
Expand Down
18 changes: 18 additions & 0 deletions filesec/util.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package filesec

import (
"crypto/sha256"
"io"
"os"
"regexp"
"runtime"
Expand Down Expand Up @@ -38,3 +40,19 @@ func runtimeOs() string {

return runtime.GOOS
}

func fsha256(file string) ([]byte, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
}
defer f.Close()

h := sha256.New()
_, err = io.Copy(h, f)
if err != nil {
return nil, err
}

return h.Sum(nil), nil
}

0 comments on commit 4937268

Please sign in to comment.