selector.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. package features
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "hash/fnv"
  7. "net"
  8. "sync"
  9. "time"
  10. "github.com/rs/zerolog"
  11. )
  12. const (
  13. featureSelectorHostname = "cfd-features.argotunnel.com"
  14. defaultRefreshFreq = time.Hour * 6
  15. lookupTimeout = time.Second * 10
  16. )
  17. type PostQuantumMode uint8
  18. const (
  19. // Prefer post quantum, but fallback if connection cannot be established
  20. PostQuantumPrefer PostQuantumMode = iota
  21. // If the user passes the --post-quantum flag, we override
  22. // CurvePreferences to only support hybrid post-quantum key agreements.
  23. PostQuantumStrict
  24. )
  25. // If the TXT record adds other fields, the umarshal logic will ignore those keys
  26. // If the TXT record is missing a key, the field will unmarshal to the default Go value
  27. // pq was removed in TUN-7970
  28. type featuresRecord struct{}
  29. func NewFeatureSelector(ctx context.Context, accountTag string, staticFeatures StaticFeatures, logger *zerolog.Logger) (*FeatureSelector, error) {
  30. return newFeatureSelector(ctx, accountTag, logger, newDNSResolver(), staticFeatures, defaultRefreshFreq)
  31. }
  32. // FeatureSelector determines if this account will try new features. It preiodically queries a DNS TXT record
  33. // to see which features are turned on
  34. type FeatureSelector struct {
  35. accountHash int32
  36. logger *zerolog.Logger
  37. resolver resolver
  38. staticFeatures StaticFeatures
  39. // lock protects concurrent access to dynamic features
  40. lock sync.RWMutex
  41. features featuresRecord
  42. }
  43. // Features set by user provided flags
  44. type StaticFeatures struct {
  45. PostQuantumMode *PostQuantumMode
  46. }
  47. func newFeatureSelector(ctx context.Context, accountTag string, logger *zerolog.Logger, resolver resolver, staticFeatures StaticFeatures, refreshFreq time.Duration) (*FeatureSelector, error) {
  48. selector := &FeatureSelector{
  49. accountHash: switchThreshold(accountTag),
  50. logger: logger,
  51. resolver: resolver,
  52. staticFeatures: staticFeatures,
  53. }
  54. if err := selector.refresh(ctx); err != nil {
  55. logger.Err(err).Msg("Failed to fetch features, default to disable")
  56. }
  57. // Run refreshLoop next time we have a new feature to rollout
  58. return selector, nil
  59. }
  60. func (fs *FeatureSelector) PostQuantumMode() PostQuantumMode {
  61. if fs.staticFeatures.PostQuantumMode != nil {
  62. return *fs.staticFeatures.PostQuantumMode
  63. }
  64. return PostQuantumPrefer
  65. }
  66. func (fs *FeatureSelector) refreshLoop(ctx context.Context, refreshFreq time.Duration) {
  67. ticker := time.NewTicker(refreshFreq)
  68. for {
  69. select {
  70. case <-ctx.Done():
  71. return
  72. case <-ticker.C:
  73. err := fs.refresh(ctx)
  74. if err != nil {
  75. fs.logger.Err(err).Msg("Failed to refresh feature selector")
  76. }
  77. }
  78. }
  79. }
  80. func (fs *FeatureSelector) refresh(ctx context.Context) error {
  81. record, err := fs.resolver.lookupRecord(ctx)
  82. if err != nil {
  83. return err
  84. }
  85. var features featuresRecord
  86. if err := json.Unmarshal(record, &features); err != nil {
  87. return err
  88. }
  89. fs.lock.Lock()
  90. defer fs.lock.Unlock()
  91. fs.features = features
  92. return nil
  93. }
  94. // resolver represents an object that can look up featuresRecord
  95. type resolver interface {
  96. lookupRecord(ctx context.Context) ([]byte, error)
  97. }
  98. type dnsResolver struct {
  99. resolver *net.Resolver
  100. }
  101. func newDNSResolver() *dnsResolver {
  102. return &dnsResolver{
  103. resolver: net.DefaultResolver,
  104. }
  105. }
  106. func (dr *dnsResolver) lookupRecord(ctx context.Context) ([]byte, error) {
  107. ctx, cancel := context.WithTimeout(ctx, lookupTimeout)
  108. defer cancel()
  109. records, err := dr.resolver.LookupTXT(ctx, featureSelectorHostname)
  110. if err != nil {
  111. return nil, err
  112. }
  113. if len(records) == 0 {
  114. return nil, fmt.Errorf("No TXT record found for %s to determine which features to opt-in", featureSelectorHostname)
  115. }
  116. return []byte(records[0]), nil
  117. }
  118. func switchThreshold(accountTag string) int32 {
  119. h := fnv.New32a()
  120. _, _ = h.Write([]byte(accountTag))
  121. return int32(h.Sum32() % 100)
  122. }