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
PATTERN_PREFILTER =
/\binto\b/i
NEEDS_MASK =
/['"]|--|\/\*|\$[A-Za-z_0-9]*\$/
LEADING_KEYWORD =
/\A\s*([a-zA-Z_]+)/
WHITESPACE_BYTES =
[9, 10, 11, 12, 13, 32].freeze
GUARD_CACHE_LIMIT =
2048
SAFE =
:safe

Class Method Summary collapse

Class Method Details

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



37
38
39
# File 'lib/pg_pipeline/session_guard.rb', line 37

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

.assert_multiplexable_normalized!(sql, mode:) ⇒ Object



41
42
43
44
45
46
47
48
49
50
# File 'lib/pg_pipeline/session_guard.rb', line 41

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



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
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/pg_pipeline/session_guard.rb', line 104

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

  while index < size
    byte = source.getbyte(index)
    nxt = index + 1 < size ? source.getbyte(index + 1) : nil

    if block_depth.positive?
      if byte == 47 && nxt == 42
        block_depth += 1
        output << "  "
        index += 2
      elsif byte == 42 && nxt == 47
        block_depth -= 1
        output << "  "
        index += 2
      else
        output << (byte == 10 ? 10 : 32)
        index += 1
      end
      next
    end

    if byte == 45 && nxt == 45
      newline = source.index("\n", index + 2)
      if newline
        output << (" " * (newline - index)) << "\n"
        index = newline + 1
      else
        output << (" " * (size - index))
        break
      end
      next
    end

    if byte == 47 && nxt == 42
      block_depth = 1
      output << "  "
      index += 2
      next
    end

    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, size - 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 : size
        output << (" " * (finish - index))
        index = finish
        next
      end
    end

    output << byte
    index += 1
  end

  output
end

.compute_unsafe_reason(sql, mode) ⇒ Object



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/pg_pipeline/session_guard.rb', line 75

def compute_unsafe_reason(sql, mode)
  code = NEEDS_MASK.match?(sql) ? code_only(sql) : sql
  lead = code[LEADING_KEYWORD, 1]&.downcase

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

  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



71
72
73
# File 'lib/pg_pipeline/session_guard.rb', line 71

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

.multiple_statements?(code) ⇒ Boolean

Returns:

  • (Boolean)


222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/pg_pipeline/session_guard.rb', line 222

def multiple_statements?(code)
  first = code.index(";")
  return false unless first

  index = first + 1
  size = code.bytesize
  while index < size
    return true unless WHITESPACE_BYTES.include?(code.getbyte(index))

    index += 1
  end
  false
end

.normalize_mode!(mode) ⇒ Object

Raises:

  • (ArgumentError)


97
98
99
100
101
102
# File 'lib/pg_pipeline/session_guard.rb', line 97

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



55
56
57
# File 'lib/pg_pipeline/session_guard.rb', line 55

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

.unsafe_reason_normalized(sql, mode:) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
# File 'lib/pg_pipeline/session_guard.rb', line 59

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

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