You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

95 lines
2.3 KiB

  1. // Copyright 2017 Google Inc. All rights reserved.
  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 cookie
  15. import (
  16. "encoding/json"
  17. "net/http"
  18. "github.com/google/martian"
  19. "github.com/google/martian/filter"
  20. "github.com/google/martian/log"
  21. "github.com/google/martian/parse"
  22. )
  23. var noop = martian.Noop("cookie.Filter")
  24. type filterJSON struct {
  25. Name string `json:"name"`
  26. Value string `json:"value"`
  27. Modifier json.RawMessage `json:"modifier"`
  28. ElseModifier json.RawMessage `json:"else"`
  29. Scope []parse.ModifierType `json:"scope"`
  30. }
  31. func init() {
  32. parse.Register("cookie.Filter", filterFromJSON)
  33. }
  34. // NewFilter builds a new cookie filter.
  35. func NewFilter(cookie *http.Cookie) *filter.Filter {
  36. log.Debugf("cookie.NewFilter: cookie: %s", cookie.String())
  37. f := filter.New()
  38. m := NewMatcher(cookie)
  39. f.SetRequestCondition(m)
  40. f.SetResponseCondition(m)
  41. return f
  42. }
  43. // filterFromJSON builds a header.Filter from JSON.
  44. //
  45. // Example JSON:
  46. // {
  47. // "scope": ["request", "result"],
  48. // "name": "Martian-Testing",
  49. // "value": "true",
  50. // "modifier": { ... },
  51. // "else": { ... }
  52. // }
  53. func filterFromJSON(b []byte) (*parse.Result, error) {
  54. msg := &filterJSON{}
  55. if err := json.Unmarshal(b, msg); err != nil {
  56. return nil, err
  57. }
  58. cookie := &http.Cookie{
  59. Name: msg.Name,
  60. Value: msg.Value,
  61. }
  62. filter := NewFilter(cookie)
  63. m, err := parse.FromJSON(msg.Modifier)
  64. if err != nil {
  65. return nil, err
  66. }
  67. filter.RequestWhenTrue(m.RequestModifier())
  68. filter.ResponseWhenTrue(m.ResponseModifier())
  69. if msg.ElseModifier != nil {
  70. em, err := parse.FromJSON(msg.ElseModifier)
  71. if err != nil {
  72. return nil, err
  73. }
  74. filter.RequestWhenFalse(em.RequestModifier())
  75. filter.ResponseWhenFalse(em.ResponseModifier())
  76. }
  77. return parse.NewResult(filter, msg.Scope)
  78. }