/
init.go
91 lines (76 loc) · 2.15 KB
/
init.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package secrets
import (
"fmt"
"io/ioutil"
"os"
"github.com/sourcegraph/sourcegraph/internal/conf"
)
var CryptObject Encrypter
var isEncrypted bool
const (
// #nosec G101
sourcegraphSecretfileEnvvar = "SOURCEGRAPH_SECRET_FILE"
sourcegraphCryptEnvvar = "SOURCEGRAPH_CRYPT_KEY"
)
func ConfiguredToEncrypt() bool {
return isEncrypted
}
func init() {
isEncrypted = false
envCryptKey, cryptOK := os.LookupEnv(sourcegraphCryptEnvvar)
var encryptionKey []byte
// set the default location if none exists
secretFile := os.Getenv(sourcegraphSecretfileEnvvar)
if secretFile == "" {
// #nosec G101
secretFile = "/var/lib/sourcegraph/token"
}
_, err := os.Stat(secretFile)
// reading from a file is first order
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))
}
encryptionKey = contents
err = os.Chmod(secretFile, 0400)
if err != nil {
panic("failed to make secrets file read only.")
}
CryptObject.EncryptionKey = encryptionKey
return
}
// environment is second order
if cryptOK {
CryptObject.EncryptionKey = []byte(envCryptKey)
return
}
// for the single docker case, we generate the secret
deployType := conf.DeployType()
if conf.IsDeployTypeSingleDockerContainer(deployType) {
b, err := GenerateRandomAESKey()
if err != nil {
panic(fmt.Sprintf("unable to read from random source: %v", err))
}
err = ioutil.WriteFile(secretFile, b, 0600)
if err != nil {
panic(err)
}
err = os.Chmod(secretFile, 0400)
if err != nil {
panic("failed to make secrets file read only.")
}
CryptObject.EncryptionKey = b
}
// wrapping in deploytype check so that we can still compile and test locally
if !(conf.IsDev(deployType) || os.Getenv("CI") == "") {
// for k8s & docker compose, expect a secret to be provided
panic(fmt.Sprintf("Either specify environment variable %s or provide the secrets file %s.",
sourcegraphCryptEnvvar,
sourcegraphSecretfileEnvvar))
}
isEncrypted = true
}