Skip to content
File

Blob: tun/server/waf_cache.go

go86 lines
1package server
2 
3import (
4 "context"
5 "time"
6 
7 "go.miragespace.co/specter/spec/protocol"
8 
9 "github.com/Yiling-J/theine-go"
10)
11 
12const (
13 hostWAFCacheBytes = 1 << 20 // 1MiB
14 hostWAFCacheTTL = 30 * time.Second
15)
16 
17type hostWAFCacheEntry struct {
18 record *protocol.HostWAFRecord
19 expiresAt time.Time
20}
21 
22func (s *Server) initHostWAFCache() {
23 cache, err := theine.NewBuilder[string, *hostWAFCacheEntry](hostWAFCacheBytes).Build()
24 if err != nil {
25 panic("BUG: " + err.Error())
26 }
27 s.hostWAFCache = cache
28}
29 
30func (s *Server) readCachedHostWAF(ctx context.Context, hostname string) (*protocol.HostWAFRecord, error) {
31 if err := ctx.Err(); err != nil {
32 return nil, err
33 }
34 cached := func() (*hostWAFCacheEntry, bool) {
35 entry, ok := s.hostWAFCache.Get(hostname)
36 return entry, ok && time.Now().Before(entry.expiresAt)
37 }
38 if entry, ok := cached(); ok {
39 return entry.record, nil
40 }
41 
42 result := s.hostWAFLoads.DoChan(hostname, func() (any, error) {
43 if entry, ok := cached(); ok {
44 return entry, nil
45 }
46 // Invalidating a cache entry can race this read. Preserve its original
47 // deadline so an older in-flight read cannot earn another full lifetime.
48 expiresAt := time.Now().Add(hostWAFCacheTTL)
49 lookupCtx, cancel := context.WithTimeout(s.ParentContext, lookupTimeout)
50 defer cancel()
51 record, _, err := s.readHostWAF(lookupCtx, hostname)
52 if err != nil {
53 return nil, err
54 }
55 if err := lookupCtx.Err(); err != nil {
56 return nil, err
57 }
58 entry := &hostWAFCacheEntry{record: record, expiresAt: expiresAt}
59 // Include keys and entry/message overhead, including successful absence.
60 cost := int64(256 + len(hostname))
61 if record != nil {
62 cost += int64(record.SizeVT() + 256 + 64*len(record.Policy.Exclusions))
63 }
64 if ttl := time.Until(expiresAt); ttl > 0 {
65 s.hostWAFCache.SetWithTTL(hostname, entry, cost, ttl)
66 }
67 return entry, nil
68 })
69 // A cancelled waiter must not cancel the shared read or cache an error.
70 select {
71 case <-ctx.Done():
72 return nil, ctx.Err()
73 case <-s.ParentContext.Done():
74 return nil, s.ParentContext.Err()
75 case result := <-result:
76 if result.Err != nil {
77 return nil, result.Err
78 }
79 entry := result.Val.(*hostWAFCacheEntry)
80 if !time.Now().Before(entry.expiresAt) {
81 return nil, context.DeadlineExceeded
82 }
83 return entry.record, nil
84 }
85}