Debian Codegraph @

internal/tokenstorage/inmemory.go

raw
1 package tokenstorage
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "sync"
8 "time"
9
10 "github.com/jkroepke/openvpn-auth-oauth2/v2/internal/crypto"
11 )
12
13 var ErrNilData = errors.New("data map cannot be nil")
14
15 const (
16 // DefaultGCInterval is the default interval for garbage collection.
17 DefaultGCInterval = time.Minute
18 )
19
20 // InMemory provides an in-memory implementation of a token storage system.
21 // It stores encrypted tokens associated with clients, supports expiration,
22 // automatic garbage collection, and is safe for concurrent use.
23 type InMemory struct {
24 data DataMap
25 cipher *crypto.Cipher
26 gcStop chan struct{}
27 gcWg sync.WaitGroup
28 expires time.Duration
29 gcInterval time.Duration
30 mu sync.RWMutex
31 }
32
33 // NewInMemory creates a new in-memory token storage with the given encryption key and expiration duration.
34 // It starts a background goroutine for garbage collection of expired tokens.
35 func NewInMemory(encryptionKey string, expires time.Duration) (*InMemory, error) {
36 return NewInMemoryWithGC(encryptionKey, expires, DefaultGCInterval)
37 }
38
39 // NewInMemoryWithGC creates a new in-memory token storage with custom GC interval.
40 // If gcInterval is 0 or negative, garbage collection is disabled.
41 func NewInMemoryWithGC(encryptionKey string, expires, gcInterval time.Duration) (*InMemory, error) {
42 encryptionCipher, err := crypto.New(encryptionKey)
43 if err != nil {
44 return nil, fmt.Errorf("create token cipher: %w", err)
45 }
46
47 storage := &InMemory{
48 data: DataMap{},
49 cipher: encryptionCipher,
50 expires: expires,
51 gcInterval: gcInterval,
52 gcStop: make(chan struct{}),
53 }
54
55 if gcInterval > 0 {
56 storage.startGC()
57 }
58
59 return storage, nil
60 }
61
62 // SetStorage replaces the current storage data with the provided DataMap.
63 // This is mainly used for testing or restoring state.
64 func (s *InMemory) SetStorage(data DataMap) error {
65 s.mu.Lock()
66 defer s.mu.Unlock()
67
68 if data == nil {
69 return ErrNilData
70 }
71
72 s.data = data
73
74 return nil
75 }
76
77 // Set stores an encrypted token for a given client, with an expiration time.
78 // The token is encrypted using AES-256-GCM before storage.
79 func (s *InMemory) Set(_ context.Context, client, token string) error {
80 encryptedBytes, err := s.cipher.EncryptBytes([]byte(token))
81 if err != nil {
82 return fmt.Errorf("encrypt error: %w", err)
83 }
84
85 s.mu.Lock()
86 defer s.mu.Unlock()
87
88 s.data[client] = item{
89 Data: encryptedBytes,
90 Expires: time.Now().Add(s.expires),
91 }
92
93 return nil
94 }
95
96 // Get retrieves and decrypts the token for a given client.
97 // If the token is expired or does not exist, ErrNotExists is returned.
98 func (s *InMemory) Get(_ context.Context, client string) (string, error) {
99 now := time.Now()
100
101 s.mu.RLock()
102 data, ok := s.data[client]
103 s.mu.RUnlock()
104
105 if !ok {
106 return "", ErrNotExists
107 }
108
109 if data.Expires.Before(now) {
110 s.deleteExpired(client, now)
111
112 return "", ErrNotExists
113 }
114
115 token, err := s.cipher.DecryptBytes(data.Data)
116 if err != nil {
117 return "", fmt.Errorf("decrypt error: %w", err)
118 }
119
120 return string(token), nil
121 }
122
123 // Consume atomically retrieves and removes the token for a given client.
124 // If the token is expired or does not exist, ErrNotExists is returned.
125 func (s *InMemory) Consume(_ context.Context, client string) (string, error) {
126 s.mu.Lock()
127 data, ok := s.data[client]
128 expired := ok && data.Expires.Before(time.Now())
129 delete(s.data, client)
130 s.mu.Unlock()
131
132 if !ok || expired {
133 return "", ErrNotExists
134 }
135
136 token, err := s.cipher.DecryptBytes(data.Data)
137 if err != nil {
138 return "", fmt.Errorf("decrypt error: %w", err)
139 }
140
141 return string(token), nil
142 }
143
144 // Delete removes the token data for a given client from storage.
145 func (s *InMemory) Delete(_ context.Context, client string) error {
146 s.mu.Lock()
147 defer s.mu.Unlock()
148
149 delete(s.data, client)
150
151 return nil
152 }
153
154 // Close stops the garbage collection goroutine and releases resources.
155 func (s *InMemory) Close() error {
156 // Make Close idempotent by only closing gcStop if it is not already closed.
157 select {
158 case <-s.gcStop:
159 // channel already closed, nothing to do
160 default:
161 close(s.gcStop)
162 }
163
164 s.gcWg.Wait()
165
166 return nil
167 }
168
169 // deleteExpired removes the current entry only if it was already expired when
170 // the caller observed an expired token. A concurrent refresh has a later
171 // expiration and must not be removed based on the caller's stale observation.
172 func (s *InMemory) deleteExpired(client string, observedAt time.Time) {
173 s.mu.Lock()
174 defer s.mu.Unlock()
175
176 data, ok := s.data[client]
177 if ok && data.Expires.Before(observedAt) {
178 delete(s.data, client)
179 }
180 }
181
182 // startGC starts the background garbage collection goroutine.
183 func (s *InMemory) startGC() {
184 s.gcWg.Go(func() {
185 ticker := time.NewTicker(s.gcInterval)
186 defer ticker.Stop()
187
188 for {
189 select {
190 case <-ticker.C:
191 s.collectExpired()
192 case <-s.gcStop:
193 return
194 }
195 }
196 })
197 }
198
199 // collectExpired removes all expired tokens from storage.
200 func (s *InMemory) collectExpired() {
201 s.mu.Lock()
202 defer s.mu.Unlock()
203
204 now := time.Now()
205 for client, item := range s.data {
206 if item.Expires.Before(now) {
207 delete(s.data, client)
208 }
209 }
210 }