allow_list.go 940 B

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