server_access_control.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright 2018 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package etcdserver
  15. import "sync"
  16. // AccessController controls etcd server HTTP request access.
  17. type AccessController struct {
  18. corsMu sync.RWMutex
  19. CORS map[string]struct{}
  20. hostWhitelistMu sync.RWMutex
  21. HostWhitelist map[string]struct{}
  22. }
  23. // NewAccessController returns a new "AccessController" with default "*" values.
  24. func NewAccessController() *AccessController {
  25. return &AccessController{
  26. CORS: map[string]struct{}{"*": {}},
  27. HostWhitelist: map[string]struct{}{"*": {}},
  28. }
  29. }
  30. // OriginAllowed determines whether the server will allow a given CORS origin.
  31. // If CORS is empty, allow all.
  32. func (ac *AccessController) OriginAllowed(origin string) bool {
  33. ac.corsMu.RLock()
  34. defer ac.corsMu.RUnlock()
  35. if len(ac.CORS) == 0 { // allow all
  36. return true
  37. }
  38. _, ok := ac.CORS["*"]
  39. if ok {
  40. return true
  41. }
  42. _, ok = ac.CORS[origin]
  43. return ok
  44. }
  45. // IsHostWhitelisted returns true if the host is whitelisted.
  46. // If whitelist is empty, allow all.
  47. func (ac *AccessController) IsHostWhitelisted(host string) bool {
  48. ac.hostWhitelistMu.RLock()
  49. defer ac.hostWhitelistMu.RUnlock()
  50. if len(ac.HostWhitelist) == 0 { // allow all
  51. return true
  52. }
  53. _, ok := ac.HostWhitelist["*"]
  54. if ok {
  55. return true
  56. }
  57. _, ok = ac.HostWhitelist[host]
  58. return ok
  59. }