Skip to content

Commit

Permalink
Add init
Browse files Browse the repository at this point in the history
Adds an init function to read the encryption token from either from the
SOURCEGRAPH_CRYPT_KEY env var or SOURCEGRAPH_SECRET_FILE location. Panics
if no secret key is found.
  • Loading branch information
daxmc99 committed Jul 23, 2020
1 parent dfdee21 commit 79fdc6a
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
1 change: 0 additions & 1 deletion internal/secrets/crypt_test.go
Expand Up @@ -32,7 +32,6 @@ func TestDBEncryptingAndDecrypting(t *testing.T) {
if decrypted != toEncrypt {
t.Fatalf("failed to decrypt")
}

}

// Test the negative result - we should fail to decrypt with bad keys
Expand Down
51 changes: 51 additions & 0 deletions internal/secrets/init.go
@@ -0,0 +1,51 @@
package secrets

import (
"fmt"
"io/ioutil"
"os"
)

var CryptObject EncryptionStore

const (
sourcegraphCryptEnvvar = "SOURCEGRAPH_CRYPT_KEY"
// #nosec G101
sourcegraphSecretfileEnvvar = "SOURCEGRAPH_SECRET_FILE"
validKeyLength = 32
)

func init() {
cryptKey, cryptOK := os.LookupEnv(sourcegraphCryptEnvvar)

// set the default location if none exists
secretFile := os.Getenv(sourcegraphSecretfileEnvvar)
if secretFile == "" {
// #nosec G101
secretFile = "/var/lib/sourcegraph/token"
}

_, err := os.Stat(secretFile)

// a lack of encryption keys means we cannot run the application, hence panic.
if err != nil && !cryptOK {
panic(fmt.Sprintf("Either specify environment variable %s or provide the secrets file %s.",
sourcegraphCryptEnvvar,
sourcegraphSecretfileEnvvar))
}
if err == nil {
contents, readErr := ioutil.ReadFile(secretFile)
if readErr != nil {
panic(fmt.Sprintf("Couldn't read file %s", sourcegraphSecretfileEnvvar))
}
if len(contents) < validKeyLength {
panic(fmt.Sprintf("Key length of %d characters is required.", validKeyLength))
}
CryptObject.EncryptionKey = contents
} else {
if len(cryptKey) != validKeyLength {
panic(fmt.Sprintf("Key length of %d characters is required.", validKeyLength))
}
CryptObject.EncryptionKey = []byte(cryptKey)
}
}

0 comments on commit 79fdc6a

Please sign in to comment.