/cloudmock/openstack/mocknetworking/securitygrouprules.go

https://github.com/kubernetes/kops · Go · 205 lines · 164 code · 22 blank · 19 comment · 54 complexity · 0223f71ee9ae8fafdbad2d34b23510d1 MD5 · raw file

  1. /*
  2. Copyright 2020 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package mocknetworking
  14. import (
  15. "encoding/json"
  16. "fmt"
  17. "net/http"
  18. "net/url"
  19. "regexp"
  20. "strconv"
  21. "github.com/google/uuid"
  22. "github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/security/rules"
  23. )
  24. type ruleListResponse struct {
  25. SecurityGroupRules []rules.SecGroupRule `json:"security_group_rules"`
  26. }
  27. type ruleGetResponse struct {
  28. SecurityGroupRule rules.SecGroupRule `json:"security_group_rule"`
  29. }
  30. type ruleCreateRequest struct {
  31. SecurityGroupRule rules.CreateOpts `json:"security_group_rule"`
  32. }
  33. func (m *MockClient) mockSecurityGroupRules() {
  34. re := regexp.MustCompile(`/security-group-rules/?`)
  35. handler := func(w http.ResponseWriter, r *http.Request) {
  36. m.mutex.Lock()
  37. defer m.mutex.Unlock()
  38. w.Header().Add("Content-Type", "application/json")
  39. sgrID := re.ReplaceAllString(r.URL.Path, "")
  40. switch r.Method {
  41. case http.MethodGet:
  42. if sgrID == "" {
  43. r.ParseForm()
  44. m.listSecurityGroupRules(w, r.Form)
  45. } else {
  46. m.getSecurityGroupRule(w, sgrID)
  47. }
  48. case http.MethodPost:
  49. m.createSecurityGroupRule(w, r)
  50. case http.MethodDelete:
  51. m.deleteSecurityGroupRule(w, sgrID)
  52. default:
  53. w.WriteHeader(http.StatusBadRequest)
  54. }
  55. }
  56. m.Mux.HandleFunc("/security-group-rules/", handler)
  57. m.Mux.HandleFunc("/security-group-rules", handler)
  58. }
  59. func (m *MockClient) listSecurityGroupRules(w http.ResponseWriter, vals url.Values) {
  60. w.WriteHeader(http.StatusOK)
  61. sgrs := filterRules(m.securityGroupRules, vals)
  62. resp := ruleListResponse{
  63. SecurityGroupRules: sgrs,
  64. }
  65. respB, err := json.Marshal(resp)
  66. if err != nil {
  67. panic(fmt.Sprintf("failed to marshal %+v", resp))
  68. }
  69. _, err = w.Write(respB)
  70. if err != nil {
  71. panic("failed to write body")
  72. }
  73. }
  74. func (m *MockClient) getSecurityGroupRule(w http.ResponseWriter, ruleID string) {
  75. if rule, ok := m.securityGroupRules[ruleID]; ok {
  76. resp := ruleGetResponse{
  77. SecurityGroupRule: rule,
  78. }
  79. respB, err := json.Marshal(resp)
  80. if err != nil {
  81. panic(fmt.Sprintf("failed to marshal %+v", resp))
  82. }
  83. _, err = w.Write(respB)
  84. if err != nil {
  85. panic("failed to write body")
  86. }
  87. } else {
  88. w.WriteHeader(http.StatusNotFound)
  89. }
  90. }
  91. func (m *MockClient) deleteSecurityGroupRule(w http.ResponseWriter, ruleID string) {
  92. if _, ok := m.securityGroupRules[ruleID]; ok {
  93. delete(m.securityGroupRules, ruleID)
  94. w.WriteHeader(http.StatusOK)
  95. } else {
  96. w.WriteHeader(http.StatusNotFound)
  97. }
  98. }
  99. func (m *MockClient) createSecurityGroupRule(w http.ResponseWriter, r *http.Request) {
  100. var create ruleCreateRequest
  101. err := json.NewDecoder(r.Body).Decode(&create)
  102. if err != nil {
  103. panic("error decoding create rule request")
  104. }
  105. w.WriteHeader(http.StatusAccepted)
  106. rule := rules.SecGroupRule{
  107. ID: uuid.New().String(),
  108. PortRangeMax: create.SecurityGroupRule.PortRangeMax,
  109. PortRangeMin: create.SecurityGroupRule.PortRangeMin,
  110. Protocol: string(create.SecurityGroupRule.Protocol),
  111. RemoteIPPrefix: create.SecurityGroupRule.RemoteIPPrefix,
  112. EtherType: string(create.SecurityGroupRule.EtherType),
  113. RemoteGroupID: create.SecurityGroupRule.RemoteGroupID,
  114. Direction: string(create.SecurityGroupRule.Direction),
  115. SecGroupID: create.SecurityGroupRule.SecGroupID,
  116. }
  117. m.securityGroupRules[rule.ID] = rule
  118. resp := ruleGetResponse{
  119. SecurityGroupRule: rule,
  120. }
  121. respB, err := json.Marshal(resp)
  122. if err != nil {
  123. panic(fmt.Sprintf("failed to marshal %+v", resp))
  124. }
  125. _, err = w.Write(respB)
  126. if err != nil {
  127. panic("failed to write body")
  128. }
  129. }
  130. func filterRules(allRules map[string]rules.SecGroupRule, vals url.Values) []rules.SecGroupRule {
  131. sgrs := make([]rules.SecGroupRule, 0)
  132. securityGroupIDFilter := vals.Get("security_group_id")
  133. directionFilter := vals.Get("direction")
  134. ethertypeFilter := vals.Get("ethertype")
  135. portRangeMaxFilter := vals.Get("port_range_max")
  136. portRangeMinFilter := vals.Get("port_range_min")
  137. protocolFilter := vals.Get("protocol")
  138. remoteGroupIDFilter := vals.Get("remote_group_id")
  139. // Example query string from cloudup
  140. // ?direction=ingress&ethertype=IPv4&port_range_max=53&port_range_min=53&protocol=udp&remote_group_id=3b39402b-320c-4e18-a2a1-11b5577a850f&security_group_id=df829d89-637c-4aff-8a46-716977f73464
  141. for _, s := range allRules {
  142. if securityGroupIDFilter != "" && s.SecGroupID != securityGroupIDFilter {
  143. continue
  144. }
  145. if directionFilter != "" && s.Direction != directionFilter {
  146. continue
  147. }
  148. if ethertypeFilter != "" && s.EtherType != ethertypeFilter {
  149. continue
  150. }
  151. if portRangeMaxFilter != "" {
  152. portRangeMax, err := strconv.ParseInt(portRangeMaxFilter, 10, 64)
  153. if err != nil {
  154. panic(fmt.Sprintf("failed to parse port_range_max parameter %v", err))
  155. }
  156. if int64(s.PortRangeMax) != portRangeMax {
  157. continue
  158. }
  159. }
  160. if portRangeMinFilter != "" {
  161. portRangeMin, err := strconv.ParseInt(portRangeMinFilter, 10, 64)
  162. if err != nil {
  163. panic(fmt.Sprintf("failed to parse port_range_max parameter %v", err))
  164. }
  165. if int64(s.PortRangeMin) != portRangeMin {
  166. continue
  167. }
  168. }
  169. if protocolFilter != "" && s.Protocol != protocolFilter {
  170. continue
  171. }
  172. // If a query doesn't provide remote_group_id this indicates we want to filter for rules
  173. // with an empty string value rather than not filter for remote_group_id
  174. if s.RemoteGroupID != remoteGroupIDFilter {
  175. continue
  176. }
  177. sgrs = append(sgrs, s)
  178. }
  179. return sgrs
  180. }