Module: PgPipeline::SessionGuard

Defined in:
lib/pg_pipeline/session_guard.rb

Constant Summary collapse

VALID_MODES =
%i[default strict].freeze
ALLOWED_LEADING =
%w[select insert update delete merge values with].freeze
FORBIDDEN_PATTERNS =
{
  "set_config" => /\bset_config\s*\(/i,
  "setseed" => /\bsetseed\s*\(/i,
  "currval" => /\bcurrval\s*\(/i,
  "lastval" => /\blastval\s*\(/i,
  "session-advisory-lock" => /\bpg_(?:try_)?advisory_lock(?:_shared)?\s*\(/i,
  "session-advisory-unlock" => /\bpg_advisory_unlock(?:_shared|_all)?\s*\(/i,
  "select-into-temp" => /\binto\s+(?:(?:global|local)\s+)?temp(?:orary)?\b/i,
  "select-into-pg-temp" => /\binto\s+(?:table\s+)?pg_temp(?:_\d+)?\s*\./i
}.freeze
STRICT_FORBIDDEN =
{
  "nextval" => /\bnextval\s*\(/i,
  "setval" => /\bsetval\s*\(/i,
  "setseed" => /\bsetseed\s*\(/i,
  "set_config" => /\bset_config\s*\(/i,
  "session-advisory-lock" => /\bpg_(?:try_)?advisory_lock(?:_shared)?\s*\(/i,
  "session-advisory-unlock" => /\bpg_advisory_unlock(?:_shared|_all)?\s*\(/i,
  "pg_export_snapshot" => /\bpg_export_snapshot\s*\(/i
}.freeze
GUARD_CACHE_LIMIT =
2048

Class Method Summary collapse

Class Method Details

.assert_multiplexable!(sql, mode: :default) ⇒ Object



32
33
34
# File 'lib/pg_pipeline/session_guard.rb', line 32

def assert_multiplexable!(sql, mode: :default)
  assert_multiplexable_normalized!(sql, mode: normalize_mode!(mode))
end

.assert_multiplexable_normalized!(sql, mode:) ⇒ Object



36
37
38
39
40
41
42
43
44
45
# File 'lib/pg_pipeline/session_guard.rb', line 36

def assert_multiplexable_normalized!(sql, mode:)
  reason = unsafe_reason_normalized(sql, mode: mode)
  return true unless reason

  raise UnsafeMultiplexError,
        "refusing to multiplex SQL (#{reason}); the shared path only accepts " \
        "session-neutral operations. Use Client#session for session work or " \
        "Client#transaction for an explicit transaction.\n" \
        "  offending SQL: #{sql.to_s.strip[0, 160]}"
end

.code_only(sql) ⇒ Object



96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/pg_pipeline/session_guard.rb', line 96

def code_only(sql)
  source = sql.to_s.b
  output = String.new(capacity: source.bytesize, encoding: Encoding::BINARY)
  index = 0
  block_depth = 0

  while index < source.bytesize
    if block_depth.positive?
      if source.byteslice(index, 2) == "/*"
        block_depth += 1
        output << "  "
        index += 2
      elsif source.byteslice(index, 2) == "*/"
        block_depth -= 1
        output << "  "
        index += 2
      else
        output << (source.getbyte(index) == 10 ? "\n" : " ")
        index += 1
      end
      next
    end

    if source.byteslice(index, 2) == "--"
      newline = source.index("\n", index + 2)
      if newline
        output << " " * (newline - index) << "\n"
        index = newline + 1
      else
        output << " " * (source.bytesize - index)
        break
      end
      next
    end

    if source.byteslice(index, 2) == "/*"
      block_depth = 1
      output << "  "
      index += 2
      next
    end

    byte = source.getbyte(index)
    if byte == 39
      index = mask_quoted(source, output, index, 39, escape_backslash: escape_string_prefix?(source, index))
      next
    end

    if byte == 34
      index = mask_quoted(source, output, index, 34, escape_backslash: false)
      next
    end

    if byte == 36
      remainder = source.byteslice(index, source.bytesize - index)
      tag = remainder.match(/\A\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$/)&.[](0)
      if tag
        closing = source.index(tag, index + tag.bytesize)
        finish = closing ? closing + tag.bytesize : source.bytesize
        output << " " * (finish - index)
        index = finish
        next
      end
    end

    output << source.getbyte(index)
    index += 1
  end

  output
end

.compute_unsafe_reason(sql, mode) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/pg_pipeline/session_guard.rb', line 68

def compute_unsafe_reason(sql, mode)
  code = code_only(sql)
  lead = code[/\A\s*([a-zA-Z_]+)/, 1]&.downcase

  return "empty" unless lead
  return "leading:#{lead}" unless ALLOWED_LEADING.include?(lead)
  return "multiple-statements" if multiple_statements?(code)

  FORBIDDEN_PATTERNS.each do |name, pattern|
    return name if code.match?(pattern)
  end

  if mode == :strict
    STRICT_FORBIDDEN.each do |name, pattern|
      return "strict:#{name}" if code.match?(pattern)
    end
  end

  nil
end

.guard_cacheObject



64
65
66
# File 'lib/pg_pipeline/session_guard.rb', line 64

def guard_cache
  @guard_cache ||= { default: {}, strict: {} }
end

.multiple_statements?(code) ⇒ Boolean

Returns:

  • (Boolean)


211
212
213
214
215
216
217
218
# File 'lib/pg_pipeline/session_guard.rb', line 211

def multiple_statements?(code)
  semicolons = []
  code.each_char.with_index { |char, i| semicolons << i if char == ";" }
  return false if semicolons.empty?

  last_non_space = code.rstrip.length - 1
  semicolons.length > 1 || semicolons.first != last_non_space
end

.normalize_mode!(mode) ⇒ Object

Raises:

  • (ArgumentError)


89
90
91
92
93
94
# File 'lib/pg_pipeline/session_guard.rb', line 89

def normalize_mode!(mode)
  normalized = mode.respond_to?(:to_sym) ? mode.to_sym : mode
  return normalized if VALID_MODES.include?(normalized)

  raise ArgumentError, "guard must be one of: #{VALID_MODES.map(&:inspect).join(", ")}"
end

.unsafe_reason(sql, mode: :default) ⇒ Object



49
50
51
# File 'lib/pg_pipeline/session_guard.rb', line 49

def unsafe_reason(sql, mode: :default)
  unsafe_reason_normalized(sql, mode: normalize_mode!(mode))
end

.unsafe_reason_normalized(sql, mode:) ⇒ Object



53
54
55
56
57
58
59
60
61
62
# File 'lib/pg_pipeline/session_guard.rb', line 53

def unsafe_reason_normalized(sql, mode:)
  key = sql.to_s
  cache = guard_cache.fetch(mode)
  return cache[key] if cache.key?(key)

  reason = compute_unsafe_reason(key, mode)
  cache.clear if cache.size >= GUARD_CACHE_LIMIT
  cache[key] = reason
  reason
end