allow_list.go 932 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package nebula
  2. import (
  3. "fmt"
  4. "regexp"
  5. )
  6. type AllowList struct {
  7. // The values of this cidrTree are `bool`, signifying allow/deny
  8. cidrTree *CIDRTree
  9. // To avoid ambiguity, all rules must be true, or all rules must be false.
  10. nameRules []AllowListNameRule
  11. }
  12. type AllowListNameRule struct {
  13. Name *regexp.Regexp
  14. Allow bool
  15. }
  16. func (al *AllowList) Allow(ip uint32) bool {
  17. if al == nil {
  18. return true
  19. }
  20. result := al.cidrTree.MostSpecificContains(ip)
  21. switch v := result.(type) {
  22. case bool:
  23. return v
  24. default:
  25. panic(fmt.Errorf("invalid state, allowlist returned: %T %v", result, result))
  26. }
  27. }
  28. func (al *AllowList) AllowName(name string) bool {
  29. if al == nil || len(al.nameRules) == 0 {
  30. return true
  31. }
  32. for _, rule := range al.nameRules {
  33. if rule.Name.MatchString(name) {
  34. return rule.Allow
  35. }
  36. }
  37. // If no rules match, return the default, which is the inverse of the rules
  38. return !al.nameRules[0].Allow
  39. }