-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsecrets.go
86 lines (76 loc) · 2.32 KB
/
secrets.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
// @author: Brian Wojtczak
// @copyright: 2024 by Brian Wojtczak
// @license: BSD-style license found in the LICENSE file
package altcha
import (
"sync"
"time"
)
const defaultSecretsRotationInterval = 5 * time.Minute
var (
currentSecret string
previousSecret string
secretsRotationCallbacks []func()
secretsRotationTicker *time.Ticker
secretsMutex = &sync.RWMutex{}
)
// GetSecrets returns the current and previous secrets used for the hmac.
func GetSecrets() (current, previous string) {
secretsMutex.RLock()
if len(currentSecret) == 0 { // not initialised yet
secretsMutex.RUnlock()
SetSecretsRotationInterval(defaultSecretsRotationInterval)
secretsMutex.RLock()
}
defer secretsMutex.RUnlock()
return currentSecret, previousSecret
}
// RotateSecrets immediately generates a new secret and replaces the previous
// secret with the current secret. This is concurrency safe and will block
// until complete.
func RotateSecrets() {
secretsMutex.Lock()
defer secretsMutex.Unlock()
rotateSecrets()
}
// WARNING: Ensure the mutex is locked before calling this function.
func rotateSecrets() {
previousSecret = currentSecret
currentSecret = randomString(32)
callbacks := secretsRotationCallbacks // copy the slice
go func() {
for _, callback := range callbacks {
callback()
}
}()
}
// SetSecretsRotationInterval sets the interval at which secrets are automatically
// rotated. Setting the interval to 0 will disable automatic rotation.
func SetSecretsRotationInterval(interval time.Duration) {
secretsMutex.Lock()
defer secretsMutex.Unlock()
if secretsRotationTicker != nil {
secretsRotationTicker.Stop()
}
if interval > 0 {
if len(currentSecret) == 0 { // not initialised yet
currentSecret = randomString(32)
}
rotateSecrets()
secretsRotationTicker = time.NewTicker(interval)
go func() {
defer secretsRotationTicker.Stop()
for range secretsRotationTicker.C {
RotateSecrets()
}
}()
}
}
// AddSecretsRotationCallback adds a callback function which is called when the
// secrets are rotated. It is run in a separate goroutine, so that the mutex
// is not held or locked when the callback is run.
func AddSecretsRotationCallback(callback func()) {
secretsMutex.Lock()
defer secretsMutex.Unlock()
secretsRotationCallbacks = append(secretsRotationCallbacks, callback)
}