| 1 |
// Copyright 2012-2025 The NATS Authors |
| 2 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 |
// you may not use this file except in compliance with the License. |
| 4 |
// You may obtain a copy of the License at |
| 5 |
// |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
package server |
| 15 |
|
| 16 |
import ( |
| 17 |
"bytes" |
| 18 |
"container/heap" |
| 19 |
"container/list" |
| 20 |
"crypto/sha256" |
| 21 |
"errors" |
| 22 |
"fmt" |
| 23 |
"math" |
| 24 |
"os" |
| 25 |
"path/filepath" |
| 26 |
"strings" |
| 27 |
"sync" |
| 28 |
"time" |
| 29 |
|
| 30 |
"github.com/nats-io/nkeys" |
| 31 |
|
| 32 |
"github.com/nats-io/jwt/v2" // only used to decode, not for storage |
| 33 |
) |
| 34 |
|
| 35 |
const ( |
| 36 |
fileExtension = ".jwt" |
| 37 |
) |
| 38 |
|
| 39 |
// validatePathExists checks that the provided path exists and is a dir if requested |
| 40 |
func validatePathExists(path string, dir bool) (string, error) { |
| 41 |
if path == _EMPTY_ { |
| 42 |
return _EMPTY_, errors.New("path is not specified") |
| 43 |
} |
| 44 |
|
| 45 |
abs, err := filepath.Abs(path) |
| 46 |
if err != nil { |
| 47 |
return _EMPTY_, fmt.Errorf("error parsing path [%s]: %v", abs, err) |
| 48 |
} |
| 49 |
|
| 50 |
var finfo os.FileInfo |
| 51 |
if finfo, err = os.Stat(abs); err != nil { |
| 52 |
if os.IsNotExist(err) { |
| 53 |
return _EMPTY_, fmt.Errorf("the path [%s] doesn't exist", abs) |
| 54 |
} |
| 55 |
return _EMPTY_, fmt.Errorf("error accessing path [%s]: %v", abs, err) |
| 56 |
} |
| 57 |
|
| 58 |
mode := finfo.Mode() |
| 59 |
if dir && mode.IsRegular() { |
| 60 |
return _EMPTY_, fmt.Errorf("the path [%s] is not a directory", abs) |
| 61 |
} |
| 62 |
|
| 63 |
if !dir && mode.IsDir() { |
| 64 |
return _EMPTY_, fmt.Errorf("the path [%s] is not a file", abs) |
| 65 |
} |
| 66 |
|
| 67 |
return abs, nil |
| 68 |
} |
| 69 |
|
| 70 |
// ValidateDirPath checks that the provided path exists and is a dir |
| 71 |
func validateDirPath(path string) (string, error) { |
| 72 |
return validatePathExists(path, true) |
| 73 |
} |
| 74 |
|
| 75 |
// JWTChanged functions are called when the store file watcher notices a JWT changed |
| 76 |
type JWTChanged func(publicKey string) |
| 77 |
|
| 78 |
// DirJWTStore implements the JWT Store interface, keeping JWTs in an optionally sharded |
| 79 |
// directory structure |
| 80 |
type DirJWTStore struct { |
| 81 |
sync.Mutex |
| 82 |
directory string |
| 83 |
shard bool |
| 84 |
readonly bool |
| 85 |
deleteType deleteType |
| 86 |
operator map[string]struct{} |
| 87 |
expiration *expirationTracker |
| 88 |
changed JWTChanged |
| 89 |
deleted JWTChanged |
| 90 |
} |
| 91 |
|
| 92 |
func newDir(dirPath string, create bool) (string, error) { |
| 93 |
fullPath, err := validateDirPath(dirPath) |
| 94 |
if err != nil { |
| 95 |
if !create { |
| 96 |
return _EMPTY_, err |
| 97 |
} |
| 98 |
if err = os.MkdirAll(dirPath, defaultDirPerms); err != nil { |
| 99 |
return _EMPTY_, err |
| 100 |
} |
| 101 |
if fullPath, err = validateDirPath(dirPath); err != nil { |
| 102 |
return _EMPTY_, err |
| 103 |
} |
| 104 |
} |
| 105 |
return fullPath, nil |
| 106 |
} |
| 107 |
|
| 108 |
// future proofing in case new options will be added |
| 109 |
type dirJWTStoreOption any |
| 110 |
|
| 111 |
// Creates a directory based jwt store. |
| 112 |
// Reads files only, does NOT watch directories and files. |
| 113 |
func NewImmutableDirJWTStore(dirPath string, shard bool, _ ...dirJWTStoreOption) (*DirJWTStore, error) { |
| 114 |
theStore, err := NewDirJWTStore(dirPath, shard, false, nil) |
| 115 |
if err != nil { |
| 116 |
return nil, err |
| 117 |
} |
| 118 |
theStore.readonly = true |
| 119 |
return theStore, nil |
| 120 |
} |
| 121 |
|
| 122 |
// Creates a directory based jwt store. |
| 123 |
// Operates on files only, does NOT watch directories and files. |
| 124 |
func NewDirJWTStore(dirPath string, shard bool, create bool, _ ...dirJWTStoreOption) (*DirJWTStore, error) { |
| 125 |
fullPath, err := newDir(dirPath, create) |
| 126 |
if err != nil { |
| 127 |
return nil, err |
| 128 |
} |
| 129 |
theStore := &DirJWTStore{ |
| 130 |
directory: fullPath, |
| 131 |
shard: shard, |
| 132 |
} |
| 133 |
return theStore, nil |
| 134 |
} |
| 135 |
|
| 136 |
type deleteType int |
| 137 |
|
| 138 |
const ( |
| 139 |
NoDelete deleteType = iota |
| 140 |
RenameDeleted |
| 141 |
HardDelete |
| 142 |
) |
| 143 |
|
| 144 |
// Creates a directory based jwt store. |
| 145 |
// |
| 146 |
// When ttl is set deletion of file is based on it and not on the jwt expiration |
| 147 |
// To completely disable expiration (including expiration in jwt) set ttl to max duration time.Duration(math.MaxInt64) |
| 148 |
// |
| 149 |
// limit defines how many files are allowed at any given time. Set to math.MaxInt64 to disable. |
| 150 |
// evictOnLimit determines the behavior once limit is reached. |
| 151 |
// * true - Evict based on lru strategy |
| 152 |
// * false - return an error |
| 153 |
func NewExpiringDirJWTStore(dirPath string, shard bool, create bool, delete deleteType, expireCheck time.Duration, limit int64, |
| 154 |
evictOnLimit bool, ttl time.Duration, changeNotification JWTChanged, _ ...dirJWTStoreOption) (*DirJWTStore, error) { |
| 155 |
fullPath, err := newDir(dirPath, create) |
| 156 |
if err != nil { |
| 157 |
return nil, err |
| 158 |
} |
| 159 |
theStore := &DirJWTStore{ |
| 160 |
directory: fullPath, |
| 161 |
shard: shard, |
| 162 |
deleteType: delete, |
| 163 |
changed: changeNotification, |
| 164 |
} |
| 165 |
if expireCheck <= 0 { |
| 166 |
if ttl != 0 { |
| 167 |
expireCheck = ttl / 2 |
| 168 |
} |
| 169 |
if expireCheck == 0 || expireCheck > time.Minute { |
| 170 |
expireCheck = time.Minute |
| 171 |
} |
| 172 |
} |
| 173 |
if limit <= 0 { |
| 174 |
limit = math.MaxInt64 |
| 175 |
} |
| 176 |
theStore.startExpiring(expireCheck, limit, evictOnLimit, ttl) |
| 177 |
theStore.Lock() |
| 178 |
err = filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error { |
| 179 |
if strings.HasSuffix(path, fileExtension) { |
| 180 |
if theJwt, err := os.ReadFile(path); err == nil { |
| 181 |
hash := sha256.Sum256(theJwt) |
| 182 |
_, file := filepath.Split(path) |
| 183 |
theStore.expiration.track(strings.TrimSuffix(file, fileExtension), &hash, string(theJwt)) |
| 184 |
} |
| 185 |
} |
| 186 |
return nil |
| 187 |
}) |
| 188 |
theStore.Unlock() |
| 189 |
if err != nil { |
| 190 |
theStore.Close() |
| 191 |
return nil, err |
| 192 |
} |
| 193 |
return theStore, err |
| 194 |
} |
| 195 |
|
| 196 |
func (store *DirJWTStore) IsReadOnly() bool { |
| 197 |
return store.readonly |
| 198 |
} |
| 199 |
|
| 200 |
func (store *DirJWTStore) LoadAcc(publicKey string) (string, error) { |
| 201 |
return store.load(publicKey) |
| 202 |
} |
| 203 |
|
| 204 |
func (store *DirJWTStore) SaveAcc(publicKey string, theJWT string) error { |
| 205 |
return store.save(publicKey, theJWT) |
| 206 |
} |
| 207 |
|
| 208 |
func (store *DirJWTStore) LoadAct(hash string) (string, error) { |
| 209 |
return store.load(hash) |
| 210 |
} |
| 211 |
|
| 212 |
func (store *DirJWTStore) SaveAct(hash string, theJWT string) error { |
| 213 |
return store.save(hash, theJWT) |
| 214 |
} |
| 215 |
|
| 216 |
func (store *DirJWTStore) Close() { |
| 217 |
store.Lock() |
| 218 |
defer store.Unlock() |
| 219 |
if store.expiration != nil { |
| 220 |
store.expiration.close() |
| 221 |
store.expiration = nil |
| 222 |
} |
| 223 |
} |
| 224 |
|
| 225 |
// Pack up to maxJWTs into a package |
| 226 |
func (store *DirJWTStore) Pack(maxJWTs int) (string, error) { |
| 227 |
count := 0 |
| 228 |
var pack []string |
| 229 |
if maxJWTs > 0 { |
| 230 |
pack = make([]string, 0, maxJWTs) |
| 231 |
} else { |
| 232 |
pack = []string{} |
| 233 |
} |
| 234 |
store.Lock() |
| 235 |
err := filepath.Walk(store.directory, func(path string, info os.FileInfo, err error) error { |
| 236 |
if info != nil && !info.IsDir() && strings.HasSuffix(path, fileExtension) { // this is a JWT |
| 237 |
if count == maxJWTs { // won't match negative |
| 238 |
return nil |
| 239 |
} |
| 240 |
pubKey := strings.TrimSuffix(filepath.Base(path), fileExtension) |
| 241 |
if store.expiration != nil { |
| 242 |
if _, ok := store.expiration.idx[pubKey]; !ok { |
| 243 |
return nil // only include indexed files |
| 244 |
} |
| 245 |
} |
| 246 |
jwtBytes, err := os.ReadFile(path) |
| 247 |
if err != nil { |
| 248 |
return err |
| 249 |
} |
| 250 |
if store.expiration != nil { |
| 251 |
claim, err := jwt.DecodeGeneric(string(jwtBytes)) |
| 252 |
if err == nil && claim.Expires > 0 && claim.Expires < time.Now().Unix() { |
| 253 |
return nil |
| 254 |
} |
| 255 |
} |
| 256 |
pack = append(pack, fmt.Sprintf("%s|%s", pubKey, string(jwtBytes))) |
| 257 |
count++ |
| 258 |
} |
| 259 |
return nil |
| 260 |
}) |
| 261 |
store.Unlock() |
| 262 |
if err != nil { |
| 263 |
return _EMPTY_, err |
| 264 |
} else { |
| 265 |
return strings.Join(pack, "\n"), nil |
| 266 |
} |
| 267 |
} |
| 268 |
|
| 269 |
// Pack up to maxJWTs into a message and invoke callback with it |
| 270 |
func (store *DirJWTStore) PackWalk(maxJWTs int, cb func(partialPackMsg string)) error { |
| 271 |
if maxJWTs <= 0 || cb == nil { |
| 272 |
return errors.New("bad arguments to PackWalk") |
| 273 |
} |
| 274 |
var packMsg []string |
| 275 |
store.Lock() |
| 276 |
dir := store.directory |
| 277 |
exp := store.expiration |
| 278 |
store.Unlock() |
| 279 |
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { |
| 280 |
if info != nil && !info.IsDir() && strings.HasSuffix(path, fileExtension) { // this is a JWT |
| 281 |
pubKey := strings.TrimSuffix(filepath.Base(path), fileExtension) |
| 282 |
store.Lock() |
| 283 |
if exp != nil { |
| 284 |
if _, ok := exp.idx[pubKey]; !ok { |
| 285 |
store.Unlock() |
| 286 |
return nil // only include indexed files |
| 287 |
} |
| 288 |
} |
| 289 |
store.Unlock() |
| 290 |
jwtBytes, err := os.ReadFile(path) |
| 291 |
if err != nil { |
| 292 |
return err |
| 293 |
} |
| 294 |
if len(jwtBytes) == 0 { |
| 295 |
// Skip if no contents in the JWT. |
| 296 |
return nil |
| 297 |
} |
| 298 |
if exp != nil { |
| 299 |
claim, err := jwt.DecodeGeneric(string(jwtBytes)) |
| 300 |
if err == nil && claim.Expires > 0 && claim.Expires < time.Now().Unix() { |
| 301 |
return nil |
| 302 |
} |
| 303 |
} |
| 304 |
packMsg = append(packMsg, fmt.Sprintf("%s|%s", pubKey, string(jwtBytes))) |
| 305 |
if len(packMsg) == maxJWTs { // won't match negative |
| 306 |
cb(strings.Join(packMsg, "\n")) |
| 307 |
packMsg = nil |
| 308 |
} |
| 309 |
} |
| 310 |
return nil |
| 311 |
}) |
| 312 |
if packMsg != nil { |
| 313 |
cb(strings.Join(packMsg, "\n")) |
| 314 |
} |
| 315 |
return err |
| 316 |
} |
| 317 |
|
| 318 |
// Merge takes the JWTs from package and adds them to the store |
| 319 |
// Merge is destructive in the sense that it doesn't check if the JWT |
| 320 |
// is newer or anything like that. |
| 321 |
func (store *DirJWTStore) Merge(pack string) error { |
| 322 |
newJWTs := strings.Split(pack, "\n") |
| 323 |
for _, line := range newJWTs { |
| 324 |
if line == _EMPTY_ { // ignore blank lines |
| 325 |
continue |
| 326 |
} |
| 327 |
split := strings.Split(line, "|") |
| 328 |
if len(split) != 2 { |
| 329 |
return fmt.Errorf("line in package didn't contain 2 entries: %q", line) |
| 330 |
} |
| 331 |
pubKey := split[0] |
| 332 |
if !nkeys.IsValidPublicAccountKey(pubKey) { |
| 333 |
return fmt.Errorf("key to merge is not a valid public account key") |
| 334 |
} |
| 335 |
if err := store.saveIfNewer(pubKey, split[1]); err != nil { |
| 336 |
return err |
| 337 |
} |
| 338 |
} |
| 339 |
return nil |
| 340 |
} |
| 341 |
|
| 342 |
func (store *DirJWTStore) Reload() error { |
| 343 |
store.Lock() |
| 344 |
exp := store.expiration |
| 345 |
if exp == nil || store.readonly { |
| 346 |
store.Unlock() |
| 347 |
return nil |
| 348 |
} |
| 349 |
idx := exp.idx |
| 350 |
changed := store.changed |
| 351 |
isCache := store.expiration.evictOnLimit |
| 352 |
// clear out indexing data structures |
| 353 |
exp.heap = make([]*jwtItem, 0, len(exp.heap)) |
| 354 |
exp.idx = make(map[string]*list.Element) |
| 355 |
exp.lru = list.New() |
| 356 |
exp.hash = [sha256.Size]byte{} |
| 357 |
store.Unlock() |
| 358 |
return filepath.Walk(store.directory, func(path string, info os.FileInfo, err error) error { |
| 359 |
if strings.HasSuffix(path, fileExtension) { |
| 360 |
if theJwt, err := os.ReadFile(path); err == nil { |
| 361 |
hash := sha256.Sum256(theJwt) |
| 362 |
_, file := filepath.Split(path) |
| 363 |
pkey := strings.TrimSuffix(file, fileExtension) |
| 364 |
notify := isCache // for cache, issue cb even when file not present (may have been evicted) |
| 365 |
if i, ok := idx[pkey]; ok { |
| 366 |
notify = !bytes.Equal(i.Value.(*jwtItem).hash[:], hash[:]) |
| 367 |
} |
| 368 |
store.Lock() |
| 369 |
exp.track(pkey, &hash, string(theJwt)) |
| 370 |
store.Unlock() |
| 371 |
if notify && changed != nil { |
| 372 |
changed(pkey) |
| 373 |
} |
| 374 |
} |
| 375 |
} |
| 376 |
return nil |
| 377 |
}) |
| 378 |
} |
| 379 |
|
| 380 |
func (store *DirJWTStore) pathForKey(publicKey string) string { |
| 381 |
if len(publicKey) < 2 { |
| 382 |
return _EMPTY_ |
| 383 |
} |
| 384 |
if !nkeys.IsValidPublicKey(publicKey) { |
| 385 |
return _EMPTY_ |
| 386 |
} |
| 387 |
fileName := fmt.Sprintf("%s%s", publicKey, fileExtension) |
| 388 |
if store.shard { |
| 389 |
last := publicKey[len(publicKey)-2:] |
| 390 |
return filepath.Join(store.directory, last, fileName) |
| 391 |
} else { |
| 392 |
return filepath.Join(store.directory, fileName) |
| 393 |
} |
| 394 |
} |
| 395 |
|
| 396 |
// Load checks the memory store and returns the matching JWT or an error |
| 397 |
// Assumes lock is NOT held |
| 398 |
func (store *DirJWTStore) load(publicKey string) (string, error) { |
| 399 |
store.Lock() |
| 400 |
defer store.Unlock() |
| 401 |
if path := store.pathForKey(publicKey); path == _EMPTY_ { |
| 402 |
return _EMPTY_, fmt.Errorf("invalid public key") |
| 403 |
} else if data, err := os.ReadFile(path); err != nil { |
| 404 |
return _EMPTY_, err |
| 405 |
} else { |
| 406 |
if store.expiration != nil { |
| 407 |
store.expiration.updateTrack(publicKey) |
| 408 |
} |
| 409 |
return string(data), nil |
| 410 |
} |
| 411 |
} |
| 412 |
|
| 413 |
// write that keeps hash of all jwt in sync |
| 414 |
// Assumes the lock is held. Does return true or an error never both. |
| 415 |
func (store *DirJWTStore) write(path string, publicKey string, theJWT string) (bool, error) { |
| 416 |
if len(theJWT) == 0 { |
| 417 |
return false, fmt.Errorf("invalid JWT") |
| 418 |
} |
| 419 |
var newHash *[sha256.Size]byte |
| 420 |
if store.expiration != nil { |
| 421 |
h := sha256.Sum256([]byte(theJWT)) |
| 422 |
newHash = &h |
| 423 |
if v, ok := store.expiration.idx[publicKey]; ok { |
| 424 |
store.expiration.updateTrack(publicKey) |
| 425 |
// this write is an update, move to back |
| 426 |
it := v.Value.(*jwtItem) |
| 427 |
oldHash := it.hash[:] |
| 428 |
if bytes.Equal(oldHash, newHash[:]) { |
| 429 |
return false, nil |
| 430 |
} |
| 431 |
} else if int64(store.expiration.Len()) >= store.expiration.limit { |
| 432 |
if !store.expiration.evictOnLimit { |
| 433 |
return false, errors.New("jwt store is full") |
| 434 |
} |
| 435 |
// this write is an add, pick the least recently used value for removal |
| 436 |
i := store.expiration.lru.Front().Value.(*jwtItem) |
| 437 |
if err := os.Remove(store.pathForKey(i.publicKey)); err != nil { |
| 438 |
return false, err |
| 439 |
} else { |
| 440 |
store.expiration.unTrack(i.publicKey) |
| 441 |
} |
| 442 |
} |
| 443 |
} |
| 444 |
if err := os.WriteFile(path, []byte(theJWT), defaultFilePerms); err != nil { |
| 445 |
return false, err |
| 446 |
} else if store.expiration != nil { |
| 447 |
store.expiration.track(publicKey, newHash, theJWT) |
| 448 |
} |
| 449 |
return true, nil |
| 450 |
} |
| 451 |
|
| 452 |
func (store *DirJWTStore) delete(publicKey string) error { |
| 453 |
if store.readonly { |
| 454 |
return fmt.Errorf("store is read-only") |
| 455 |
} else if store.deleteType == NoDelete { |
| 456 |
return fmt.Errorf("store is not set up to for delete") |
| 457 |
} |
| 458 |
store.Lock() |
| 459 |
defer store.Unlock() |
| 460 |
name := store.pathForKey(publicKey) |
| 461 |
if store.deleteType == RenameDeleted { |
| 462 |
if err := os.Rename(name, name+".deleted"); err != nil { |
| 463 |
if os.IsNotExist(err) { |
| 464 |
return nil |
| 465 |
} |
| 466 |
return err |
| 467 |
} |
| 468 |
} else if err := os.Remove(name); err != nil { |
| 469 |
if os.IsNotExist(err) { |
| 470 |
return nil |
| 471 |
} |
| 472 |
return err |
| 473 |
} |
| 474 |
store.expiration.unTrack(publicKey) |
| 475 |
store.deleted(publicKey) |
| 476 |
return nil |
| 477 |
} |
| 478 |
|
| 479 |
// Save puts the JWT in a map by public key and performs update callbacks |
| 480 |
// Assumes lock is NOT held |
| 481 |
func (store *DirJWTStore) save(publicKey string, theJWT string) error { |
| 482 |
if store.readonly { |
| 483 |
return fmt.Errorf("store is read-only") |
| 484 |
} |
| 485 |
store.Lock() |
| 486 |
path := store.pathForKey(publicKey) |
| 487 |
if path == _EMPTY_ { |
| 488 |
store.Unlock() |
| 489 |
return fmt.Errorf("invalid public key") |
| 490 |
} |
| 491 |
dirPath := filepath.Dir(path) |
| 492 |
if _, err := validateDirPath(dirPath); err != nil { |
| 493 |
if err := os.MkdirAll(dirPath, defaultDirPerms); err != nil { |
| 494 |
store.Unlock() |
| 495 |
return err |
| 496 |
} |
| 497 |
} |
| 498 |
changed, err := store.write(path, publicKey, theJWT) |
| 499 |
cb := store.changed |
| 500 |
store.Unlock() |
| 501 |
if changed && cb != nil { |
| 502 |
cb(publicKey) |
| 503 |
} |
| 504 |
return err |
| 505 |
} |
| 506 |
|
| 507 |
// Assumes the lock is NOT held, and only updates if the jwt is new, or the one on disk is older |
| 508 |
// When changed, invokes jwt changed callback |
| 509 |
func (store *DirJWTStore) saveIfNewer(publicKey string, theJWT string) error { |
| 510 |
if store.readonly { |
| 511 |
return fmt.Errorf("store is read-only") |
| 512 |
} |
| 513 |
path := store.pathForKey(publicKey) |
| 514 |
if path == _EMPTY_ { |
| 515 |
return fmt.Errorf("invalid public key") |
| 516 |
} |
| 517 |
dirPath := filepath.Dir(path) |
| 518 |
if _, err := validateDirPath(dirPath); err != nil { |
| 519 |
if err := os.MkdirAll(dirPath, defaultDirPerms); err != nil { |
| 520 |
return err |
| 521 |
} |
| 522 |
} |
| 523 |
if _, err := os.Stat(path); err == nil { |
| 524 |
if newJWT, err := jwt.DecodeGeneric(theJWT); err != nil { |
| 525 |
return err |
| 526 |
} else if existing, err := os.ReadFile(path); err != nil { |
| 527 |
return err |
| 528 |
} else if existingJWT, err := jwt.DecodeGeneric(string(existing)); err != nil { |
| 529 |
// skip if it can't be decoded |
| 530 |
} else if existingJWT.ID == newJWT.ID { |
| 531 |
return nil |
| 532 |
} else if existingJWT.IssuedAt > newJWT.IssuedAt { |
| 533 |
return nil |
| 534 |
} else if newJWT.Subject != publicKey { |
| 535 |
return fmt.Errorf("jwt subject nkey and provided nkey do not match") |
| 536 |
} else if existingJWT.Subject != newJWT.Subject { |
| 537 |
return fmt.Errorf("subject of existing and new jwt do not match") |
| 538 |
} |
| 539 |
} |
| 540 |
store.Lock() |
| 541 |
cb := store.changed |
| 542 |
changed, err := store.write(path, publicKey, theJWT) |
| 543 |
store.Unlock() |
| 544 |
if err != nil { |
| 545 |
return err |
| 546 |
} else if changed && cb != nil { |
| 547 |
cb(publicKey) |
| 548 |
} |
| 549 |
return nil |
| 550 |
} |
| 551 |
|
| 552 |
func xorAssign(lVal *[sha256.Size]byte, rVal [sha256.Size]byte) { |
| 553 |
for i := range rVal { |
| 554 |
(*lVal)[i] ^= rVal[i] |
| 555 |
} |
| 556 |
} |
| 557 |
|
| 558 |
// returns a hash representing all indexed jwt |
| 559 |
func (store *DirJWTStore) Hash() [sha256.Size]byte { |
| 560 |
store.Lock() |
| 561 |
defer store.Unlock() |
| 562 |
if store.expiration == nil { |
| 563 |
return [sha256.Size]byte{} |
| 564 |
} else { |
| 565 |
return store.expiration.hash |
| 566 |
} |
| 567 |
} |
| 568 |
|
| 569 |
// An jwtItem is something managed by the priority queue |
| 570 |
type jwtItem struct { |
| 571 |
index int |
| 572 |
publicKey string |
| 573 |
expiration int64 // consists of unix time of expiration (ttl when set or jwt expiration) in seconds |
| 574 |
hash [sha256.Size]byte |
| 575 |
} |
| 576 |
|
| 577 |
// A expirationTracker implements heap.Interface and holds Items. |
| 578 |
type expirationTracker struct { |
| 579 |
heap []*jwtItem // sorted by jwtItem.expiration |
| 580 |
idx map[string]*list.Element |
| 581 |
lru *list.List // keep which jwt are least used |
| 582 |
limit int64 // limit how many jwt are being tracked |
| 583 |
evictOnLimit bool // when limit is hit, error or evict using lru |
| 584 |
ttl time.Duration |
| 585 |
hash [sha256.Size]byte // xor of all jwtItem.hash in idx |
| 586 |
quit chan struct{} |
| 587 |
wg sync.WaitGroup |
| 588 |
} |
| 589 |
|
| 590 |
func (q *expirationTracker) Len() int { return len(q.heap) } |
| 591 |
|
| 592 |
func (q *expirationTracker) Less(i, j int) bool { |
| 593 |
pq := q.heap |
| 594 |
return pq[i].expiration < pq[j].expiration |
| 595 |
} |
| 596 |
|
| 597 |
func (q *expirationTracker) Swap(i, j int) { |
| 598 |
pq := q.heap |
| 599 |
pq[i], pq[j] = pq[j], pq[i] |
| 600 |
pq[i].index = i |
| 601 |
pq[j].index = j |
| 602 |
} |
| 603 |
|
| 604 |
func (q *expirationTracker) Push(x any) { |
| 605 |
n := len(q.heap) |
| 606 |
item := x.(*jwtItem) |
| 607 |
item.index = n |
| 608 |
q.heap = append(q.heap, item) |
| 609 |
q.idx[item.publicKey] = q.lru.PushBack(item) |
| 610 |
} |
| 611 |
|
| 612 |
func (q *expirationTracker) Pop() any { |
| 613 |
old := q.heap |
| 614 |
n := len(old) |
| 615 |
item := old[n-1] |
| 616 |
old[n-1] = nil // avoid memory leak |
| 617 |
item.index = -1 |
| 618 |
q.heap = old[0 : n-1] |
| 619 |
q.lru.Remove(q.idx[item.publicKey]) |
| 620 |
delete(q.idx, item.publicKey) |
| 621 |
return item |
| 622 |
} |
| 623 |
|
| 624 |
func (pq *expirationTracker) updateTrack(publicKey string) { |
| 625 |
if e, ok := pq.idx[publicKey]; ok { |
| 626 |
i := e.Value.(*jwtItem) |
| 627 |
if pq.ttl != 0 { |
| 628 |
// only update expiration when set |
| 629 |
i.expiration = time.Now().Add(pq.ttl).UnixNano() |
| 630 |
heap.Fix(pq, i.index) |
| 631 |
} |
| 632 |
if pq.evictOnLimit { |
| 633 |
pq.lru.MoveToBack(e) |
| 634 |
} |
| 635 |
} |
| 636 |
} |
| 637 |
|
| 638 |
func (pq *expirationTracker) unTrack(publicKey string) { |
| 639 |
if it, ok := pq.idx[publicKey]; ok { |
| 640 |
xorAssign(&pq.hash, it.Value.(*jwtItem).hash) |
| 641 |
heap.Remove(pq, it.Value.(*jwtItem).index) |
| 642 |
delete(pq.idx, publicKey) |
| 643 |
} |
| 644 |
} |
| 645 |
|
| 646 |
func (pq *expirationTracker) track(publicKey string, hash *[sha256.Size]byte, theJWT string) { |
| 647 |
var exp int64 |
| 648 |
// prioritize ttl over expiration |
| 649 |
if pq.ttl != 0 { |
| 650 |
if pq.ttl == time.Duration(math.MaxInt64) { |
| 651 |
exp = math.MaxInt64 |
| 652 |
} else { |
| 653 |
exp = time.Now().Add(pq.ttl).UnixNano() |
| 654 |
} |
| 655 |
} else { |
| 656 |
if g, err := jwt.DecodeGeneric(theJWT); err == nil { |
| 657 |
exp = time.Unix(g.Expires, 0).UnixNano() |
| 658 |
} |
| 659 |
if exp == 0 { |
| 660 |
exp = math.MaxInt64 // default to indefinite |
| 661 |
} |
| 662 |
} |
| 663 |
if e, ok := pq.idx[publicKey]; ok { |
| 664 |
i := e.Value.(*jwtItem) |
| 665 |
xorAssign(&pq.hash, i.hash) // remove old hash |
| 666 |
i.expiration = exp |
| 667 |
i.hash = *hash |
| 668 |
heap.Fix(pq, i.index) |
| 669 |
} else { |
| 670 |
heap.Push(pq, &jwtItem{-1, publicKey, exp, *hash}) |
| 671 |
} |
| 672 |
xorAssign(&pq.hash, *hash) // add in new hash |
| 673 |
} |
| 674 |
|
| 675 |
func (pq *expirationTracker) close() { |
| 676 |
if pq == nil || pq.quit == nil { |
| 677 |
return |
| 678 |
} |
| 679 |
close(pq.quit) |
| 680 |
pq.quit = nil |
| 681 |
} |
| 682 |
|
| 683 |
func (store *DirJWTStore) startExpiring(reCheck time.Duration, limit int64, evictOnLimit bool, ttl time.Duration) { |
| 684 |
store.Lock() |
| 685 |
defer store.Unlock() |
| 686 |
quit := make(chan struct{}) |
| 687 |
pq := &expirationTracker{ |
| 688 |
make([]*jwtItem, 0, 10), |
| 689 |
make(map[string]*list.Element), |
| 690 |
list.New(), |
| 691 |
limit, |
| 692 |
evictOnLimit, |
| 693 |
ttl, |
| 694 |
[sha256.Size]byte{}, |
| 695 |
quit, |
| 696 |
sync.WaitGroup{}, |
| 697 |
} |
| 698 |
store.expiration = pq |
| 699 |
pq.wg.Add(1) |
| 700 |
go func() { |
| 701 |
t := time.NewTicker(reCheck) |
| 702 |
defer t.Stop() |
| 703 |
defer pq.wg.Done() |
| 704 |
for { |
| 705 |
now := time.Now().UnixNano() |
| 706 |
store.Lock() |
| 707 |
if pq.Len() > 0 { |
| 708 |
if it := pq.heap[0]; it.expiration <= now { |
| 709 |
path := store.pathForKey(it.publicKey) |
| 710 |
if err := os.Remove(path); err == nil { |
| 711 |
heap.Pop(pq) |
| 712 |
pq.unTrack(it.publicKey) |
| 713 |
xorAssign(&pq.hash, it.hash) |
| 714 |
store.Unlock() |
| 715 |
continue // we removed an entry, check next one right away |
| 716 |
} |
| 717 |
} |
| 718 |
} |
| 719 |
store.Unlock() |
| 720 |
select { |
| 721 |
case <-t.C: |
| 722 |
case <-quit: |
| 723 |
return |
| 724 |
} |
| 725 |
} |
| 726 |
}() |
| 727 |
} |