whitelist.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package jwk
  2. import "regexp"
  3. // InsecureWhitelist allows any URLs to be fetched. This is the default
  4. // behavior of `jwk.Fetch()`, but this exists to allow other libraries
  5. // (such as jws, via jws.VerifyAuto) and users to be able to explicitly
  6. // state that they intend to not check the URLs that are being fetched
  7. type InsecureWhitelist struct{}
  8. func (InsecureWhitelist) IsAllowed(string) bool {
  9. return true
  10. }
  11. // RegexpWhitelist is a jwk.Whitelist object comprised of a list of *regexp.Regexp
  12. // objects. All entries in the list are tried until one matches. If none of the
  13. // *regexp.Regexp objects match, then the URL is deemed unallowed.
  14. type RegexpWhitelist struct {
  15. patterns []*regexp.Regexp
  16. }
  17. func NewRegexpWhitelist() *RegexpWhitelist {
  18. return &RegexpWhitelist{}
  19. }
  20. func (w *RegexpWhitelist) Add(pat *regexp.Regexp) *RegexpWhitelist {
  21. w.patterns = append(w.patterns, pat)
  22. return w
  23. }
  24. // IsAlloed returns true if any of the patterns in the whitelist
  25. // returns true.
  26. func (w *RegexpWhitelist) IsAllowed(u string) bool {
  27. for _, pat := range w.patterns {
  28. if pat.MatchString(u) {
  29. return true
  30. }
  31. }
  32. return false
  33. }
  34. // MapWhitelist is a jwk.Whitelist object comprised of a map of strings.
  35. // If the URL exists in the map, then the URL is allowed to be fetched.
  36. type MapWhitelist struct {
  37. store map[string]struct{}
  38. }
  39. func NewMapWhitelist() *MapWhitelist {
  40. return &MapWhitelist{store: make(map[string]struct{})}
  41. }
  42. func (w *MapWhitelist) Add(pat string) *MapWhitelist {
  43. w.store[pat] = struct{}{}
  44. return w
  45. }
  46. func (w *MapWhitelist) IsAllowed(u string) bool {
  47. _, b := w.store[u]
  48. return b
  49. }
  50. // WhitelistFunc is a jwk.Whitelist object based on a function.
  51. // You can perform any sort of check against the given URL to determine
  52. // if it can be fetched or not.
  53. type WhitelistFunc func(string) bool
  54. func (w WhitelistFunc) IsAllowed(u string) bool {
  55. return w(u)
  56. }