Class: Assistant::SqlBroker

Inherits:
Object
  • Object
show all
Defined in:
app/services/assistant/sql_broker.rb

Overview

Single execution broker for read-only analytics SQL. Enforces:

  • Role-based object access
  • Sensitive object blocking
  • Sensitive column redaction
  • Statement timeout + row caps
  • Audit logging

Constant Summary collapse

READ_ONLY_PREFIXES =

Read only prefixes.

%w[SELECT SHOW WITH EXPLAIN SET].freeze
DEFAULT_STATEMENT_TIMEOUT_MS =

Default statement timeout ms.

8_000

Instance Method Summary collapse

Constructor Details

#initialize(connection_class_name:, service_key:, role:, tool_name:, allowed_objects: nil, audit_context: {}) ⇒ SqlBroker

Returns a new instance of SqlBroker.

Parameters:

  • allowed_objects (Set, nil) (defaults to: nil)

    Domain-resolved set of allowed view/table names.
    nil = unrestricted (admin). Falls back to DataPolicy.allowed_objects(role) if not provided.

  • connection_class_name (Object)
  • service_key (Object)
  • role (Object)
  • tool_name (Object)
  • audit_context (Hash{Symbol => Object}) (defaults to: {})


25
26
27
28
29
30
31
32
33
# File 'app/services/assistant/sql_broker.rb', line 25

def initialize(connection_class_name:, service_key:, role:, tool_name:, allowed_objects: nil, audit_context: {})
  require 'pg_query'
  @connection_class_name = connection_class_name
  @service_key = service_key
  @role = Assistant::DataPolicy.normalize_role(role)
  @allowed_objects = allowed_objects
  @tool_name = tool_name
  @audit_context = audit_context || {}
end

Instance Method Details

#execute(sql:, max_rows:) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'app/services/assistant/sql_broker.rb', line 35

def execute(sql:, max_rows:)
  started_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  normalized_sql = normalize_sql(sql)
  first_word = normalized_sql.split(/\s+/).first&.upcase

  return blocked!("Only read-only queries allowed. Statement starts with: #{first_word}", normalized_sql, started_at) unless READ_ONLY_PREFIXES.include?(first_word)

  objects = extract_objects(normalized_sql)
  disallowed = objects.reject { |obj| Assistant::DataPolicy.object_allowed?(role: @role, object_name: obj, allowed_objects: @allowed_objects) }
  return blocked!("Access denied. Restricted objects: #{disallowed.join(', ')}", normalized_sql, started_at, objects: objects) if disallowed.any?

  rows = run_read_only(normalized_sql)
  redacted_columns = sensitive_columns(rows, objects, normalized_sql)
  rows = redact_rows(rows, redacted_columns) if redacted_columns.any?

  truncated = rows.size > max_rows
  col_hints = build_column_hint_map(rows, objects)
  response = {
    row_count: rows.size,
    rows: rows.first(max_rows),
    truncated: truncated,
    note: truncated ? "Showing #{max_rows} of #{rows.size} rows. Add LIMIT for better results." : nil,
    redacted_columns: redacted_columns.presence,
    column_hints: col_hints.presence
  }.compact

  audit!(
    sql: normalized_sql,
    status: 'success',
    duration_ms: elapsed_ms(started_at),
    referenced_objects: objects,
    returned_row_count: response[:rows].size,
    returned_column_count: response[:rows].first&.keys&.size.to_i
  )
  response
rescue PgQuery::ParseError => e
  errored!("Invalid SQL syntax: #{e.message}", normalized_sql, started_at)
rescue ActiveRecord::StatementInvalid => e
  errored!(e.message, normalized_sql, started_at, objects: objects_for_error(normalized_sql))
end