zenmanage 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +27 -0
  3. data/CODE_OF_CONDUCT.md +84 -0
  4. data/CONTRIBUTING.md +22 -0
  5. data/LICENSE +21 -0
  6. data/README.md +382 -0
  7. data/SECURITY.md +9 -0
  8. data/examples/caching.rb +58 -0
  9. data/examples/context_based_flags.rb +45 -0
  10. data/examples/defaults.rb +62 -0
  11. data/examples/percentage_rollouts.rb +37 -0
  12. data/examples/rails_integration.rb +74 -0
  13. data/examples/simple_flags.rb +41 -0
  14. data/lib/generators/zenmanage/install/install_generator.rb +18 -0
  15. data/lib/generators/zenmanage/install/templates/initializer.rb +23 -0
  16. data/lib/zenmanage/api_client.rb +264 -0
  17. data/lib/zenmanage/attribute.rb +55 -0
  18. data/lib/zenmanage/cache/base.rb +46 -0
  19. data/lib/zenmanage/cache/filesystem_cache.rb +88 -0
  20. data/lib/zenmanage/cache/memory_cache.rb +63 -0
  21. data/lib/zenmanage/cache/null_cache.rb +22 -0
  22. data/lib/zenmanage/config_builder.rb +215 -0
  23. data/lib/zenmanage/configuration.rb +118 -0
  24. data/lib/zenmanage/context.rb +125 -0
  25. data/lib/zenmanage/defaults_collection.rb +68 -0
  26. data/lib/zenmanage/errors.rb +21 -0
  27. data/lib/zenmanage/flag.rb +200 -0
  28. data/lib/zenmanage/flag_manager.rb +197 -0
  29. data/lib/zenmanage/hash_access.rb +72 -0
  30. data/lib/zenmanage/rails/controller_helpers.rb +85 -0
  31. data/lib/zenmanage/rails/middleware.rb +34 -0
  32. data/lib/zenmanage/rails/railtie.rb +60 -0
  33. data/lib/zenmanage/rollout.rb +45 -0
  34. data/lib/zenmanage/rollout_bucket.rb +40 -0
  35. data/lib/zenmanage/rule.rb +142 -0
  36. data/lib/zenmanage/rule_engine.rb +156 -0
  37. data/lib/zenmanage/rule_store.rb +164 -0
  38. data/lib/zenmanage/target.rb +37 -0
  39. data/lib/zenmanage/version.rb +6 -0
  40. data/lib/zenmanage/webhook.rb +89 -0
  41. data/lib/zenmanage.rb +183 -0
  42. metadata +216 -0
@@ -0,0 +1,45 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Zenmanage
4
+ # Represents a percentage rollout configuration attached to a flag.
5
+ #
6
+ # Present only when a rollout is active. Contains a separate target/rules pair
7
+ # and the bucketing parameters (salt, percentage).
8
+ # @api private
9
+ class Rollout
10
+ attr_reader :target, :rules, :percentage, :salt, :status
11
+
12
+ # @param target [Target]
13
+ # @param rules [Array<Rule>]
14
+ # @param percentage [Integer] 0–100
15
+ # @param salt [String]
16
+ # @param status [String] always `"active"` when present
17
+ def initialize(target:, rules:, percentage:, salt:, status: "active")
18
+ @target = target
19
+ @rules = Array(rules)
20
+ @percentage = percentage.to_i
21
+ @salt = salt.to_s
22
+ @status = status.to_s
23
+ end
24
+
25
+ def self.from_hash(data)
26
+ new(
27
+ target: Target.from_hash(HashAccess.hash(data, :target)),
28
+ rules: HashAccess.array(data, :rules).map { |r| Rule.from_hash(r) },
29
+ percentage: HashAccess.integer(data, :percentage),
30
+ salt: HashAccess.string(data, :salt, ""),
31
+ status: HashAccess.string(data, :status, "active"),
32
+ )
33
+ end
34
+
35
+ def to_h
36
+ {
37
+ "target" => @target.to_h,
38
+ "rules" => @rules.map(&:to_h),
39
+ "percentage" => @percentage,
40
+ "salt" => @salt,
41
+ "status" => @status,
42
+ }
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "zlib"
4
+
5
+ module Zenmanage
6
+ # Percentage rollout bucketing algorithm.
7
+ #
8
+ # Uses CRC32 (IEEE polynomial) to deterministically assign context identifiers
9
+ # to buckets. The algorithm matches PHP's `hash("crc32b", ...)` and the
10
+ # JavaScript SDK's CRC32B implementation, ensuring consistent bucketing
11
+ # across all SDKs and the API.
12
+ #
13
+ # @example
14
+ # Zenmanage::RolloutBucket.in_bucket?("my-salt", "user-123", 50)
15
+ # # => true or false, deterministically
16
+ class RolloutBucket
17
+ # Determine whether a context identifier falls within a rollout bucket.
18
+ #
19
+ # The algorithm is deterministic: the same `(salt, identifier)` pair always
20
+ # produces the same result. Increasing the percentage only adds new contexts
21
+ # to the bucket — it never removes existing ones (monotonic expansion).
22
+ #
23
+ # @param salt [String] random string unique to the rollout, used as hash seed
24
+ # @param identifier [String, nil] context identifier (e.g., user ID).
25
+ # Returns `false` when `nil` or empty.
26
+ # @param percentage [Integer] rollout percentage (0–100)
27
+ # @return [Boolean]
28
+ # @raise [ArgumentError] if percentage is outside 0–100
29
+ def self.in_bucket?(salt, identifier, percentage)
30
+ raise ArgumentError, "Percentage must be between 0 and 100" unless (0..100).cover?(percentage)
31
+ return false if identifier.nil? || identifier.to_s.empty?
32
+
33
+ input = "#{salt}:#{identifier}"
34
+ hash = Zlib.crc32(input) & 0xFFFFFFFF # ensure unsigned 32-bit
35
+ bucket = hash % 100
36
+
37
+ bucket < percentage
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,142 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Zenmanage
4
+ # Represents a single condition value in a rule (e.g., a segment identifier or attribute value).
5
+ # @api private
6
+ class ConditionValue
7
+ attr_reader :identifier, :type
8
+
9
+ def initialize(identifier, type = nil)
10
+ @identifier = identifier.to_s
11
+ @type = type&.to_s
12
+ end
13
+
14
+ def self.from_hash(data)
15
+ new(HashAccess.string(data, :identifier, ""), HashAccess.string(data, :type))
16
+ end
17
+ end
18
+
19
+ # Represents a rule condition (criteria for matching a context).
20
+ # @api private
21
+ class Condition
22
+ attr_reader :selector, :selector_subtype, :comparer, :values
23
+
24
+ # @param selector [String] one of `"segment"`, `"context"`, `"attribute"`
25
+ # @param selector_subtype [String, nil] attribute name for attribute selectors
26
+ # @param comparer [String] operator (e.g., `"equal"`, `"contains"`)
27
+ # @param values [Array<ConditionValue>]
28
+ # @param readable_values [Boolean] false when the payload's values were missing or
29
+ # held something that names nobody
30
+ def initialize(selector:, comparer:, selector_subtype: nil, values: [], readable_values: true)
31
+ @selector = selector
32
+ @selector_subtype = selector_subtype
33
+ @comparer = comparer
34
+ @values = Array(values)
35
+ @readable_values = readable_values
36
+ end
37
+
38
+ # @return [Boolean]
39
+ def readable_values?
40
+ @readable_values
41
+ end
42
+
43
+ def self.from_hash(data)
44
+ values = HashAccess.array(data, :values).map do |v|
45
+ v.is_a?(Hash) ? ConditionValue.from_hash(v) : ConditionValue.new(v.to_s)
46
+ end
47
+
48
+ new(
49
+ selector: HashAccess.string(data, :selector, ""),
50
+ selector_subtype: (data["selectorSubtype"] || HashAccess.value(data, :selector_subtype))&.to_s,
51
+ comparer: HashAccess.string(data, :comparer, ""),
52
+ values: values,
53
+ readable_values: readable?(HashAccess.value(data, :values)),
54
+ )
55
+ end
56
+
57
+ # Whether every entry of a payload's values names something: a string, or a hash
58
+ # with a string identifier.
59
+ def self.readable?(raw)
60
+ return false if raw.nil?
61
+
62
+ entries = raw.is_a?(Array) ? raw : [raw]
63
+ entries.all? do |entry|
64
+ entry.is_a?(String) || (entry.is_a?(Hash) && HashAccess.value(entry, :identifier).is_a?(String))
65
+ end
66
+ end
67
+ private_class_method :readable?
68
+
69
+ def to_h
70
+ {
71
+ "selector" => @selector,
72
+ "selector_subtype" => @selector_subtype,
73
+ "comparer" => @comparer,
74
+ "values" => @values.map { |v| { "identifier" => v.identifier, "type" => v.type } },
75
+ }
76
+ end
77
+ end
78
+
79
+ # Represents the value component of a rule or target.
80
+ # @api private
81
+ class RuleValue
82
+ attr_reader :version, :value
83
+
84
+ def initialize(version, value)
85
+ @version = version.to_s
86
+ @value = value
87
+ end
88
+
89
+ def self.from_hash(data)
90
+ new(HashAccess.string(data, :version, ""), HashAccess.value(data, :value))
91
+ end
92
+
93
+ def to_h
94
+ { "version" => @version, "value" => @value }
95
+ end
96
+ end
97
+
98
+ # Represents a single targeting rule on a flag.
99
+ # @api private
100
+ class Rule
101
+ attr_reader :version, :description, :criteria, :position, :value
102
+
103
+ def initialize(version:, description:, criteria:, position:, value:)
104
+ @version = version.to_s
105
+ @description = description.to_s
106
+ @criteria = criteria
107
+ @position = position.to_i
108
+ @value = value
109
+ end
110
+
111
+ def self.from_hash(data)
112
+ new(
113
+ version: HashAccess.string(data, :version, ""),
114
+ description: HashAccess.string(data, :description, ""),
115
+ criteria: Condition.from_hash(criteria_hash(data)),
116
+ position: HashAccess.integer(data, :position),
117
+ value: RuleValue.from_hash(HashAccess.hash(data, :value)),
118
+ )
119
+ end
120
+
121
+ # Criteria arrive either as an array of condition hashes or as a single
122
+ # condition hash; only the first condition is used either way.
123
+ #
124
+ # @return [Hash]
125
+ def self.criteria_hash(data)
126
+ criteria = HashAccess.hash(data, :criteria)
127
+ criteria = criteria.first if criteria.is_a?(Array)
128
+ criteria || {}
129
+ end
130
+ private_class_method :criteria_hash
131
+
132
+ def to_h
133
+ {
134
+ "version" => @version,
135
+ "description" => @description,
136
+ "criteria" => @criteria.to_h,
137
+ "position" => @position,
138
+ "value" => @value.to_h,
139
+ }
140
+ end
141
+ end
142
+ end
@@ -0,0 +1,156 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Zenmanage
4
+ # Evaluates targeting rules against a {Context} to determine the applicable flag value.
5
+ #
6
+ # Supports three selector types:
7
+ # - `"context"` — compares the context identifier (and type) with the rule's contexts
8
+ # - `"segment"` — checks whether the context belongs to the rule's segment members
9
+ # - `"attribute"` — compares the values of one context attribute
10
+ #
11
+ # Supported comparers: `equal`, `notequal`, `in`, `notin`, `contains`, `notcontains`,
12
+ # `startswith`, `notstartswith`, `endswith`, `notendswith`, `gt`, `gte`, `lt`, `lte`,
13
+ # `isnull`, `notnull`, `regex`, `notregex`. Underscores, hyphens, spaces and case are
14
+ # ignored, so `not_equal` and `notequal` are the same comparer.
15
+ #
16
+ # The semantics follow the Zenmanage API's own rule evaluation: `equal`, `contains` and
17
+ # the other single-value comparers use the rule's first value, and a negated comparer
18
+ # matches a context that doesn't carry the attribute at all.
19
+ class RuleEngine
20
+ # Each comparer as its positive operator and whether it negates the result.
21
+ COMPARERS = {
22
+ "equal" => [:equal, false], "notequal" => [:equal, true],
23
+ "in" => [:in, false], "notin" => [:in, true],
24
+ "contains" => [:contains, false], "notcontains" => [:contains, true],
25
+ "startswith" => [:startswith, false], "notstartswith" => [:startswith, true],
26
+ "endswith" => [:endswith, false], "notendswith" => [:endswith, true],
27
+ "regex" => [:regex, false], "notregex" => [:regex, true],
28
+ "isnull" => [:null, false], "notnull" => [:null, true],
29
+ "gt" => [:gt, false], "gte" => [:gte, false],
30
+ "lt" => [:lt, false], "lte" => [:lte, false]
31
+ }.freeze
32
+
33
+ NUMERIC_OPERATORS = { gt: :>, gte: :>=, lt: :<, lte: :<= }.freeze
34
+
35
+ private_constant :COMPARERS, :NUMERIC_OPERATORS
36
+
37
+ # Evaluate rules for a flag against the provided context.
38
+ #
39
+ # Rules are sorted by position (lowest first); rules that share a position keep the
40
+ # order they arrived in. Returns the value of the first matching rule, or `nil` if no
41
+ # rule matches.
42
+ #
43
+ # @param flag [Flag]
44
+ # @param context [Context]
45
+ # @return [Hash, nil] the matched rule value hash, or `nil`
46
+ def evaluate(flag, context)
47
+ rules = flag.rules.sort_by.with_index { |rule, index| [rule.position, index] }
48
+
49
+ rules.find { |rule| matches?(rule.criteria, context) }&.value&.value
50
+ end
51
+
52
+ private
53
+
54
+ def matches?(condition, context)
55
+ operator, negated = COMPARERS[condition.comparer.to_s.downcase.delete("_\\- ")]
56
+ # A comparer this release doesn't know never matches, negated or not.
57
+ return false unless operator
58
+
59
+ case condition.selector
60
+ when "context", "segment" then identifier_matches?(condition, context, operator, negated)
61
+ when "attribute" then attribute_matches?(condition, context, operator, negated)
62
+ else false
63
+ end
64
+ end
65
+
66
+ def identifier_matches?(condition, context, operator, negated)
67
+ # `isnull` and `notnull` only mean something for an attribute.
68
+ return false if operator == :null || context.identifier.to_s.empty? || unreadable_segment?(condition)
69
+ # An empty segment has no members, so everyone is outside it. An empty context
70
+ # rule names nobody to compare with.
71
+ return negated && condition.selector == "segment" if condition.values.empty?
72
+
73
+ listed?(candidates(condition, operator), context, operator) != negated
74
+ end
75
+
76
+ # A missing or unreadable member list isn't an empty segment: nothing matches it,
77
+ # negated or not.
78
+ def unreadable_segment?(condition)
79
+ condition.selector == "segment" && !condition.readable_values?
80
+ end
81
+
82
+ # A segment is a membership list, so every member counts under `equal` too.
83
+ def candidates(condition, operator)
84
+ return condition.values unless operator == :equal && condition.selector == "context"
85
+
86
+ condition.values.first(1)
87
+ end
88
+
89
+ def listed?(values, context, operator)
90
+ values.any? do |value|
91
+ applies_to?(value, context) && satisfies?(operator, context.identifier, [value.identifier])
92
+ end
93
+ end
94
+
95
+ # A condition value pinned to a different context type never applies.
96
+ def applies_to?(condition_value, context)
97
+ type = condition_value.type
98
+ type.nil? || type.empty? || type == context.type
99
+ end
100
+
101
+ def attribute_matches?(condition, context, operator, negated)
102
+ name = condition.selector_subtype
103
+ return false if name.nil? || name.empty?
104
+
105
+ attribute = context.attribute(name)
106
+ return null?(attribute) != negated if operator == :null
107
+ # An absent attribute matches no value, so only a negated comparer matches it.
108
+ return negated if attribute.nil?
109
+
110
+ expected = condition.values.map(&:identifier)
111
+ return false unless comparable?(operator, expected)
112
+
113
+ attribute.values.any? { |actual| satisfies?(operator, actual, expected) } != negated
114
+ end
115
+
116
+ # An absent attribute counts as null.
117
+ def null?(attribute)
118
+ attribute.nil? || attribute.values.all?(&:empty?)
119
+ end
120
+
121
+ def comparable?(operator, expected)
122
+ return false if expected.empty?
123
+
124
+ operator == :in || !expected.first.empty?
125
+ end
126
+
127
+ # Whether one actual value satisfies the positive +operator+. Only `in` looks past
128
+ # the first expected value.
129
+ def satisfies?(operator, actual, expected)
130
+ value = expected.first
131
+
132
+ case operator
133
+ when :in then expected.include?(actual)
134
+ when :equal then actual == value
135
+ when :contains then actual.include?(value)
136
+ when :startswith then actual.start_with?(value)
137
+ when :endswith then actual.end_with?(value)
138
+ when :regex then regex_match?(actual, value)
139
+ else compare_numbers(NUMERIC_OPERATORS.fetch(operator), actual, value)
140
+ end
141
+ end
142
+
143
+ def regex_match?(actual, pattern)
144
+ Regexp.new(pattern).match?(actual)
145
+ rescue RegexpError
146
+ false
147
+ end
148
+
149
+ def compare_numbers(comparison, actual, expected)
150
+ left = Float(actual, exception: false)
151
+ right = Float(expected, exception: false)
152
+
153
+ !left.nil? && !right.nil? && left.public_send(comparison, right)
154
+ end
155
+ end
156
+ end
@@ -0,0 +1,164 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Zenmanage
6
+ # Holds the loaded rules for a {FlagManager} and every manager scoped from it, and
7
+ # reloads them once they are older than the cache TTL.
8
+ #
9
+ # - The first load blocks every caller until it finishes.
10
+ # - A later reload is done by one caller; the others keep reading the current rules.
11
+ # - A failed load keeps the rules already in memory and is retried after
12
+ # {RELOAD_RETRY_SECONDS} (or the TTL, if that is shorter), so an outage doesn't turn
13
+ # every flag evaluation into a network request.
14
+ #
15
+ # @api private
16
+ class RuleStore
17
+ CACHE_KEY = "zenmanage_rules"
18
+ # Stored with the cached rules, so whoever reads them knows how old they are.
19
+ EXPIRES_AT_FIELD = "zenmanage_expires_at"
20
+ RELOAD_RETRY_SECONDS = 30
21
+ NO_FLAGS = {}.freeze
22
+
23
+ # @return [StandardError, nil] why the last load failed, or nil if it succeeded
24
+ attr_reader :last_error
25
+
26
+ def initialize(api_client:, cache:, cache_ttl:, logger:, cache_key: CACHE_KEY)
27
+ @api_client = api_client
28
+ @cache = cache
29
+ @cache_key = cache_key
30
+ @cache_ttl = cache_ttl
31
+ @logger = logger
32
+ @flags = nil
33
+ @expires_at = nil
34
+ @last_error = nil
35
+ @mutex = Mutex.new
36
+ end
37
+
38
+ # The current flags, loading or reloading them when due. Never raises.
39
+ #
40
+ # @return [Hash{String => Flag}]
41
+ def flags
42
+ reload_if_due
43
+ @flags || NO_FLAGS
44
+ end
45
+
46
+ # Fetch the rules from the API now, bypassing the cache.
47
+ #
48
+ # @raise [FetchRulesError, InvalidRulesError] if they can't be fetched; the rules
49
+ # already in memory are kept and the load is retried as after a failed reload
50
+ def refresh!
51
+ @mutex.synchronize do
52
+ load_from_api
53
+ rescue StandardError => e
54
+ record_failure(e)
55
+ raise
56
+ end
57
+ end
58
+
59
+ private
60
+
61
+ def reload_if_due
62
+ return unless due?
63
+
64
+ if @flags.nil?
65
+ @mutex.synchronize { load_rules if due? }
66
+ elsif @mutex.try_lock
67
+ begin
68
+ load_rules if due?
69
+ ensure
70
+ @mutex.unlock
71
+ end
72
+ end
73
+ end
74
+
75
+ def due?
76
+ @expires_at.nil? || now >= @expires_at
77
+ end
78
+
79
+ def load_rules
80
+ flags, lifetime = cached_rules
81
+ return load_from_api unless flags
82
+
83
+ store(flags, lifetime)
84
+ rescue StandardError => e
85
+ record_failure(e)
86
+ end
87
+
88
+ def record_failure(error)
89
+ @last_error = error
90
+ @expires_at = now + [RELOAD_RETRY_SECONDS, @cache_ttl].min
91
+ fallback = @flags ? "keeping the rules already in memory" : "falling back to configured defaults"
92
+ @logger.warn("Failed to load rules, #{fallback}: #{error.message}")
93
+ end
94
+
95
+ def load_from_api
96
+ @logger.info("Fetching rules from API")
97
+ data = @api_client.get_rules
98
+ flags = parse(data["flags"], "Failed to parse flag from API")
99
+
100
+ write_cache(data)
101
+ # The TTL starts after the cache write, so the next reload can't read this same entry.
102
+ store(flags, @cache_ttl)
103
+ @logger.info("Rules loaded (#{flags.length} flags, TTL: #{@cache_ttl}s)")
104
+ end
105
+
106
+ def store(flags, lifetime)
107
+ @flags = flags
108
+ @expires_at = now + lifetime
109
+ @last_error = nil
110
+ end
111
+
112
+ # @return [Array(Hash{String => Flag}, Numeric), nil] the cached flags and how many
113
+ # more seconds they're good for, or nil when the cache holds no usable rules
114
+ def cached_rules
115
+ cached = @cache.get(@cache_key)
116
+ return nil unless cached
117
+
118
+ data = JSON.parse(cached)
119
+ return nil unless data.is_a?(Hash) && data["flags"].is_a?(Array)
120
+
121
+ lifetime = remaining_lifetime(data)
122
+ return nil unless lifetime.positive?
123
+
124
+ @logger.debug("Loading rules from cache")
125
+ [parse(data["flags"], "Failed to parse flag"), lifetime]
126
+ rescue StandardError => e
127
+ @logger.warn("Failed to read cached rules: #{e.message}")
128
+ nil
129
+ end
130
+
131
+ # Rules another process cached are only used for what's left of their TTL. Wall
132
+ # clock time, because it's compared across processes.
133
+ def remaining_lifetime(data)
134
+ expires_at = data[EXPIRES_AT_FIELD]
135
+ return @cache_ttl unless expires_at.is_a?(Numeric)
136
+
137
+ [expires_at - Time.now.to_f, @cache_ttl].min
138
+ end
139
+
140
+ # A cache that can't be written to costs a refetch later; it doesn't cost the rules.
141
+ def write_cache(data)
142
+ entry = data.merge(EXPIRES_AT_FIELD => Time.now.to_f + @cache_ttl)
143
+ @cache.set(@cache_key, JSON.generate(entry), @cache_ttl)
144
+ rescue StandardError => e
145
+ @logger.warn("Failed to cache rules: #{e.message}")
146
+ end
147
+
148
+ # Build flags from their payloads, dropping (and logging) any that fail.
149
+ #
150
+ # @return [Hash{String => Flag}]
151
+ def parse(flag_data, error_prefix)
152
+ flag_data.each_with_object({}) do |data, flags|
153
+ flag = Flag.from_hash(data)
154
+ flags[flag.key] ||= flag
155
+ rescue StandardError => e
156
+ @logger.warn("#{error_prefix}: #{e.message}")
157
+ end.freeze
158
+ end
159
+
160
+ def now
161
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
162
+ end
163
+ end
164
+ end
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Zenmanage
4
+ # Represents a flag target — the default value shown when no rule matches.
5
+ # @api private
6
+ class Target
7
+ attr_reader :version, :expired_at, :published_at, :scheduled_at, :value
8
+
9
+ def initialize(value:, version: "", expired_at: nil, published_at: nil, scheduled_at: nil)
10
+ @version = version.to_s
11
+ @expired_at = expired_at
12
+ @published_at = published_at
13
+ @scheduled_at = scheduled_at
14
+ @value = value
15
+ end
16
+
17
+ def self.from_hash(data)
18
+ new(
19
+ version: HashAccess.string(data, :version, ""),
20
+ expired_at: HashAccess.value(data, :expired_at),
21
+ published_at: HashAccess.value(data, :published_at),
22
+ scheduled_at: HashAccess.value(data, :scheduled_at),
23
+ value: RuleValue.from_hash(HashAccess.hash(data, :value)),
24
+ )
25
+ end
26
+
27
+ def to_h
28
+ {
29
+ "version" => @version,
30
+ "expired_at" => @expired_at,
31
+ "published_at" => @published_at,
32
+ "scheduled_at" => @scheduled_at,
33
+ "value" => @value.to_h,
34
+ }
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Zenmanage
4
+ # The current version of the Zenmanage Ruby SDK.
5
+ VERSION = "1.0.0"
6
+ end
@@ -0,0 +1,89 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "openssl"
4
+
5
+ module Zenmanage
6
+ # Receives Zenmanage environment webhooks, so rule changes apply as soon as they are
7
+ # published instead of when the cache TTL lapses.
8
+ module Webhook
9
+ SIGNATURE_PREFIX = "sha256="
10
+
11
+ # Whether +signature+ (the `X-Zenmanage-Signature` header) is the HMAC-SHA256 of
12
+ # +payload+ under the webhook's signing secret.
13
+ #
14
+ # @param payload [String] the raw request body, exactly as received
15
+ # @param signature [String, nil] formatted as `sha256=<hex>`
16
+ # @param secret [String, nil] the signing secret (`whsec_...`)
17
+ # @return [Boolean]
18
+ def self.verify_signature(payload, signature, secret)
19
+ return false if secret.to_s.empty? || !signature.to_s.start_with?(SIGNATURE_PREFIX)
20
+
21
+ expected = SIGNATURE_PREFIX + OpenSSL::HMAC.hexdigest("SHA256", secret, payload.to_s)
22
+
23
+ OpenSSL.secure_compare(expected, signature.to_s)
24
+ end
25
+
26
+ # A Rack app that refreshes the flag rules when it receives a signed webhook.
27
+ #
28
+ # It refreshes the process that handles the request. Other processes pick the change
29
+ # up when their cache TTL lapses.
30
+ #
31
+ # @example config/routes.rb
32
+ # mount Zenmanage::Webhook::Endpoint.new => "/zenmanage/webhook"
33
+ #
34
+ # @example Sinatra / plain Rack
35
+ # map "/zenmanage/webhook" do
36
+ # run Zenmanage::Webhook::Endpoint.new(client: client, secret: ENV["MY_SECRET"])
37
+ # end
38
+ class Endpoint
39
+ SIGNATURE_ENV_KEY = "HTTP_X_ZENMANAGE_SIGNATURE"
40
+ ALLOWED_METHODS = %w[POST PUT PATCH].freeze
41
+ MAX_BODY_BYTES = 1_048_576
42
+
43
+ # @param secret [String, nil] signing secret; defaults to `ZENMANAGE_WEBHOOK_SECRET`
44
+ # @param client [Client, nil] client to refresh; defaults to {Zenmanage.client}
45
+ def initialize(secret: nil, client: nil)
46
+ @secret = secret
47
+ @client = client
48
+ end
49
+
50
+ # @param env [Hash] Rack environment
51
+ def call(env)
52
+ return respond(405, "Method not allowed.") unless ALLOWED_METHODS.include?(env["REQUEST_METHOD"])
53
+
54
+ secret = @secret || ENV.fetch("ZENMANAGE_WEBHOOK_SECRET", nil)
55
+ return respond(500, "Webhook secret is not configured.") if secret.to_s.empty?
56
+
57
+ body = read_body(env["rack.input"])
58
+ return respond(413, "Payload too large.") if body.bytesize > MAX_BODY_BYTES
59
+ return respond(401, "Invalid signature.") unless Webhook.verify_signature(body, env[SIGNATURE_ENV_KEY], secret)
60
+
61
+ refresh
62
+ end
63
+
64
+ private
65
+
66
+ # The signature covers the whole body, so rewind in case an earlier middleware
67
+ # (Rack::MethodOverride, for one) has already read it.
68
+ def read_body(input)
69
+ input.rewind if input.respond_to?(:rewind)
70
+ input&.read(MAX_BODY_BYTES + 1).to_s
71
+ end
72
+
73
+ def refresh
74
+ client = @client || Zenmanage.client
75
+ return respond(500, "Zenmanage is not configured.") unless client
76
+
77
+ client.flags.refresh_rules
78
+ respond(200, "Flag rules refreshed.")
79
+ rescue Zenmanage::Error
80
+ # A failure status makes Zenmanage retry the delivery.
81
+ respond(502, "Could not refresh flag rules.")
82
+ end
83
+
84
+ def respond(status, message)
85
+ [status, { "content-type" => "application/json" }, [%({"message":"#{message}"})]]
86
+ end
87
+ end
88
+ end
89
+ end