Security Model

Read-only by design. Defense in depth. Every tool is non-destructive.

Architecture · Configuration · Tools Reference · FAQ


CautionThis gem is designed for development environments. The query tool, and MCP over HTTP from inside the app, are disabled in production by default. Sensitive files are blocked. All 35 tools are read-only.

Design principles

  1. Read-only by design - All 35 tools are annotated as non-destructive in the MCP protocol
  2. Defense in depth - Multiple security layers, not single points of failure
  3. Sensitive data blocking - Configurable patterns prevent access to secrets
  4. Offline except where named - No network calls except optional rails_search_docs with fetch: true, and the standalone binary's daily version check against rubygems.org (RAILS_AI_CONTEXT_NO_UPDATE_CHECK=1 turns it off)
  5. Graceful degradation - Missing optional dependencies don't expose errors or state

SQL query safety (4 layers)

The rails_query tool uses a 4-layer security model:

flowchart LR
    Q[SQL Query] --> L1{Layer 1\nSQL gate}
    L1 -->|"Blocked:\nINSERT, DROP,\nUNION SELECT..."| R1[Rejected]
    L1 -->|SELECT only| L2{Layer 2\nDatabase Read-Only}
    L2 -->|"SET TRANSACTION\nREAD ONLY\n+ timeout"| L3{Layer 3\nRow Limit}
    L3 -->|"Cap: 1000 rows\nDefault: 100"| L4{Layer 4\nSecret Columns}
    L4 -->|"names password_digest,\napi_key, ..."| R1
    L4 -->|"no secret column"| OK[Safe Result]

    style R1 fill:#e74c3c,stroke:#c0392b,color:#fff
    style OK fill:#27ae60,stroke:#1e8449,color:#fff
    style L1 fill:#e67e22,stroke:#d35400,color:#fff
    style L2 fill:#f39c12,stroke:#e67e22,color:#fff
    style L3 fill:#3498db,stroke:#2980b9,color:#fff
    style L4 fill:#9b59b6,stroke:#8e44ad,color:#fff

Layer 1 - The SQL gate: statement checks

Before any query reaches the database, the SQL gate (RailsAiContext::SqlGate) reads it once and answers either the text to run or a refusal with the reason. It holds every check in this layer and, on PostgreSQL, the plan checks of Layer 1b. Comments and quotes are read the way the connection's database family reads them:

Layer 1b - The SQL gate: PostgreSQL plan checks (planning only)

The textual layer cannot see a whole-row serialisation (SELECT row_to_json(u.*) FROM users u) or an admin function introduced through a view, because no secret column name appears in the query. On PostgreSQL, before the query runs, the tool plans it with EXPLAIN (VERBOSE, FORMAT JSON) inside the same read-only transaction - planning only, nothing executes, a VOLATILE function included (the planner does not fold one). The plan is refused when it:

Every statement except SHOW is planned, and an EXPLAIN is planned as the statement it explains. EXPLAIN (GENERIC_PLAN) is planned with that option too, read as the server reads it (its last value, quoted or not), so a statement with $1 in it is planned as PostgreSQL 16 and later plan it. A statement whose plan cannot be read does not run: when planning times out the answer is the timeout, when planning fails it is the SQL error, and when the server returns no plan the statement is refused.

A whole-row read of a relation with no secret column (row_to_json(posts.*)) is allowed. Before these checks scan a plan expression, its string constants are masked (PostgreSQL's deparser always doubles quotes and never emits an E'' string, so a constant is matched exactly), so a secret word inside a '%key%'::text filter or a literal argument is not mistaken for a column or a function.

A subquery or a join over a table that holds a secret column runs when it reads none of them. A scan under an aggregate, a join or a Result node hands up every column of its table, and the plan check counts a secret column only when that node names it. So SELECT (SELECT count(*) FROM users) AS n, count(id), max(id) and EXISTS (SELECT 1 FROM users) run, while max(api_token), count(api_token), string_agg(api_token, ','), row_to_json(users), a whole row and count(users) are refused.

Relations and settings that are never read

A statement that names one of these on the database family that has it is refused. The name is matched on the raw text, so it is refused inside a string literal too. Names are folded the way MySQL folds them before they are matched. The answer is "Blocked: <name> is not read. It holds values sampled from other tables, other sessions' statements or stored credentials, and rails_query cannot tell which of them are secret." For a relation or function that lists settings it ends " To read one setting, run SHOW with its name."

Database Never read What it holds
PostgreSQL pg_stats, pg_stats_ext, pg_stats_ext_exprs, pg_statistic, pg_statistic_ext, pg_statistic_ext_data, pg_largeobject values sampled or copied from tables
PostgreSQL pg_stat_activity and the functions it reads through (pg_stat_get_activity, pg_stat_get_backend_activity), pg_stat_statements, pg_prepared_statements, pg_cursors other sessions' and earlier statements
PostgreSQL pg_authid, pg_shadow, pg_db_role_setting password hashes, and the settings stored for a role or a database
PostgreSQL pg_user_mapping, pg_user_mappings, information_schema.user_mapping_options, pg_subscription, pg_foreign_server, pg_foreign_data_wrapper, pg_foreign_table connection options, which can carry a password
PostgreSQL pg_settings, pg_file_settings, pg_show_all_settings(), pg_show_all_file_settings(), pg_hba_file_rules, pg_ident_file_mappings every setting, and the authentication files
MySQL and MariaDB anything after mysql. or sys., performance_schema, global_priv accounts and their password hashes, other sessions' statements
MySQL and MariaDB processlist, general_log, slow_log, and in information_schema: INNODB_TRX, INNODB_LOCKS, INNODB_LOCK_WAITS, the INNODB_FT_ tables, USER_STATISTICS, CLIENT_STATISTICS, PROFILING, OPTIMIZER_TRACE other sessions' statements, locked rows, indexed words
MySQL and MariaDB column_statistics, column_stats values sampled from tables
SQLite sqlite_stat1, sqlite_stat3, sqlite_stat4 values sampled from indexes
SQLite sqlite_stmt the connection's own statements with their literals

Each name belongs to one database family and is refused there alone. A PostgreSQL catalog name is not refused on MySQL, MariaDB or SQLite, and a MySQL name is not refused on PostgreSQL or SQLite. On its own family a name is matched as a whole word, so an app table that carries one (slow_log on MySQL) cannot be queried. The information_schema names in the MySQL row are matched only under that schema, so an app's own user_statistics table runs.

The mysql and sys schemas are told by a name before a dot, on text with string literals masked, on MySQL and MariaDB alone. So 'mysql.com' inside a single-quoted string runs. An alias cannot be told from a schema without a parser, so an alias named sys or mysql before a dot is refused too. Every such refusal outside double-quoted text, a real FROM mysql.user included, ends " A name before a dot is read as that schema, so an alias named sys needs another name.", with mysql where that is the name. A double-quoted text that holds mysql. or sys. is refused too, and its answer ends " The name stands before a dot inside double-quoted text, which MySQL reads as a name when the session's sql_mode holds ANSI_QUOTES, and rails_query does not read the session's mode. Write the text in single quotes."

On PostgreSQL the plan is checked for the same names, as relations and as functions, so a view over one is refused: information_schema.user_mappings, information_schema.foreign_servers and pg_stat_subscription are refused that way. pg_authid, pg_shadow and pg_db_role_setting are the exception. A view over them runs, and their rolpassword and setconfig columns are secret columns: pg_roles, pg_user and information_schema.schemata run, SELECT rolconfig FROM pg_roles comes back [FILTERED], and an expression over either column is refused.

PostgreSQL settings are read one at a time, and the ones that can hold a secret are refused:

Stated limits:

Layer 2 - Database-level read-only

After validation, the query runs through its database family, which knows how its database spells a read-only transaction and a statement timeout:

Family Mechanism A timeout arrives as
PostgreSQL (and PostGIS) SET TRANSACTION READ ONLY + SET LOCAL statement_timeout ActiveRecord::QueryCanceled
MySQL (mysql2 and Trilogy) SET TRANSACTION READ ONLY + the session's max_execution_time, read first, set for the statement and put back afterwards, also when the statement fails ActiveRecord::StatementTimeout (3024), sometimes QueryCanceled (1317)
MariaDB SET TRANSACTION READ ONLY + the session's max_statement_time, read first, set for the statement and put back afterwards (MariaDB has no max_execution_time and ignores MySQL's hint) native code 1969
SQLite A read-only connection in a child process, killed at timeout the gem's own timeout

What bounds each statement a rails_query call sends:

Statement PostgreSQL MySQL and MariaDB SQLite
The query, and explain: true statement_timeout, a wait on a lock included the session's statement limit, and lock_wait_timeout for a wait on a lock the child process's deadline
The reads beside it: the schema read behind the secret column rule, and on PostgreSQL the plan, its pg_proc lookup and the column trace statement_timeout, a wait on a lock included the session's statement limit, and lock_wait_timeout for a wait on a lock no statement limit; a wait on another writer ends at the connection's busy timeout

The query has query_timeout to itself. The reads beside it share a second query_timeout, and each is charged the time it ran, so the statements of a call take about twice query_timeout at most. On PostgreSQL, MySQL and MariaDB the reads with no bound are of a setting's own value for the settings note, which wait on no lock. Building the app's context, which a cold call does first, is charged to neither, and so are the gate's checks on the statement's text, which the statement length limit bounds. The schema read is a few statements whatever the number of tables: four at most on MySQL and MariaDB, five on PostgreSQL and six on SQLite. On a SQLite file database where a query process can run, two more reads ask what the app's own connection alone holds, so eight reads come before the statement there. On PostgreSQL a plan that holds a foreign scan adds one catalog read. A statement or a view definition that names another schema or database adds the reads of that one.

A read that runs out of that time ends the call with an error that says which side of the statement it was on:

Stated limits of the time bound:

A database leased by name connects with the connect_timeout of its config/database.yml entry, or query_timeout rounded up to whole seconds when the entry sets none, so a server that never answers the connection ends the call. On MySQL and MariaDB such a connection also gets a read_timeout of twice query_timeout plus 5 seconds unless its entry sets one, so a server that goes silent after the handshake ends the call. On PostgreSQL connect_timeout is the only client bound. Taking the lease down does not replace the outcome of the call: its connections are thrown away and its pool removed, and an error there is not raised. The primary uses the app's own pool and its settings.

The MySQL session variable bounds a statement that starts with WITH or EXPLAIN ANALYZE too; the MAX_EXECUTION_TIME hint binds only the outermost SELECT, so it is not used. query_timeout is a positive number, and PostgreSQL, MySQL and MariaDB bound a value under a millisecond at one millisecond. A timeout is read from the error's class or the database's native code alone, so an SQL error whose message names a column called timeout is reported as an SQL error. On PostgreSQL a statement another session cancels (pg_cancel_backend) raises the timeout's class too, and the server's message alone tells them apart: a cancel, whose message ends "due to user request", is answered as the SQL error it is. A server that writes its messages in another language answers such a cancel as the timeout. A wait that PostgreSQL's own lock_timeout ended is answered as the timeout. A connection the server dropped is no timeout: on Rails 7.1 and later the answer is an error that starts "The <name> database stopped answering during the query:".

On MySQL and MariaDB the session that holds the read-only transaction and the time limit is the only one the statement is sent on. Rails replaces a connection it lost before the transaction begins, and the new session has neither guard. So the session's id is read inside the transaction, with one SELECT CONNECTION_ID(), and compared with the one the limits were set on. When they differ the answer is "The <name> database stopped answering during the query: the connection was replaced before the statement was sent, and the new session has no read-only transaction and no time limit, so the statement was not sent".

On PostgreSQL and MySQL the query executes inside a transaction, then rolls back (even if it could write, it can't). MySQL's read-only transaction still lets FOR SHARE, LOCK IN SHARE MODE and INTO through, so the Layer 1 checks stay on every family.

On a connection that is already inside a transaction (a tool called from a transactional test, a mounted server inside a request's transaction, a transaction the app opened with a raw BEGIN that Active Record does not count) the guard leaves that transaction open as it found it, with its writes. PostgreSQL guards inside a savepoint, chosen by the server's own transaction status, so the outer transaction stays writable. MySQL and MariaDB cannot make an open transaction read-only: the server refuses SET TRANSACTION READ ONLY inside one, and a BEGIN there would commit it, so no BEGIN is sent, the statement is not sent, and the answer is "Query failed: MySQL cannot make a transaction that is already open read-only, so the statement was not sent. Run it outside the transaction." SQLite runs the statement on the app's own connection, so it reads the rows of the open transaction. It runs under PRAGMA query_only = ON, and the pragma is put back as it was found.

A statement that reads a setting the guard sets for it answers the guard's value: statement_timeout and transaction_read_only on PostgreSQL, the statement limit (max_execution_time or max_statement_time) and lock_wait_timeout on MySQL and MariaDB. When the statement reads one of them (SHOW name, @@name, @@SESSION.name, @@LOCAL.name or current_setting('name'), the name backquoted or not), or a SHOW VARIABLES row or MariaDB's information_schema.SESSION_VARIABLES names one, the answer ends with a note that says so and gives the session's own value, for example "statement_timeout here is the value rails_query sets for each statement it runs. The session's own: statement_timeout 50s." A name used as an alias or a column, one in a string or a comment, and a global value on MySQL and MariaDB get no note. On SQLite a PRAGMA statement is no read, and the pragma_query_only function is refused by name.

An adapter with no family (SQL Server, Oracle, CockroachDB and any other) is refused: rails_query answers with the adapter's name and sends no statement, because it cannot give that database a read-only transaction and a timeout it has verified. The family is read from the database's configuration, so the refusal comes before any connection is opened or verified. CockroachDB's adapter is built on PostgreSQL's, but the adapter's name alone chooses the family, so it is refused too.

A SQLite database whose file is not there is refused by name before anything connects, with or without a database argument, since connecting would create the file. The answer names bin/rails db:prepare.

A SQLite statement runs on the app's own connection, under PRAGMA query_only = ON, in five cases: an in-memory database, a platform without fork, a statement the child process could not prepare, a transaction open on the app's connection, and a statement that names something the app's connection alone holds. The third is a statement that needs a table, function, virtual-table module, collation or encryption key only the app's own connection has. That case is told from which step failed in the child, and the error's text is not read. A statement the child prepared and that fails while it runs is answered with its SQL error and is not run again. The fourth is there because the child opens the file itself and would answer without the rows of the open transaction.

The fifth is told before the child starts, by two reads on the app's connection: its temp objects and its attached databases. When it holds any of them, a statement runs there if it names one of them, the temp catalog (sqlite_temp_master, sqlite_temp_schema) or the temp schema, or if it calls a pragma function (pragma_table_info(...), pragma_table_list and the rest) or dbstat, whose argument can name any of them. The child has none of these and would answer an empty list, the rows of a main table of the same name, or "unknown database". A table that only an attached database holds needs no match: the child cannot prepare a statement that reads it, which is the third case. A stated limit: a name is matched anywhere in the statement's text, in any letter case and inside a string too, so a statement that holds such a name as plain data runs on the app's connection as well.

On the app's own connection a statement that returns rows slowly ends with the timeout answer a few rows after query_timeout passes. The sqlite3 driver holds the interpreter lock while a statement steps, and an interrupt lands only between two rows, so the end comes late by the time those rows take. One long step cannot be ended there at all. So the table and EXPLAIN answers of such a run say it ran without a time limit: "This SQLite query ran without a time limit: query_timeout needs a file-backed database, a platform with fork, and nothing that only the app's own connection has." CSV output stays plain data.

A SQLite database that another connection keeps locked is answered as locked: "The database is locked by another connection, so the query did not run. Run it again when the other connection has finished." It is an error response. The child process waits on a lock for 80% of query_timeout, so a lock that stays is answered before the timeout. The child tells its parent the moment it meets a lock, so a child that started late on a slow machine and still waits at the deadline is answered as locked too. The child takes its read lock before it prepares the statement and tells its parent once it holds it. No writer can stop the statement from there on, so a statement that then runs past the deadline answers the timeout, also when a writer asks for the lock while it runs. A lock met while the connection opens gets the locked answer. The reads on the app's own connection wait for that connection's busy timeout.

On sqlite3 1.x a query does not run when another connection in the same process held an exclusive lock on a rollback-journal database as it started (BEGIN EXCLUSIVE): the child inherits that lock record and it never clears. A lock held by another process is waited on as usual, and an open write transaction or any lock in WAL mode does not block it.

Layer 3 - Row limit

Layer 4 - Secret column rejection

A query that names a secret column is rejected before execution, and a secret column's values are redacted where a SELECT * returns them. One rule (RailsAiContext::SecretColumns) decides what is secret, used by the pre-execution refusal, the PostgreSQL plan check and result redaction alike. A column is secret when it is:

minus anything in config.query_allowed_columns. An encrypts column is the exception: it is a secret column whatever that list holds. A query that names it is refused, the refusal says the allowed list does not release it, and its values stay [FILTERED].

Default redacted patterns: password_digest, encrypted_password, password_hash, reset_password_token, confirmation_token, unlock_token, otp_secret, session_data, secret_key, api_key, api_secret, access_token, refresh_token, jti. Those are the defaults of config.query_redacted_columns. The fixed built-in list adds password_reset_token, remember_token, secret, private_key, authentication_string, rolpassword and setconfig. The last three are where MySQL and PostgreSQL keep password hashes and stored settings.

The pre-execution refusal matches on two things, as whole identifiers. Names are folded the way the databases compare them. On SQLite that is ASCII letters alone, so "é" and "É" are two columns there and a refusal of one leaves the other. On PostgreSQL, MySQL and MariaDB every letter is folded to lowercase, with MySQL's reading of a dotted capital I as i, since a collation or a database encoding can fold more than ASCII there, and a false refusal is the safe side. What a name means is read with every letter folded on every family: a column whose name folds to a built-in name or to one the heuristic flags is a secret column, and so is one a configured name folds to when no column of the database spells that name as the database folds it.

The rule follows what a statement reaches. It starts from these columns, by database family:

Family The columns the rule reads
PostgreSQL Every relation on the search path that stores rows: tables, partitioned tables, materialized views, foreign tables and sequences. A sequence holds no secret column, so SELECT last_value FROM <sequence> runs. Then every schema the statement's text names, and every relation the statement's plan names, in any schema. The session's temporary tables are read like any table. The system schemas are left out: the never-read list and the catalog columns rolpassword and setconfig hold what is secret there
MySQL and MariaDB The base tables of the connection's database. Then those of every database the statement's text names. mysql, sys, performance_schema and information_schema are left out: their relations are refused by name or hold no app data
SQLite The tables of main, of temp and of every attached database

A schema or database is told by a name before a dot, and the server says which of those names are schemas. Each name is read backward from its dot, bare or in backticks or double quotes, so nothing written before the name changes how it is read, a quote character inside a string included. A name in brackets is not read: SQLite reads every schema whatever a statement names, and on MySQL and MariaDB Layer 1 refuses the bracket. A view the statement names can name a further schema or database in its definition, and a view named there a further one. The rule follows those views three reads deep. A view no statement names is not followed, so a statement that names no other schema or database and no such view costs no extra read. On PostgreSQL the plan reads through a plain view, so only a materialized view's definition is followed. A statement that names a view that leads deeper is not run: "The view <view> leads through more databases than rails_query follows, so the secret columns it could read cannot be told and no statement that names it runs." On PostgreSQL the sentence says "schemas". A schema whose columns cannot be read stops the statement too: "The columns of <name> could not be read, so the secret columns there cannot be told and no query that reads it runs." On PostgreSQL a relation the plan names and the rule could not read is refused by the plan check of Layer 1b. So a statement that names a secret column of a table in another schema or database is refused by name, as one in the connection's own is.

A refusal names a view, a table or a relation as the database spells it. The rule itself compares names case folded as above, with a run of spaces as one space. So two names that differ by a run of spaces alone are one name to the rule, and a refusal names the first of them it read.

The schema read fails closed. When the columns of the database cannot be read, no query runs on it and the answer is "The columns of the <name> database could not be read, so its secret columns cannot be told and no query runs on it." Only the primary falls back to the cached context's schema, and it is refused the same way when that has no tables either.

So SELECT password_digest AS pd FROM users, SELECT upper(api_token) FROM users and SELECT (SELECT api_token FROM users LIMIT 1) AS leaked are all refused: post-execution redaction reads the output column names, which the caller controls through aliases and expressions, so it cannot be relied on. The refusal starts "Blocked: query references secret column api_token." and says how to release a name that holds no secret. A table or alias that merely contains a secret word (a tokens table) does not trip the check - only a real column name does. SELECT * stays allowed, and its secret columns are redacted in the result.

A secret word inside a string literal - a LIKE '%secret%' pattern, a JSON key ->>'token' - is data. On PostgreSQL the check runs on literal-masked text, and the plan layer (Layer 1b) then has to vouch: a query that passed only because a name sat inside a literal runs only when its plan was obtained and cleared every check, so a masker fooled by a quote trick (standard_conforming_strings off, an E'' string) is not the only guard. A statement with no plan to read, such as SHOW, keeps the raw-text refusal. On MySQL, MariaDB and SQLite the match stays on raw text with no masking, because a quote's meaning there depends on server modes (NO_BACKSLASH_ESCAPES, ANSI_QUOTES) or a dotted single-quoted name is an identifier (t.'col').

If one of your own columns merely looks secret (an oauth_applications.secret, say), exempt it by name:

config.query_allowed_columns = %w[secret]

On a standalone install, where no initializer runs, put the name under query_allowed_columns: in .rails-ai-context.yml.

Results are redacted as well: a returned column comes back as [FILTERED] when the rule flags its output name, and on PostgreSQL when its origin is a secret base column - either by provenance (PG::Result#ftable / #ftablecol, mapped to the base column) or by the plan's top-node Output, whose i-th expression is result column i. The plan path catches a view (or inlined CTE/subquery/join) that renamed a secret column to a harmless name: CREATE VIEW user_tokens AS SELECT id, api_token AS t FROM users; SELECT t FROM user_tokens returns t as [FILTERED]. A quoted mixed-case secret column ("Salt") is filtered in place the same way. So is a secret column under a wildcard over a partitioned table or an inheritance parent: each partition is read as its own relation, a result column is filtered when any of them hands a secret column up in that place, and a whole-row read is refused when any of them holds one. An expression beside the wildcard (SELECT *, id + 1 AS next) changes nothing: each plain result column keeps its table column, and each partition's expressions are checked as expressions. The arms of a UNION ALL inside a view are read the same way: each arm against its own table, so no arm stands for another. A result column whose table's column names cannot be read is filtered when that table holds a secret column. When the table cannot be told either, it is filtered when any table holds one. On SQLite a second result column of the same name comes back as name:1, and the rule reads that name without its suffix. SHOW, DESCRIBE and EXPLAIN output skips column-name redaction; the one exception is SHOW CREATE TABLE / SHOW CREATE VIEW, whose definition text is run through the shared secret redaction so a credential embedded in it is filtered.

Some relations are refused whole, because no result column of them is traced to a table column. MySQL, MariaDB and SQLite trace none at all, so there two refusals stand in for the plan checks:

On PostgreSQL a plain view is traced through the plan and its secret columns are filtered in place. A materialized view stores its rows, so its result columns have no table column to be traced to, and it is held to the view rule above: a statement that reads one whose definition names a secret column, directly or through a view, is refused with the view answer. So is a statement that reads it through a view over it, since the plan names it. A materialized view is told by its schema and name, as the plan gives them, so a table of the same name in another schema runs.

On SQLite a table that holds another table's rows or words under other names is not read. The name is matched on the raw text, inside a string literal too:

dbstat runs: it gives sizes and no stored value.

Stated limits on MySQL, MariaDB and SQLite, where no plan is read: SELECT * FROM t INTERSECT SELECT <a guessed row> (and EXCEPT) tells whether a whole row equals the guess, and an ordinal ORDER BY 3 over a wildcard tells the order of a secret column's values. Neither returns a value: the secret columns of the rows that come back are [FILTERED]. PostgreSQL refuses both by the plan. On SQLite a string literal equal to the name of a relation that holds a secret column refuses a statement with a wildcard in a subquery, also when the string is plain data there: the rule cannot tell the two uses apart without a parser.

On every family a generated column whose expression reads a secret column is a secret column itself: a statement that names it is refused and its values come back [FILTERED]. SQLite stores no expression per column, so each one is cut from its table's definition. A generated column whose part of the definition cannot be found is read by the whole definition, and is then secret once anything in it names a secret column. A generated column is known by its name. When two tables each have one of the same name, that name is secret when either reads a secret column, and it is held as an encrypts column when either reads one. config.query_allowed_columns releases a generated column, or a column a view reads, by name, unless it reads an encrypts column.

A stored procedure or function is a stated limit: its body is not read, so a function that returns a secret column's value returns it, and the value is filtered by its output name only.

A column is known by the name it has in this database, which is a stated limit too. A foreign table that gives a secret column of the remote table another local name (the column_name option), a column a trigger fills from a secret column and a table built from another are read by their own names, so their values come back unless that name is secret itself. config.query_redacted_columns takes such a name.

The exemption covers the results too: an allowed name comes back unredacted. A column declared with encrypts is refused by name and stays [FILTERED] either way: an encrypted-at-rest attribute is not meant to be read back raw.

Environment guard

WarningDisabled in production by default. Only enable with config.allow_query_in_production = true if you understand the implications.

The refusal is an error response, isError over MCP and exit 1 from the CLI: "rails_query is disabled in production for data privacy. Set config.allow_query_in_production = true to override."


Sensitive file blocking

The rails_search_code and file-reading tools block access to sensitive files:

Default patterns

.env .env.* *.env .envrc
config/master.key
config/credentials.yml.enc config/credentials/*.yml.enc
config/database.yml config/secrets*.yml config/secrets*.yml.enc
config/application.yml
config/settings.local.yml config/settings/*.local.yml
config/cable.yml config/storage.yml
config/mongoid.yml config/redis.yml
*.pem *.key *.p8 *.p12 *.pfx *.jks *.keystore
**/id_rsa **/id_ed25519 **/id_ecdsa **/id_dsa
.ssh/* .aws/credentials .aws/config .netrc .pgpass .my.cnf
.npmrc .yarnrc .bundle/config

A placeholder whose name ends in .example, .sample, .template or .dist (.env.example) is committed to be read, so a basename glob such as .env.* does not block it. A pattern that names it exactly, with no glob characters, still does, and so does a path pattern (one with a /, such as .ssh/*), which covers everything under it.

A pattern reads the way a .gitignore line does. One with a / names its file below the root as well, so config/database.yml covers an engine's, a pack's and a test/dummy app's copy, and a leading / anchors it at the root. A trailing / names a folder and everything in it, and **/ stands for any number of folders, none included, so **/id_rsa covers an id_rsa at the root too. A file a link brings in from the app's repository is also asked by its name there, so a link to a pack's config/ folder cannot hide the config/ a pattern looks for. A path a caller names that is longer than 4096 bytes, which no file system holds, is answered as not found.

AI context file exclusions

Search also excludes generated AI context files to prevent circular references:

CLAUDE.md, .claude/, .mcp.json
.cursor/, .cursorrules
.github/copilot-instructions.md, .github/instructions/, .vscode/mcp.json, .github/mcp.json
AGENTS.md, opencode.json
.codex/
.ai-context.json

Configuration

config.sensitive_patterns = %w[.env* *.key *.pem credentials.yml.enc]

On the static tier (--no-boot, or a boot that failed) no initializer runs. The gem reads every Ruby file of the app that names it (RailsAiContext or rails_ai_context), however the boot loads it, without running it: a file under a config/ folder, and the top level and class bodies of any other file, which run as the file loads, whole; the body of a method outside config/, a tool's or a helper's that runs when called, for what it writes. Tests (a spec/ or test/ folder at any depth, an engine's test app among them), db/, tmp/, vendor/bundle/, vendor/ruby/, vendor/cache/, vendor/gems/, an installed copy of the gem, a folder holding rails-ai-context.gemspec that is not a link (a checkout of the gem's own source, the root included, though the app's own config/ folder is always read), a generator's templates, hidden files and links are left out, and config/initializers and config/environments are read through a link as Rails globs them. The literal values those files write to sensitive_patterns, excluded_paths and skip_tools are added to the YAML's, a list joined from literals (%w[a.yml] + %w[b.yml]) among them; a removal is left out. A booted app keeps the same union: the YAML's entries for those three lists and every value the code adds, whichever runs first. Reading a frozen constant of RailsAiContext::Configuration (PRESETS) changes no setting and is not refused. A value it cannot read, such as one built from a constant or the environment, the configuration handed to other code or reached through send, a pattern changed in place, or a file that does not parse, stops the static tier with an error that names the file and line; outside a method, so does a list or one of its patterns kept or handed on. A file outside the app, a list a method keeps and changes later, and code that reaches the settings through a name it builds at run time (const_get("Rails" + "AiContext")) are not followed. .rails-ai-context.yml is read on every tier.


Path traversal protection

All file-reading operations validate paths against Rails.root:

real_path = File.realpath(requested_path)
root = File.realpath(Rails.root.to_s)
raise unless real_path == root || real_path.start_with?(root + File::SEPARATOR)

A path may also resolve into a directory the app links in from its own git repository, as described under "Links in and out of the app" below. The VFS (rails-ai-context://views/{path}) applies the same protection for view template reads.

A symlink inside the app is followed when it leads into the app root, or into the engine its test/dummy runs in, and a directory link is also followed when it leads anywhere inside the git work tree that holds the app. A monorepo's shared package linked into packs/ or app/javascript/controllers is read as the app's own, under the path the app gives it (packs/billing/app/models/invoice.rb). A file reached through such a directory is read only when its real path stays inside the app or inside that directory. Outside a git repository nothing marks where the project ends, so only links that stay inside the app root are followed. A link to anywhere else, a home directory included, is not followed: the file is neither listed nor read. A link that resolves nowhere is not listed either.

The walks over app code follow a linked-in directory where Rails does: the trees Zeitwerk autoloads (models, controllers, jobs, mailers, channels, helpers, components, concerns, policies and the rest of app/, packs and in-repo engines included), the view resolver's templates and layouts, and the JavaScript roots a bundler reads. A file Rails finds with a glob of its own is found the way that glob finds it, entering no linked directory below where it starts: initializers, locale and environment files, migrations, seeds, rake tasks, test files and mailer previews. Among those, a linked file is read only when it stays inside the app.

A tool handed a path that leads out of the app refuses it, and so does a tool that resolves a name to one file - a log, a partial, a concern - when that file leads out; see "How a refusal is reported" below. A tool that answers from what the walks found, such as rails_get_stimulus, never lists a file a link carries out, and asked for that controller by name answers that it is not there. A path into a linked-in directory is accepted wherever a path is (packs/billing/app/models/invoice.rb), and the sensitive patterns are matched against the file's name inside that directory as well as the app's. rails_search_code searches the linked-in directories too.

Booted, a class Rails loaded through a link out of the app is still described from what reflection answers, such as a job's queue name; only its file goes unread. rails_security_scan hands the app to Brakeman, which reads it by its own rules.

Frontend roots outside the app

Two directories outside Rails.root are read, for frontend manifests only: each frontend_paths entry you configure (../web-client), and the JS workspace root above the app (the nearest ancestor holding a lockfile or declaring workspaces, never above the git root and never outside a git repository). Only package.json, lockfiles and the presence of a bundler config (vite.config.* and similar) are read there, plus a configured entry's tsconfig.json and the configs it extends inside that same directory. Sensitive patterns and symlink containment apply relative to that directory, and the frontend section of rails_get_config names it in its answer.

The bundle config/boot.rb declares

An app with no lockfile of its own (an engine's test/dummy) has its gems in the Gemfile its config/boot.rb sets as BUNDLE_GEMFILE (../../Gemfile). That Gemfile and its lockfile (gems.rb and gems.locked alike) are read with the same trust as the app's own Gemfile.lock, only when their directory is inside the app's git repository, never above its root and never outside a repository. Besides those two, only a file that Gemfile names with eval_gemfile inside that directory, and the lib/ of a path gem the lockfile names inside the repository (the engine's own remote: .), are read. A file there that links out of the directory is refused.

The engine an app's test/dummy runs in

Booted from an engine's test/dummy, the engine whose root holds the app root (a loaded Rails::Engine, never this gem) is the project's own source: its app/ code, its app/views layouts and templates, and, when the dummy keeps no test/ or spec/ of its own, its test suite are read. Paths into it are printed relative to the app root (../../app/models/...), and symlink containment applies relative to the engine root. Without booting, only the test suite is read this way, and only from the directory of the bundle config/boot.rb declares (read under the rule above) when it holds a *.gemspec and contains the app root.

How a refusal is reported

A path refused on policy - outside the app, a traversal, a sensitive file - comes back as an error result: isError: true over MCP, exit 1 from the CLI, and the text starts with Path not allowed: <path>, followed by (sensitive file) when the name is the reason. A path that is simply not there is an ordinary answer and exits 0, so a script can tell the two apart. rails_validate, which answers for several files at once, says Path not allowed on the refused file's own line; a file it cannot validate, refused or missing, fails the validation, so that answer is an error result either way.

The same holds for a name a tool turns into a file: a log (rails_read_logs file:), a partial (rails_get_partial_interface partial:) or a concern (rails_get_concern name:) whose file links out of the app is refused, not reported missing. A list of what a tool can read, such as the available logs or partials, leaves out every entry it would refuse. rails_diagnose still diagnoses the error it is given when the file: it is pointed at is refused, says so, and returns the whole answer as an error result.


Command injection prevention

Search tools use array-based command execution (never shell strings):

# Safe: array form
Open3.capture3("rg", "--no-heading", "--", pattern, directory)

# Pattern injection prevented by -- separator

File type parameters accept only alphanumeric characters.

An argument git would read as an option never reaches it: rails_review_changes resolves its ref to a commit first (git rev-parse --verify <ref>^{commit}) and hands git that commit's SHA. A ref that starts with a dash is refused, so --output=<path> cannot make git diff write a file.


Regex injection prevention

On Ruby 3.2 and newer, user-supplied regex patterns have a 1-second timeout (2 seconds in the Ruby search fallback):

Regexp.new(pattern, timeout: 1)

Complex patterns that would cause catastrophic backtracking raise RegexpError instead of hanging.

WarningRegexp.timeout does not exist on Ruby 3.1, which this gem still supports. There the timeout is skipped, and a pattern crafted to backtrack catastrophically can hang the process serving the tool. If you expose rails_search_code to input you do not control, run it on Ruby 3.2 or newer.


Safe file reading

SafeFile.read provides drop-in safety for all file reads:


Redaction

Everything that leaves your app through this gem - log lines, query rows, environment values, config source slices - passes through one redaction module before anything else can touch it. Redacting and shortening are a single operation there, so a long credential cannot be cut apart in a way that hides it from the pattern that would have caught it.

What gets redacted:

Markers

Redacted values carry one of two markers, and only these two:

Marker Means
[FILTERED] A value was removed because it is or may be a secret
[EMAIL] An email address was removed

Marker presence and this vocabulary are part of the output contract (see below) - you can pattern-match on them.


Output contract

Contract, safe to depend on:

Incidental, expected to change between releases:

Pin your assertions to the first list. When something in the second list changes in a way that could break a pinned assertion, the CHANGELOG says so.


Migration safety

The rails_migration_advisor tool validates input:


MCP HTTP transport

No HTTP entry point authenticates a client: every tool answers whoever reaches the endpoint.

Inside the app - the mounted engine and auto_mount - the endpoint is on your app's own web server, so it is as reachable as the app is. In every environment but development and test - production, and a staging app the network reaches the same way - both refuse every request with a 403 and a JSON-RPC error that says how to opt in, and log the refusal once. config.allow_http_in_production = true lets them answer there. Set it only with the endpoint behind your app's authentication, such as a routes constraint around the mount. auto_mount answers before routing, so nothing in the app can guard it, and doctor's "MCP HTTP endpoint" check fails that pair. With the option on and the engine, it warns.

Both answer the hosts the app's config.hosts allows, judged by Rails' own HostAuthorization with its host_authorization exclusions, as every other route of the app is: myapp.localhost and any IP address in development, the app's own names in production, every host when config.hosts is empty. A host it does not allow, such as a DNS rebinding attacker's domain, gets 403 "Forbidden: Invalid Host header", and a browser's request from another origin gets 403 "Forbidden: Invalid Origin header". The MCP SDK's own check, which answers only 127.0.0.1, ::1 and localhost, is off for these two.

The standalone server - rails-ai-context serve --transport http and rails ai:serve_http - is its own process and binds 127.0.0.1 by default. http_bind can open it to the network, still with no authentication. The server answers only requests whose Host header is 127.0.0.1, ::1 or localhost, which stops a DNS rebinding attack from a browser but not a client that sends Host: localhost itself; a client that addresses the machine by IP or name gets 403 "Invalid Host header". So a non-loopback bind suits a container whose port is published to the host, where the client still connects to localhost. The server says so on stderr when it starts.

auto_mount is false by default, and the engine exists only where you mount it. Mount it guarded, if defined?(RailsAiContext::Engine), so the routes file still loads where the gem is not installed.

The engine builds one transport per process, under a mutex, outside the controller class, and the app's code reloader never replaces that class, so a session lasts across edits in development.


Credential handling


Reporting vulnerabilities

Email crisjosephnahine@gmail.com. Response within 48 hours.

Supported versions: only the latest 5.x release gets security fixes. See the repo root SECURITY.md for the full policy.


← Introspectors · CLI Reference →

Back to Home