diff --git a/README.md b/README.md index 00539ef..b7407a0 100644 --- a/README.md +++ b/README.md @@ -235,13 +235,83 @@ select_only=true ``` Needs `az login` beforehand, and the signed-in identity mapped as a database -user: `CREATE USER [you@company.com] FROM EXTERNAL PROVIDER;`. Encryption and -certificate verification are forced on for this mode, because an access token is -a bearer credential and an unverified connection hands it to whoever answers. +user. Map a dedicated reader identity, or a group, with `db_datareader` only: + +```sql +CREATE USER [argos-readers] FROM EXTERNAL PROVIDER; +ALTER ROLE db_datareader ADD MEMBER [argos-readers]; +``` + +Do not let Argos sign in as the server's Entra admin: the admin is a member of +`db_owner` in every user database and enters each one as `dbo`, so the only thing +between the agent and a `DELETE` is Argos's filter. Argos checks this on connect +and warns (see the [database role check](docs/guides/security-guide.md#database-role-check)). +Encryption and certificate verification are forced on for this mode, because an +access token is a bearer credential and an unverified connection hands it to +whoever answers. + +#### A separate Azure identity for the agent + +The Azure CLI keeps its sign-in in a profile directory, `~/.azure` unless +`AZURE_CONFIG_DIR` says otherwise. Sign the reader identity in to a profile of +its own, and start Argos with that variable, so the agent never uses your own, +possibly admin, login: + +```bash +export AZURE_CONFIG_DIR="$HOME/.azure-claude-ro" +az login # as the reader identity +claude mcp add argos --scope user -e AZURE_CONFIG_DIR="$HOME/.azure-claude-ro" -- \ + node "$(pwd)/dist/cli.js" serve --config "$HOME/.config/argos/config.ini" +``` + +Your own shell keeps `~/.azure` and your own login. To give one database its own +profile instead of the whole server, set `azure_config_dir` on it: + +```ini +[database.azure_sql] +type=mssql +host=your-server.database.windows.net +database=your_database_name +authentication=azure-cli +azure_config_dir=~/.azure-claude-ro +``` + +Then check who Argos is from inside a session, with `sql_query`: + +```sql +SELECT USER_NAME() AS db_user, IS_ROLEMEMBER('db_owner') AS is_owner, + IS_ROLEMEMBER('db_datawriter') AS is_writer; +``` + +`db_user` should be the reader, and both flags `0`. `sql_test_connection` runs +the same check and says so. See the [SQL Server guide](docs/databases/sql-server.md#azure-cli-authentication) for the details, including unattended use. +### Azure Database for PostgreSQL without a password + +The same Azure CLI sign-in works for Azure Database for PostgreSQL. The Entra +access token is the password, fetched fresh for every new connection because it +is valid for 5 to 60 minutes. + +```ini +[database.azure_pg] +type=postgresql +host=your-server.postgres.database.azure.com +port=5432 +database=your_database_name +username=argos-readers +authentication=azure-cli +select_only=true +# azure_tenant_id=00000000-0000-0000-0000-000000000000 +``` + +`username` is the Entra user or group as mapped in the database with +`pgaadauth_create_principal`. TLS with certificate verification is forced, for +the same reason as for Azure SQL. See the +[PostgreSQL guide](docs/databases/postgresql.md#azure-database-for-postgresql-with-azure-cli-authentication). + ### Multi-Database Analytics Setup ```ini [database.transactions] @@ -276,7 +346,11 @@ query_timeout=30000 1. **Query validation**: SQL injection prevention and syntax analysis 2. **Complexity limits**: resource-intensive queries are refused -3. **SELECT-only mode**: read-only database access for production safety +3. **SELECT-only mode**: Argos refuses anything but a read. The filter is a second net: the + database role is the boundary, so for a `select_only` database Argos asks the database + once per connection whether its role can write, and warns in `sql_test_connection`, + `sql_list_databases` and the pane when it can. Set `require_readonly_role=true` to refuse + such a connection instead 4. **Read-only pane**: what you run from the pane opens read-only at the database (SQLite read-only mode, a read-only PostgreSQL or MySQL session) behind the SELECT-only check; SQL Server has no session-level equivalent and relies on the check. The diff --git a/config.ini.template b/config.ini.template index c102746..7448282 100644 --- a/config.ini.template +++ b/config.ini.template @@ -13,6 +13,8 @@ select_only=true timeout=30000 # Check column names against the cached schema before running a query (default: true) # name_check=true +# Refuse to connect when the database role can write (default: false, which only warns) +# require_readonly_role=false # Field Redaction Configuration (optional) # redaction_enabled=true diff --git a/docs/api/mcp-tools-reference.md b/docs/api/mcp-tools-reference.md index 06d3e72..85847fd 100644 --- a/docs/api/mcp-tools-reference.md +++ b/docs/api/mcp-tools-reference.md @@ -280,9 +280,17 @@ Test connectivity to a database, establish SSH tunnels if needed, and capture sc Connection successful to production SSH tunnel established SELECT-only mode active + Database role: read-only (analytics_reader) Schema captured: 45 tables, 1,247 columns ``` +**A SELECT-only connection whose role can write:** +``` + Connection successful to azure_sql + SELECT-only mode active + Warning: select_only is on, but this connection can write as dbo (db_owner). Argos's filter is the only guard. Connect as a read-only role. +``` + **Failed Connection:** ``` Connection failed to production: Connection timeout after 30000ms diff --git a/docs/claude-code/pane.md b/docs/claude-code/pane.md index 8512cb4..6106b6e 100644 --- a/docs/claude-code/pane.md +++ b/docs/claude-code/pane.md @@ -123,8 +123,15 @@ footer says `tab: leave field`, and Tab moves out so the hotkeys work again. ![The Connections tab: counts across the top and a card each for shop (SQLite, full access) and analytics (PostgreSQL, select-only)](../images/claude-code/connections.png) One card per database from `config.ini`: type, host, whether it uses an SSH -tunnel or SSL, whether it is SELECT-only, and how old its captured schema is. -Passwords are never shown. +tunnel or SSL, whether it is SELECT-only, what its database role may do, and how +old its captured schema is. Passwords are never shown. + +The `role` line comes from the MCP server, which checks a SELECT-only +connection's role each time it connects. `read-only` is what you want. `can +write: db_owner as dbo` (in the warning colour) means the role could change data +and Argos's SQL filter is the only thing in the way: connect as a read-only +role. `not checked yet` means the server has not connected to it since the +check shipped. The single-key shortcuts are for the lists. While you type in the Schema filter or the Editor field, the letters go into the field. diff --git a/docs/databases/postgresql.md b/docs/databases/postgresql.md index 823a913..3978146 100644 --- a/docs/databases/postgresql.md +++ b/docs/databases/postgresql.md @@ -113,6 +113,43 @@ ssl=true select_only=true ``` +### Azure Database for PostgreSQL with Azure CLI authentication + +The Azure CLI's sign-in is the credential: Argos asks it for a Microsoft Entra +access token and sends that as the password, so no secret is written to +`config.ini`. + +```ini +[database.azure_pg] +type=postgresql +host=myserver.postgres.database.azure.com +port=5432 +database=myapp +username=argos-readers +authentication=azure-cli +select_only=true +# Only when the server's tenant is not the CLI's active context. Must be the GUID. +# azure_tenant_id=00000000-0000-0000-0000-000000000000 +``` + +- `username` is the Entra principal's name as the database knows it: a user's + sign-in name, or a group's display name, as mapped with + `SELECT * FROM pgaadauth_create_principal('argos-readers', false, false);`. + Grant that role read access only. +- A token is valid for 5 to 60 minutes, so Argos fetches a fresh one for every + new connection the pool opens rather than holding one that expires. +- TLS with certificate verification is forced. `ssl=false` is a startup error, + and `ssl_verify=false` does not reach this path: an access token on an + unverified connection goes to whoever answers. Through an SSH tunnel the + certificate is checked against `host`, not the tunnel's local address, so a + private endpoint behind a bastion still verifies. +- `az login` must have been run. A token failure says so, rather than surfacing + as an opaque login error. +- `azure_config_dir=~/.azure-claude-ro` takes the token from that Azure CLI + profile instead of the server's, so the agent can use a reader identity signed + in with `AZURE_CONFIG_DIR=~/.azure-claude-ro az login` while your own shell + keeps your login. + ### Cloud Database (Google Cloud SQL) ```ini [database.gcp_sql] diff --git a/docs/databases/sql-server.md b/docs/databases/sql-server.md index 8b0df65..3b4f4ed 100644 --- a/docs/databases/sql-server.md +++ b/docs/databases/sql-server.md @@ -141,8 +141,34 @@ Requirements: - The [Azure CLI](https://learn.microsoft.com/cli/azure/install-azure-cli) is installed and on `PATH`. - `az login` has been run, and the signed-in identity has access to the database. -- The Azure AD identity is mapped to a database user, for example: - `CREATE USER [you@company.com] FROM EXTERNAL PROVIDER;` +- The Entra identity is mapped to a database user. Use a dedicated reader + identity or group with `db_datareader` only: + `CREATE USER [argos-readers] FROM EXTERNAL PROVIDER;` then + `ALTER ROLE db_datareader ADD MEMBER [argos-readers];` +- Not the server's Entra admin: the admin is a member of `db_owner` in every + user database and enters each one as `dbo`. Argos warns when a `select_only` + connection can write; see the + [database role check](../guides/security-guide.md#database-role-check). + +### A separate Azure CLI profile + +`az` keeps its sign-in in `~/.azure`, or in `AZURE_CONFIG_DIR` when that is set. +Start Argos with `AZURE_CONFIG_DIR` pointing at a profile where only the reader +identity is signed in (`AZURE_CONFIG_DIR=~/.azure-claude-ro az login`), or set +`azure_config_dir` on one database to give just that database its own profile: + +```ini +[database.azure_cli] +type=mssql +host=myserver.database.windows.net +database=mydatabase +authentication=azure-cli +azure_config_dir=~/.azure-claude-ro +``` + +With `azure_config_dir` Argos runs `az account get-access-token` itself with that +profile, so two databases in one config can use two identities. The path must be +absolute; a leading `~` is your home directory. ### Choosing the tenant diff --git a/docs/guides/configuration-guide.md b/docs/guides/configuration-guide.md index c201e9c..453b0d5 100644 --- a/docs/guides/configuration-guide.md +++ b/docs/guides/configuration-guide.md @@ -115,6 +115,7 @@ value Argos cannot read is reported instead of guessed. | `ssl` | `false` | Enable SSL/TLS | `true` | | `timeout` | `30000` | Connection timeout (ms) | `15000` | | `mcp_configurable` | `false` | Allow MCP tools to modify this database config | `true` | +| `require_readonly_role` | `false` | Refuse a `select_only` connection whose database role can write, or whose privileges could not be checked. Off, the check only warns; see [Database role check](security-guide.md#database-role-check) | `true` | | `name_check` | `true` | Check column names against the cached schema before a SELECT runs; see [Name Checking](../api/mcp-tools-reference.md#name-checking) | `false` | #### SQLite-Specific Parameters @@ -128,11 +129,17 @@ value Argos cannot read is reported instead of guessed. | `encrypt` | `true` | Enable connection encryption | `false` | | `authentication` | `sql` | Authentication mode: `sql` or `azure-cli` | `azure-cli` | | `azure_tenant_id` | *CLI's active tenant* | Tenant to take the Azure CLI token from (GUID) | `00000000-0000-0000-0000-000000000000` | +| `azure_config_dir` | *the server's profile* | Azure CLI profile directory (as `AZURE_CONFIG_DIR`) this database takes its token from, so it can use its own reader identity | `~/.azure-claude-ro` | With `authentication=azure-cli` the connection uses the identity already signed in to the Azure CLI, so `username` and `password` are neither required nor read. See the [SQL Server guide](../databases/sql-server.md#azure-cli-authentication). +PostgreSQL takes `authentication=azure-cli` and `azure_tenant_id` too, for Azure +Database for PostgreSQL. There `username` is still required: it is the Entra +principal's name. See the +[PostgreSQL guide](../databases/postgresql.md#azure-database-for-postgresql-with-azure-cli-authentication). + ### Default Port Numbers - **PostgreSQL**: 5432 - **MySQL**: 3306 diff --git a/docs/guides/security-guide.md b/docs/guides/security-guide.md index e6db5b6..574a1c3 100644 --- a/docs/guides/security-guide.md +++ b/docs/guides/security-guide.md @@ -36,9 +36,13 @@ reaches the driver: - **No dangerous construct appears** — `INTO OUTFILE`, `INTO DUMPFILE`, `COPY … PROGRAM`, `WAITFOR DELAY`, and function calls such as `LOAD_FILE`, `SYSTEM`, `SHELL`, `EXEC`, `BENCHMARK`, `SLEEP`, `pg_read_file`, `pg_ls_dir`, - `lo_import`, `lo_export`, `pg_sleep` and `dblink`. These are matched as - function calls with a word boundary, so an ordinary column named - `description` is not mistaken for `SCRIPT`. + `pg_sleep`, every `dblink*`, `lo_*` and `pg_file_*` function, and the + PostgreSQL functions that change state from inside a SELECT: `set_config`, + `pg_terminate_backend`, `pg_cancel_backend`, `pg_reload_conf`, `nextval` and + `setval`. These are matched as function calls with a word boundary, so an + ordinary column named `description` is not mistaken for `SCRIPT`. +- **No invisible formatting characters.** A zero-width space inside a keyword + hides the keyword from the scan, so none are accepted. - **It is within the complexity limits** from `[security]`: joins, subqueries, unions, group-bys, overall score and raw length. @@ -50,6 +54,13 @@ complexity checks. It only stops restricting the leading command. ### The limits of it +The published bypass families (stacked statements, comments as whitespace, +`SET`, data-modifying CTEs, `SELECT ... INTO`, `COPY ... TO PROGRAM`, side-effect +functions, case and Unicode tricks) are pinned as a regression suite in +`tests/unit/security-bypass-regression.test.ts`. What no keyword list can see is +the inside of a function: a SELECT that calls a user-defined or extension +function that writes passes the filter. + This is defence in depth, not a substitute for database permissions. **Give the account only the rights it needs.** If the account cannot write, no parser bug can make it write: @@ -69,6 +80,44 @@ CREATE USER 'argos_ro'@'%' IDENTIFIED BY '…'; GRANT SELECT ON app.* TO 'argos_ro'@'%'; ``` +### Database role check + +Argos checks that boundary for you. Each time it connects to a `select_only` +database it asks the database, with read-only queries, what the role may do: + +| Engine | What it reads | Counts as "can write" | +|--------|---------------|-----------------------| +| SQL Server | `USER_NAME()`, `IS_ROLEMEMBER` for `db_owner`, `db_datawriter`, `db_ddladmin`, `IS_SRVROLEMEMBER('sysadmin')` (NULL on Azure SQL Database), `HAS_PERMS_BY_NAME` on the database and every visible table | any of those roles, entering as `dbo`, or INSERT/UPDATE/DELETE/CREATE TABLE granted directly | +| PostgreSQL | `rolsuper`, membership of `pg_execute_server_program`, `pg_read_server_files`, `pg_write_server_files`, `pg_write_all_data`, `has_table_privilege` on every visible table, `has_schema_privilege(..., 'CREATE')`, `default_transaction_read_only` | superuser, any of those roles, INSERT/UPDATE/DELETE/TRUNCATE on a table, or CREATE in a schema | +| MySQL | `SHOW GRANTS FOR CURRENT_USER()` | anything beyond `SELECT`, `SHOW VIEW` and `USAGE`; `FILE` is named on its own | +| SQLite | the mode Argos opened the file in | a file opened read-write | + +When the role can write, `sql_test_connection`, `sql_list_databases` and the +pane say so: + +``` +Warning: select_only is on, but this connection can write as dbo (db_owner). +Argos's filter is the only guard. Connect as a read-only role. +``` + +It is a warning, not a block. Set `require_readonly_role=true` on the database to +refuse the connection instead; with it on, a check that could not run also +refuses, because "unknown" is not "read-only". + +Two results surprise people: + +- **Azure SQL with `authentication=azure-cli`, signed in as the server's Entra + admin.** The admin is a member of `db_owner` in every user database and enters + each one as `dbo`. Sign in as a dedicated reader identity instead; see the + [SQL Server guide](../databases/sql-server.md#azure-cli-authentication). +- **PostgreSQL 14 and older.** Every role may create tables in `public` unless + that was revoked, so the check reports `CREATE in schema public`. Fix it with + `REVOKE CREATE ON SCHEMA public FROM PUBLIC;`. + +MySQL roles granted to the user are listed in `SHOW GRANTS` by name only. The +check does not expand them, so a granted role counts as "can write": unknown is +not read-only. Grant `SELECT` to the user directly to get a clean result. + ## Parameters Pass values through `params` rather than building them into the SQL. Each diff --git a/plugin/hooks/lib/layout.spec.ts b/plugin/hooks/lib/layout.spec.ts index fe95328..71b5e0f 100644 --- a/plugin/hooks/lib/layout.spec.ts +++ b/plugin/hooks/lib/layout.spec.ts @@ -41,6 +41,23 @@ describe('the Connections tab', () => { expect(text.match(/access\s+select-only/g)).toHaveLength(1) }) + it("says what a select-only connection's database role may do, and warns when it can write", () => { + const only = (c: ConnectionView) => model({ connections: { ask: 1, phase: 'done', answer: [c], failure: null } }) + const rows = (c: ConnectionView) => paneRows(only(c), 100, 40) + const segment = (c: ConnectionView, text: RegExp) => rows(c).flatMap(r => r.segments).find(s => text.test(s.text)) + // The fixture: the server found the SQLite file opened read-only. + expect(all(rows(CONNECTIONS[0]!))).toMatch(/role\s+read-only/) + const writer: ConnectionView = { ...CONNECTIONS[0]!, type: 'mssql', role: { checkedAt: 't', canWrite: true, principal: 'dbo', reasons: ['db_owner'] } } + expect(all(rows(writer))).toMatch(/role\s+can write: db_owner as dbo/) + expect(segment(writer, /^can write/)?.color).toBe('warning') + expect(all(rows({ ...writer, role: { ...writer.role!, canWrite: null } }))).toMatch(/role\s+could not be checked/) + expect(all(rows({ ...writer, role: null }))).toMatch(/role\s+not checked yet/) + // From a CLI older than the check. + const { role: _role, ...older } = writer + expect(all(rows(older))).toMatch(/role\s+not checked yet/) + expect(all(rows(CONNECTIONS[1]!))).toMatch(/role\s+not checked \(full access\)/) + }) + it('says the engine, the host, the tunnel, MCP configuration and when the schema was captured', () => { const captured = { ...CONNECTIONS[0]!, type: 'postgresql', host: 'db.internal', ssh: true, ssl: true, mcpConfigurable: true, schemaCapturedAt: '2000-01-01T00:00:00.000Z' } const text = all(paneRows(model({ connections: { ask: 1, phase: 'done', answer: [captured], failure: null } }), 100, 40)) diff --git a/plugin/hooks/lib/layout.ts b/plugin/hooks/lib/layout.ts index a649a56..68e2def 100644 --- a/plugin/hooks/lib/layout.ts +++ b/plugin/hooks/lib/layout.ts @@ -126,10 +126,25 @@ function capturedOf(at: string | null, now: number): Segment[] { return Number.isNaN(t) ? [{ text: 'never captured', dim: true }] : [{ text: `captured ${formatAge(now - t)} ago` }] } +/** + * What the database role of a select_only connection may do, as the MCP server + * last found it. A role that can write is the warning: Argos's filter is then + * the only guard. + */ +function roleOf(c: ConnectionView): Segment[] { + if (!c.selectOnly) return [{ text: 'not checked (full access)', dim: true }] + const role = c.role ?? null + if (role === null) return [{ text: 'not checked yet', dim: true }] + if (role.canWrite === null) return [{ text: 'could not be checked', dim: true }] + const who: Segment[] = role.principal === null ? [] : [{ text: ` as ${role.principal}`, dim: true }] + if (!role.canWrite) return [{ text: 'read-only', color: STATUS_COLOURS.ok }, ...who] + return [{ text: `can write: ${role.reasons.join(', ')}`, color: STATUS_COLOURS.warn }, ...who] +} + /** * One connection as a card: its name in the title, then its engine (a chip in - * its colour), host, tunnel, access, whether MCP may change its config, and - * when its schema was captured. The marked card is tinted, its first line + * its colour), host, tunnel, access, what its database role may do, whether + * MCP may change its config, and when its schema was captured. The marked card is tinted, its first line * carrying the marker and the press that marks it. */ function connectionBlock(c: ConnectionView, i: number, marked: boolean, now: number): Block { @@ -143,6 +158,7 @@ function connectionBlock(c: ConnectionView, i: number, marked: boolean, now: num line('host', c.host === null ? [{ text: 'local', dim: true }] : [{ text: c.host }]), line('tunnel', tunnel === '' ? [{ text: 'none', dim: true }] : [{ text: tunnel }]), line('access', c.selectOnly ? [{ text: 'select-only', color: STATUS_COLOURS.ok }] : [{ text: 'full access', color: STATUS_COLOURS.warn }]), + line('role', roleOf(c)), line('MCP', [{ text: `configurable: ${c.mcpConfigurable ? 'yes' : 'no'}`, ...(c.mcpConfigurable ? {} : { dim: true }) }]), line('schema', capturedOf(c.schemaCapturedAt, now)), ] diff --git a/plugin/hooks/lib/parse.spec.ts b/plugin/hooks/lib/parse.spec.ts index ae01d16..00eaacc 100644 --- a/plugin/hooks/lib/parse.spec.ts +++ b/plugin/hooks/lib/parse.spec.ts @@ -28,6 +28,14 @@ describe('reading what the argos CLI prints', () => { expect(parsePins([{ ...(fixture('pins') as object[])[0], sql: null }])).toBeNull() }) + it('reads a connection from a CLI older than the role check, and rejects a malformed role', () => { + const [first] = fixture('connections') as Record[] + const { role: _role, ...older } = first! + expect(parseConnections([older])).toEqual([older]) + expect(parseConnections([{ ...first, role: { checkedAt: 't', canWrite: 'no', principal: null, reasons: [] } }])).toBeNull() + expect(parseConnections([{ ...first, role: { checkedAt: 't', canWrite: null, principal: null, reasons: [] } }])).not.toBeNull() + }) + it('rejects what is not the shape at all', () => { for (const raw of [null, undefined, 'text', 3, {}, [{}]]) { expect(parseConnections(raw)).toBeNull() diff --git a/plugin/hooks/lib/parse.ts b/plugin/hooks/lib/parse.ts index d4cf08e..b37b2e4 100644 --- a/plugin/hooks/lib/parse.ts +++ b/plugin/hooks/lib/parse.ts @@ -68,6 +68,13 @@ const isChange = (raw: unknown): raw is SchemaChange => { return false } +const isRole = shape>({ + checkedAt: isString, + canWrite: orNull(isBoolean), + principal: orNull(isString), + reasons: listOf(isString), +}) + const isConnection = shape({ name: isString, type: isString, @@ -77,6 +84,7 @@ const isConnection = shape({ selectOnly: isBoolean, mcpConfigurable: isBoolean, schemaCapturedAt: orNull(isString), + role: optional(orNull(isRole)), }) const isSchema = shape({ diff --git a/plugin/hooks/mod/__tests__/fake-port.ts b/plugin/hooks/mod/__tests__/fake-port.ts index 4745e9a..3c7454b 100644 --- a/plugin/hooks/mod/__tests__/fake-port.ts +++ b/plugin/hooks/mod/__tests__/fake-port.ts @@ -21,6 +21,7 @@ export function fakePort(options: { files?: Record; run?: Runner const runs: { argv: string[]; timeoutMs: number | undefined }[] = [] const reads: string[] = [] const opened: string[] = [] + const openedWith: Record[] = [] const closed: string[] = [] const panes = new Set() const registered: string[] = [] @@ -58,6 +59,7 @@ export function fakePort(options: { files?: Record; run?: Runner panes: async () => [...panes].map(id => ({ id })), open: async (args: { id: string }) => { opened.push(args.id) + openedWith.push({ ...args }) panes.add(args.id) return { isPlaced: true } }, @@ -111,6 +113,7 @@ export function fakePort(options: { files?: Record; run?: Runner runs, reads, opened, + openedWith, closed, registered, advance, diff --git a/plugin/hooks/mod/session.spec.ts b/plugin/hooks/mod/session.spec.ts index 872690b..b8589e5 100644 --- a/plugin/hooks/mod/session.spec.ts +++ b/plugin/hooks/mod/session.spec.ts @@ -44,12 +44,33 @@ describe('the /argos command', () => { const port = fakePort() expect(await runCommand(port.io, '')).toBe('Argos pane opened.') expect(port.opened).toEqual(['argos']) + // The pane lays no ground of its own: the terminal's shows through. + expect(port.openedWith[0]).toMatchObject({ id: 'argos', backgroundColor: 'transparent' }) await port.advance() expect(port.runs.map(r => r.argv[2]).sort()).toEqual(['connections', 'history', 'pins']) expect(await runCommand(port.io, ' ')).toBe('Argos pane closed.') expect(port.closed).toEqual(['argos']) }) + it('opens without the transparent background on a host that refuses it', async () => { + const port = fakePort() + const open = port.io.ui.open + port.io.ui.open = async (args: { id: string; backgroundColor?: string }) => { + if (args.backgroundColor !== undefined) throw new Error('unknown key backgroundColor') + return open(args) + } + expect(await runCommand(port.io, '')).toBe('Argos pane opened.') + expect(port.openedWith).toEqual([{ id: 'argos', title: 'Argos' }]) + }) + + it('says so when the pane cannot be opened at all', async () => { + const port = fakePort() + port.io.ui.open = async () => { + throw new Error('no surface') + } + expect(await runCommand(port.io, '')).toBe('argos: the pane could not be opened (no surface)') + }) + it('answers anything else with its usage', async () => { const port = fakePort() expect(await runCommand(port.io, 'inspect x')).toMatch(/^Usage: \/argos/) diff --git a/plugin/hooks/mod/session.ts b/plugin/hooks/mod/session.ts index 7cbdd07..d15d85c 100644 --- a/plugin/hooks/mod/session.ts +++ b/plugin/hooks/mod/session.ts @@ -62,12 +62,23 @@ export async function startUp(io: Port, openOnStart: boolean): Promise { /** * Opens the pane and reads the connections again: every open does, so the * pane never presents an old list as current. The read runs on a timer. A - * refused or unplaced pane is the person's layout, not a failure of the mod. + * pane left unplaced is the person's layout, not a failure of the mod. + * The pane asks for no ground of its own, so the terminal's shows through; a + * host older than that option refuses the open, and is asked again without it. + * Resolves to why the pane could not be opened, or null when it was. */ -export async function openPane(io: Port): Promise { +export async function openPane(io: Port): Promise { await reloadConnections(io) await reloadQueries(io) - await io.ui.open({ id: PANE, title: 'Argos' }).catch(() => undefined) + try { + await io.ui.open({ id: PANE, title: 'Argos', backgroundColor: 'transparent' }) + return null + } catch { + return io.ui + .open({ id: PANE, title: 'Argos' }) + .then(() => null) + .catch((err: unknown) => message(err)) + } } /** Whether the pane is open now. */ @@ -84,8 +95,8 @@ export async function runCommand(io: Port, args: string): Promise { await io.ui.close({ id: PANE }).catch(() => undefined) return 'Argos pane closed.' } - await openPane(io) - return 'Argos pane opened.' + const failed = await openPane(io) + return failed === null ? 'Argos pane opened.' : `argos: the pane could not be opened (${failed})` } catch (err) { return `argos: ${message(err)}` } diff --git a/plugin/types/index.d.ts b/plugin/types/index.d.ts index 1e8cc95..c87be1a 100644 --- a/plugin/types/index.d.ts +++ b/plugin/types/index.d.ts @@ -18,6 +18,19 @@ export type ConnectionView = { selectOnly: boolean mcpConfigurable: boolean schemaCapturedAt: string | null + /** + * The MCP server's last check of a select_only connection's database role + * (`RoleView`); null when none ran, absent from a CLI older than the check. + */ + role?: RoleView | null +} + +/** What the database role may do, as the MCP server last found it; `canWrite` null when the check could not run. */ +export type RoleView = { + checkedAt: string + canWrite: boolean | null + principal: string | null + reasons: string[] } /** A change the schema check found, as the CLI's `src/schema/diff.ts` names it. */ diff --git a/src/classes/ConnectionManager.ts b/src/classes/ConnectionManager.ts index 67e19dd..8ea192c 100644 --- a/src/classes/ConnectionManager.ts +++ b/src/classes/ConnectionManager.ts @@ -26,8 +26,13 @@ import { recordFailure, recordSuccess, } from '../utils/circuit-breaker.js'; -import { CircuitOpenError } from '../utils/error-handler.js'; +import { CircuitOpenError, sanitizeError } from '../utils/error-handler.js'; import { writeAuditLog } from '../utils/audit-logger.js'; +import { + isPrivilegeReport, + privilegeWarning, + type PrivilegeProbe, +} from '../database/privileges.js'; // ============================================================================ // Connection Manager Class @@ -94,6 +99,7 @@ export class ConnectionManager extends EventEmitter { private sshTunnelManager: EnhancedSSHTunnelManager; private logger = getLogger(); private circuits = new Map(); + private privileges = new Map(); private metrics?: MetricsManager; private queryCache?: QueryCache; @@ -153,6 +159,9 @@ export class ConnectionManager extends EventEmitter { */ public unregisterDatabase(name: string): void { delete this.databases[name]; + this.privileges.delete(name); + // An updated or removed database's role check no longer describes it. + this.emit('unregistered', name); // Audit H2: invalidate the query cache for this database so stale results // from the old config/host are not served after an update or removal. @@ -277,6 +286,8 @@ export class ConnectionManager extends EventEmitter { ...config, host: tunnelInfo.localHost, port: tunnelInfo.localPort, + // The certificate names the database host, not the tunnel's local end. + ...(config.host ? { tls_servername: config.host } : {}), }; // Create new adapter with tunnel config @@ -315,6 +326,24 @@ export class ConnectionManager extends EventEmitter { }); } + // The database role is the boundary, the filter a second net: check the role once per + // connection, before the connection is published, so no caller can be handed it while + // require_readonly_role is still deciding. + if (config.select_only) { + const probe = await this.runPrivilegeProbe(dbName, adapter, connection); + if (config.require_readonly_role && !(isPrivilegeReport(probe) && !probe.canWrite)) { + await this.discardUnpublished(dbName, config, adapter, connection); + const why = isPrivilegeReport(probe) + ? `its role can write (${probe.reasons.join('; ')})` + : `its privileges could not be checked (${probe.error})`; + throw new ConnectionError( + `Refused to connect to '${dbName}': require_readonly_role is on and ${why}. ` + + 'Connect as a read-only role, or turn require_readonly_role off.', + { database: dbName } + ); + } + } + // Store connection info const connectionInfo: ConnectionInfo = { connection, @@ -349,6 +378,67 @@ export class ConnectionManager extends EventEmitter { } } + /** + * Run the adapter's privilege probe, remember the result and say when a + * select_only connection can write. A probe that fails is remembered as such, + * never thrown: the result is advice unless require_readonly_role asks for more. + */ + private async runPrivilegeProbe( + dbName: string, + adapter: DatabaseAdapter, + connection: DatabaseConnection + ): Promise { + let probe: PrivilegeProbe; + try { + probe = await this.withQueryTimeout( + dbName, + () => adapter.probePrivileges(connection), + 'Privilege check' + ); + } catch (error) { + // Driver errors can carry hosts, users or connection strings: the stored text reaches clients. + probe = { error: sanitizeError(error), checkedAt: new Date().toISOString() }; + this.logger.info(`Could not check the privileges of '${dbName}'`, { error: probe.error }); + } + this.privileges.set(dbName, probe); + const warning = privilegeWarning(probe); + if (warning) this.logger.warning(`Database '${dbName}': ${warning}`); + this.emit('privileges', dbName, probe); + return probe; + } + + /** Close a connection that was never published: its client, its pool and its tunnel. */ + private async discardUnpublished( + dbName: string, + config: DatabaseConfig, + adapter: DatabaseAdapter, + connection: DatabaseConnection + ): Promise { + await adapter.disconnect(connection).catch(() => undefined); + const poolable = adapter as unknown as { destroyPool?: () => Promise }; + if (typeof poolable.destroyPool === 'function') + await poolable.destroyPool().catch(() => undefined); + if (config.ssh_host) await this.sshTunnelManager.closeTunnel(dbName).catch(() => undefined); + } + + /** The last privilege check of a select_only database, if one ran. */ + public getPrivileges(dbName: string): PrivilegeProbe | undefined { + return this.privileges.get(dbName); + } + + /** Check a select_only database's privileges again on its open (or a new) connection. */ + async checkPrivileges(dbName: string): Promise { + const config = this.getDatabaseConfig(dbName); + if (!config?.select_only) return undefined; + const fresh = !this.connections.has(dbName); + const { connection } = await this.getConnection(dbName); + // A new connection was just checked by createConnection. + if (fresh) return this.privileges.get(dbName); + const adapter = this.adapters.get(dbName); + if (!adapter) return undefined; + return this.runPrivilegeProbe(dbName, adapter, connection); + } + /** * Get an existing connection or create a new one */ diff --git a/src/classes/SQLMCPServer.ts b/src/classes/SQLMCPServer.ts index 4727a21..7dc8449 100644 --- a/src/classes/SQLMCPServer.ts +++ b/src/classes/SQLMCPServer.ts @@ -4,6 +4,7 @@ * are extracted into src/tools/ and src/utils/response-formatter.ts */ +import type { PrivilegeProbe } from '../database/privileges.js'; import { EventEmitter } from 'events'; import { existsSync } from 'fs'; import { join, dirname, resolve } from 'path'; @@ -325,6 +326,21 @@ export class SQLMCPServer extends EventEmitter { this.connectionManager.on('disconnected', (dbName: string) => { this.logger.info(`Database connection closed: ${dbName}`); }); + // The pane reads the role check from the store: it runs in another process. + this.connectionManager.on('privileges', (dbName: string, probe: PrivilegeProbe) => { + this.paneStore?.recordRole(dbName, probe).catch((error) => { + this.logger.debug(`Could not record the role check of '${dbName}'`, { + error: (error as Error).message, + }); + }); + }); + this.connectionManager.on('unregistered', (dbName: string) => { + this.paneStore?.forgetRole(dbName).catch((error) => { + this.logger.debug(`Could not forget the role check of '${dbName}'`, { + error: (error as Error).message, + }); + }); + }); this.connectionManager.on('error', (error: Error, dbName?: string) => { this.logger.error(`Database connection error${dbName ? ` (${dbName})` : ''}`, error); }); diff --git a/src/classes/SecurityManager.ts b/src/classes/SecurityManager.ts index ca9956d..45dd423 100644 --- a/src/classes/SecurityManager.ts +++ b/src/classes/SecurityManager.ts @@ -21,7 +21,24 @@ import { getLogger } from '../utils/logger.js'; // ============================================================================ /** + * The SQL filter: what SELECT-only mode refuses before a query reaches the driver. * + * What it can promise: one statement, led by a read command, with no write, DDL or + * privilege keyword anywhere in it, none of the listed side-effect functions, no + * invisible formatting characters, and within the complexity limits. The published + * bypass families (stacked statements, comments as whitespace, SET, data-modifying + * CTEs, SELECT ... INTO, COPY ... TO PROGRAM, side-effect functions, case and + * Unicode tricks) are pinned in tests/unit/security-bypass-regression.test.ts. + * + * What it cannot promise: that a function it does not know has no side effects. + * A SELECT may call a user-defined function, or an extension's, that writes, and + * no keyword list sees inside it. Nor does it bound load beyond the complexity + * score: a heavy read is stopped by query_timeout, not here. + * + * So this is the second net. The boundary is the database role: a role that cannot + * write cannot be made to write by any parser bug. ConnectionManager checks the role + * of every select_only connection (src/database/privileges.ts) and warns, or with + * require_readonly_role refuses, when it can write. */ export class SecurityManager extends EventEmitter implements ISecurityManager { // Commands that are dangerous regardless of select_only mode @@ -416,6 +433,18 @@ export class SecurityManager extends EventEmitter implements ISecurityManager { }; } + // Invisible formatting characters (zero-width spaces and joiners, bidi controls, + // soft hyphens) split a keyword for this validator while meaning nothing to a + // reader: DELETE is not DELETE here. No read needs them. + if (/\p{Cf}/u.test(query)) { + return { + allowed: false, + reason: + 'Query contains invisible Unicode formatting characters (such as a zero-width space), which are not allowed in SELECT-only mode.', + confidence: 1.0, + }; + } + // Clean and normalize query let normalizedQuery: string; try { @@ -879,7 +908,19 @@ export class SecurityManager extends EventEmitter implements ISecurityManager { 'LO_IMPORT', 'LO_EXPORT', 'PG_SLEEP', - 'DBLINK', + // PostgreSQL functions that change state from inside a plain SELECT: session + // settings (turning a read-only session read-write), other backends, the server + // configuration, and sequences (an advance survives a rollback). + 'SET_CONFIG', + 'PG_TERMINATE_BACKEND', + 'PG_CANCEL_BACKEND', + 'PG_RELOAD_CONF', + 'PG_ROTATE_LOGFILE', + 'PG_SWITCH_WAL', + 'PG_PROMOTE', + 'NEXTVAL', + 'SETVAL', + 'LOWRITE', ]; for (const name of dangerousFunctionNames) { @@ -888,6 +929,20 @@ export class SecurityManager extends EventEmitter implements ISecurityManager { } } + // Whole families, matched by prefix: dblink_connect/dblink_exec/..., the + // large-object functions (lo_from_bytea, lo_unlink, lo_put, ...) and adminpack's + // pg_file_write/pg_file_unlink/.... lo_get only reads a large object and stays allowed. + const readOnlyMembers = new Set(['LO_GET']); + for (const prefix of ['DBLINK', 'LO_', 'PG_FILE_']) { + for (const match of query.matchAll(new RegExp(`\\b(${prefix}\\w*)\\s*\\(`, 'gi'))) { + const name = match[1]!.toUpperCase(); + if (!readOnlyMembers.has(name)) { + dangerous.push(`Function: ${name}`); + break; + } + } + } + // Phrase / construct patterns (not function-call shaped). const dangerousConstructs: Array<[string, RegExp]> = [ ['INTO OUTFILE', /\bINTO\s+OUTFILE\b/i], diff --git a/src/cli/pane-commands.ts b/src/cli/pane-commands.ts index 43b5e3a..5407df5 100644 --- a/src/cli/pane-commands.ts +++ b/src/cli/pane-commands.ts @@ -13,6 +13,7 @@ const LAST_CHANGE_SCAN = 500; /** List configured connections without opening any of them. */ export async function connections(core: Core): Promise { + const roles = await core.store.roles(); return Object.entries(core.config.databases).map(([name, c]) => ({ name, type: c.type, @@ -22,6 +23,8 @@ export async function connections(core: Core): Promise { selectOnly: c.select_only !== false, mcpConfigurable: !!c.mcp_configurable, schemaCapturedAt: core.schemaManager.getSchema(name)?.captured_at ?? null, + // Only a select_only connection is checked; a stale check of one switched to full access is not shown. + role: c.select_only !== false ? (roles[name] ?? null) : null, })); } diff --git a/src/database/adapters/AdapterFactory.ts b/src/database/adapters/AdapterFactory.ts index 9da526e..4c8bfa1 100644 --- a/src/database/adapters/AdapterFactory.ts +++ b/src/database/adapters/AdapterFactory.ts @@ -3,7 +3,7 @@ */ import type { DatabaseConfig, DatabaseTypeString } from '../../types/index.js'; -import { usesAzureCliAuth } from '../../utils/config.js'; +import { needsUsername, usesAzureCliAuth } from '../../utils/config.js'; import type { DatabaseAdapter } from './base.js'; import { MySQLAdapter } from './mysql.js'; import { PostgreSQLAdapter } from './postgresql.js'; @@ -76,8 +76,9 @@ export class AdapterFactory { // config loader exempts the pair too. Without this branch a valid // azure-cli database parses and loads but is rejected here, before the // adapter that knows how to connect it is ever built. + // PostgreSQL still needs the username: the Entra principal's name. if (config && usesAzureCliAuth(config)) { - return ['host', 'database']; + return needsUsername(config) ? ['host', 'database', 'username'] : ['host', 'database']; } return ['host', 'database', 'username', 'password']; default: diff --git a/src/database/adapters/base.ts b/src/database/adapters/base.ts index b7f68f2..bdabee6 100644 --- a/src/database/adapters/base.ts +++ b/src/database/adapters/base.ts @@ -11,6 +11,7 @@ import type { DatabaseTypeString, } from '../../types/index.js'; import { RedactionManager } from '../../classes/RedactionManager.js'; +import type { PrivilegeReport } from '../privileges.js'; // ============================================================================ // Abstract Database Adapter @@ -98,6 +99,14 @@ export abstract class DatabaseAdapter { */ abstract fingerprintQuery(): string; + /** + * Ask the database what this connection's role may do, with read-only queries. + * Engines without a probe say so by throwing; the caller treats that as unknown. + */ + public async probePrivileges(_connection: DatabaseConnection): Promise { + throw new Error(`no privilege probe for ${this.config.type}`); + } + // ============================================================================ // Performance Analysis // ============================================================================ diff --git a/src/database/adapters/mssql.ts b/src/database/adapters/mssql.ts index 71ac5d9..75829f8 100644 --- a/src/database/adapters/mssql.ts +++ b/src/database/adapters/mssql.ts @@ -10,6 +10,8 @@ import type { ConnectionPool as MSSQLConnectionPool, IResult, config as MSSQLCon // for the real package via `.default` and for the jest mock, which has no `.default`). const sql = ((sqlNs as unknown as { default?: typeof sqlNs }).default ?? sqlNs) as typeof sqlNs; import { DatabaseAdapter } from './base.js'; +import { azureCliCredential } from '../azure-credential.js'; +import { MSSQL_PRIVILEGE_QUERY, mssqlPrivileges, type PrivilegeReport } from '../privileges.js'; import type { DatabaseConnection, QueryResult, @@ -81,14 +83,10 @@ export class MSSQLAdapter extends DatabaseAdapter { }; if (azureCli) { - // Imported lazily so installs that never touch Azure, and the other three - // adapters, do not pay to load @azure/identity. - const { AzureCliCredential } = await import('@azure/identity'); - const tenantId = this.config.azure_tenant_id; connectionConfig.authentication = { type: 'token-credential', options: { - credential: tenantId ? new AzureCliCredential({ tenantId }) : new AzureCliCredential(), + credential: await azureCliCredential(this.config), }, }; } else { @@ -350,6 +348,11 @@ export class MSSQLAdapter extends DatabaseAdapter { return `SET SHOWPLAN_ALL ON; ${query}; SET SHOWPLAN_ALL OFF`; } + /** What this connection's role may do, from one read-only query. */ + override async probePrivileges(connection: DatabaseConnection): Promise { + return mssqlPrivileges(await this.executeQuery(connection, MSSQL_PRIVILEGE_QUERY)); + } + /** * Cheap query whose single row changes when the schema changes. */ diff --git a/src/database/adapters/mysql.ts b/src/database/adapters/mysql.ts index 5be75f0..9cffcb4 100644 --- a/src/database/adapters/mysql.ts +++ b/src/database/adapters/mysql.ts @@ -9,6 +9,7 @@ import type { PoolConnection as MySQLPoolConnection, } from 'mysql2/promise'; import { DatabaseAdapter } from './base.js'; +import { MYSQL_PRIVILEGE_QUERY, mysqlPrivileges, type PrivilegeReport } from '../privileges.js'; import type { DatabaseConnection, QueryResult, @@ -311,6 +312,11 @@ export class MySQLAdapter extends DatabaseAdapter { return `EXPLAIN FORMAT=JSON ${query}`; } + /** What this connection's role may do, from one read-only query. */ + override async probePrivileges(connection: DatabaseConnection): Promise { + return mysqlPrivileges(await this.executeQuery(connection, MYSQL_PRIVILEGE_QUERY)); + } + /** * Cheap query whose single row changes when the schema changes. */ diff --git a/src/database/adapters/postgresql.ts b/src/database/adapters/postgresql.ts index 36b5c03..918b1dd 100644 --- a/src/database/adapters/postgresql.ts +++ b/src/database/adapters/postgresql.ts @@ -2,9 +2,17 @@ * PostgreSQL Database Adapter */ +import * as tls from 'node:tls'; import * as pg from 'pg'; import type { Client as PgClient, PoolClient } from 'pg'; import { DatabaseAdapter } from './base.js'; +import { usesAzureCliAuth } from '../../utils/config.js'; +import { azureCliCredential, type EntraCredential } from '../azure-credential.js'; +import { + POSTGRES_PRIVILEGE_QUERY, + postgresPrivileges, + type PrivilegeReport, +} from '../privileges.js'; import type { DatabaseConnection, QueryResult, @@ -18,11 +26,46 @@ import type { // PostgreSQL Adapter Implementation // ============================================================================ +/** The resource Azure Database for PostgreSQL accepts Entra access tokens for. */ +export const AZURE_POSTGRES_SCOPE = 'https://ossrdbms-aad.database.windows.net/.default'; + +/** + * Whether a connect failure came from acquiring the token rather than from the + * connection itself; see the same check in the SQL Server adapter. + */ +function isCredentialFailure(error: unknown): boolean { + const name = (error as { name?: string } | null)?.name; + return name === 'CredentialUnavailableError' || name === 'AuthenticationError'; +} + /** * */ export class PostgreSQLAdapter extends DatabaseAdapter { private _pool?: pg.Pool; + private credential?: Promise; + + /** The Azure CLI credential, built once per adapter. */ + private entraCredential(): Promise { + this.credential ??= azureCliCredential(this.config); + return this.credential; + } + + /** + * A fresh Entra access token, the password for one new connection. Tokens live + * 5 to 60 minutes, so the pool asks again for every connection it opens rather + * than holding one string that would expire under it. + */ + private async entraToken(): Promise { + const credential = await this.entraCredential(); + const token = await credential.getToken(AZURE_POSTGRES_SCOPE); + if (!token?.token) { + const error = new Error('The Azure CLI returned no access token'); + error.name = 'CredentialUnavailableError'; + throw error; + } + return token.token; + } // ============================================================================ // Connection Management @@ -34,6 +77,7 @@ export class PostgreSQLAdapter extends DatabaseAdapter { const database = this.config.database as string; const username = this.config.username as string; const password = this.config.password as string; + const azureCli = usesAzureCliAuth(this.config); // Same resolution as every other adapter: query_timeout, else the // connection timeout, else 30s. This used to read query_timeout directly @@ -46,7 +90,8 @@ export class PostgreSQLAdapter extends DatabaseAdapter { port: this.parseConfigValue(this.config.port, 'number', 5432), database, user: username, - password, + // An async password is called by pg for every new connection. + password: azureCli ? () => this.entraToken() : password, max: 10, connectionTimeoutMillis: this.connectionTimeout, // Server-side cancellation: PostgreSQL aborts a query that runs longer than @@ -55,12 +100,17 @@ export class PostgreSQLAdapter extends DatabaseAdapter { query_timeout: statementTimeout, }; - // Mirror the same SSL branches as the old connect() to avoid behavior change - if (this.config.ssl !== undefined) { + if (azureCli) { + // A bearer token on an unverified connection goes to whoever answers, and is + // replayable against every database the identity can reach: TLS with + // certificate verification, whatever ssl and ssl_verify say. + poolConfig.ssl = this.verifiedTls(); + } else if (this.config.ssl !== undefined) { + // Mirror the same SSL branches as the old connect() to avoid behavior change const sslEnabled = this.parseConfigValue(this.config.ssl, 'boolean', false); if (sslEnabled) { const sslVerify = this.verifyServerCertificate(); - poolConfig.ssl = { rejectUnauthorized: sslVerify }; + poolConfig.ssl = sslVerify ? this.verifiedTls() : { rejectUnauthorized: false }; } else { poolConfig.ssl = false; // explicitly disable } @@ -71,11 +121,29 @@ export class PostgreSQLAdapter extends DatabaseAdapter { return this._pool; } + /** + * TLS with certificate verification. Through an SSH tunnel the connection goes to + * 127.0.0.1, so the certificate is checked against the database's own hostname + * (tls_servername), which is also sent as SNI. + */ + private verifiedTls(): pg.PoolConfig['ssl'] { + const name = this.config.tls_servername; + if (!name) return { rejectUnauthorized: true }; + return { + rejectUnauthorized: true, + servername: name, + checkServerIdentity: (_host, cert) => tls.checkServerIdentity(name, cert), + }; + } + /** * */ async connect(): Promise { - this.validateConfig(['host', 'database', 'username', 'password']); + const azureCli = usesAzureCliAuth(this.config); + this.validateConfig( + azureCli ? ['host', 'database', 'username'] : ['host', 'database', 'username', 'password'] + ); try { const client: PoolClient = await this.getPool().connect(); if (this.config.read_only_session) { @@ -90,7 +158,13 @@ export class PostgreSQLAdapter extends DatabaseAdapter { } return client as DatabaseConnection; } catch (error) { - throw this.createError('Failed to acquire PostgreSQL connection from pool', error as Error); + throw this.createError( + azureCli && isCredentialFailure(error) + ? 'Failed to connect to PostgreSQL using Azure CLI authentication. ' + + 'Check that the Azure CLI is installed and that `az login` has been run' + : 'Failed to acquire PostgreSQL connection from pool', + error as Error + ); } } @@ -217,6 +291,11 @@ export class PostgreSQLAdapter extends DatabaseAdapter { return `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ${query}`; } + /** What this connection's role may do, from one read-only query. */ + override async probePrivileges(connection: DatabaseConnection): Promise { + return postgresPrivileges(await this.executeQuery(connection, POSTGRES_PRIVILEGE_QUERY)); + } + /** * Cheap query whose single row changes when the schema changes. */ diff --git a/src/database/adapters/sqlite.ts b/src/database/adapters/sqlite.ts index e1e64d6..d704fae 100644 --- a/src/database/adapters/sqlite.ts +++ b/src/database/adapters/sqlite.ts @@ -13,6 +13,7 @@ const sqlite3 = ((sqlite3Ns as unknown as { default?: typeof sqlite3Ns }).defaul sqlite3Ns) as typeof sqlite3Ns; const { Database } = sqlite3; import { DatabaseAdapter } from './base.js'; +import { sqlitePrivileges, type PrivilegeReport } from '../privileges.js'; import type { DatabaseConnection, QueryResult, @@ -282,6 +283,11 @@ export class SQLiteAdapter extends DatabaseAdapter { return `EXPLAIN QUERY PLAN ${query}`; } + /** SQLite has no roles: the file is opened read-only for a select_only database, read-write otherwise. */ + override async probePrivileges(_connection: DatabaseConnection): Promise { + return sqlitePrivileges(!!this.config.select_only); + } + /** * Cheap query whose single row changes when the schema changes. capture_version changes * the fingerprint of every schema cached before the capture gained generated columns and diff --git a/src/database/azure-credential.ts b/src/database/azure-credential.ts new file mode 100644 index 0000000..3ddd5fc --- /dev/null +++ b/src/database/azure-credential.ts @@ -0,0 +1,120 @@ +/** + * The Azure CLI credential the SQL Server and PostgreSQL adapters take Entra + * tokens from. + * + * `@azure/identity`'s AzureCliCredential runs `az` in the server's own + * environment, so the whole server shares one Azure CLI profile (the default, or + * whatever AZURE_CONFIG_DIR the server was started with). A database that sets + * `azure_config_dir` gets its own profile instead: a dedicated reader identity + * signed in with `AZURE_CONFIG_DIR= az login`, kept apart from the person's + * own, possibly admin, login. + */ + +import { execFile } from 'node:child_process'; +import { homedir } from 'node:os'; +import type { DatabaseConfig } from '../types/index.js'; + +/** The part of `@azure/identity`'s TokenCredential the drivers call. */ +export interface EntraCredential { + getToken( + scopes: string | string[] + ): Promise<{ token: string; expiresOnTimestamp: number } | null>; +} + +const AZ_TIMEOUT_MS = 30_000; + +/** An error the adapters read as "the token could not be acquired". */ +function unavailable(message: string): Error { + const error = new Error(message); + error.name = 'CredentialUnavailableError'; + return error; +} + +/** + * `az account get-access-token`, run with AZURE_CONFIG_DIR set to one profile + * directory. Nothing is cached here: `az` keeps and refreshes its own tokens. + */ +export class AzureCliProfileCredential implements EntraCredential { + constructor( + private readonly configDir: string, + private readonly tenantId?: string + ) {} + + /** A token for the first scope, from this profile; throws CredentialUnavailableError when there is none. */ + async getToken( + scopes: string | string[] + ): Promise<{ token: string; expiresOnTimestamp: number }> { + const scope = Array.isArray(scopes) ? scopes[0] : scopes; + if (!scope) throw unavailable('No scope to request an Azure CLI token for'); + const resource = scope.replace(/\/\.default$/, ''); + const args = ['account', 'get-access-token', '--output', 'json', '--resource', resource]; + if (this.tenantId) args.push('--tenant', this.tenantId); + + const stdout = await new Promise((resolve, reject) => { + execFile( + 'az', + args, + { + env: { ...process.env, AZURE_CONFIG_DIR: this.configDir }, + cwd: homedir(), + timeout: AZ_TIMEOUT_MS, + encoding: 'utf8', + // az is a batch file on Windows; the arguments are fixed strings and a GUID. + shell: process.platform === 'win32', + }, + (error, out, err) => { + if (!error) return resolve(out); + if ((error as NodeJS.ErrnoException).code === 'ENOENT') { + return reject(unavailable('The Azure CLI (az) is not installed or not on PATH')); + } + const detail = String(err ?? '') + .trim() + .split('\n')[0]; + reject( + unavailable( + `No token from the Azure CLI profile in ${this.configDir}: ` + + `run AZURE_CONFIG_DIR="${this.configDir}" az login` + + (detail ? ` (${detail})` : '') + ) + ); + } + ); + }); + + let parsed: { accessToken?: unknown; expires_on?: unknown; expiresOn?: unknown }; + try { + parsed = JSON.parse(stdout); + } catch { + throw unavailable('The Azure CLI answered with something other than JSON'); + } + if (typeof parsed.accessToken !== 'string' || parsed.accessToken === '') { + throw unavailable('The Azure CLI returned no access token'); + } + // expires_on is epoch seconds (az 2.54+); expiresOn a local date-time string. + const expiresOnTimestamp = + typeof parsed.expires_on === 'number' + ? parsed.expires_on * 1000 + : typeof parsed.expires_on === 'string' && /^\d+$/.test(parsed.expires_on) + ? Number(parsed.expires_on) * 1000 + : Date.parse(String(parsed.expiresOn ?? '')); + return { + token: parsed.accessToken, + expiresOnTimestamp: Number.isFinite(expiresOnTimestamp) ? expiresOnTimestamp : Date.now(), + }; + } +} + +/** + * The credential for a database using authentication=azure-cli: its own profile + * when it sets azure_config_dir, else `@azure/identity`'s AzureCliCredential + * (imported lazily so installs that never touch Azure do not load it). + */ +export async function azureCliCredential( + config: Pick +): Promise { + const tenantId = config.azure_tenant_id; + if (config.azure_config_dir) + return new AzureCliProfileCredential(config.azure_config_dir, tenantId); + const { AzureCliCredential } = await import('@azure/identity'); + return tenantId ? new AzureCliCredential({ tenantId }) : new AzureCliCredential(); +} diff --git a/src/database/privileges.ts b/src/database/privileges.ts new file mode 100644 index 0000000..0053e09 --- /dev/null +++ b/src/database/privileges.ts @@ -0,0 +1,290 @@ +/** + * What the database itself would let a connection do. + * + * Argos's SQL filter is a second net. The boundary is the role the connection + * logs in as: a select_only database connected as a principal that can write + * is one filter bug away from a DELETE. The probe asks the database, with + * read-only queries, whether the role can write, so that can be said out loud. + * + * The mapping functions here are pure: each adapter runs its own query and hands + * the rows over. + */ + +import type { QueryResult } from '../types/index.js'; + +export interface PrivilegeReport { + /** True when the database would let this connection change data or schema. */ + canWrite: boolean; + /** Who the database says the connection is, e.g. `dbo`, `reader@contoso.com`. */ + principal: string | null; + /** Why it can write, one short phrase each: `db_owner`, `INSERT on 12 tables`. */ + reasons: string[]; + /** Facts that matter but do not make it writable on their own. */ + notes: string[]; + /** ISO timestamp of the probe. */ + checkedAt: string; +} + +/** A probe that could not run. Never fatal: the warning is advice, not a gate. */ +export interface PrivilegeProbeFailure { + error: string; + checkedAt: string; +} + +export type PrivilegeProbe = PrivilegeReport | PrivilegeProbeFailure; + +/** Whether a probe result is a report rather than a failure. */ +export function isPrivilegeReport(probe: PrivilegeProbe | undefined): probe is PrivilegeReport { + return probe !== undefined && 'canWrite' in probe; +} + +const now = (): string => new Date().toISOString(); + +/** A flag as a driver returns it: 1, true, '1', 't' (pg text), 'on'. */ +function truthy(value: unknown): boolean { + if (typeof value === 'boolean') return value; + if (typeof value === 'number') return value === 1; + if (typeof value === 'bigint') return value === 1n; + if (typeof value === 'string') + return ['1', 't', 'true', 'on', 'yes'].includes(value.toLowerCase()); + return false; +} + +function count(value: unknown): number { + const n = + typeof value === 'string' ? Number(value) : typeof value === 'bigint' ? Number(value) : value; + return typeof n === 'number' && Number.isFinite(n) ? n : 0; +} + +function text(value: unknown): string | null { + return typeof value === 'string' && value !== '' ? value : null; +} + +function firstRow(result: QueryResult): Record { + const row = result.rows[0]; + if (!row) throw new Error('the privilege query returned no row'); + return row; +} + +const plural = (n: number, word: string): string => `${n} ${word}${n === 1 ? '' : 's'}`; + +// ============================================================================ +// SQL Server +// ============================================================================ + +/** + * One row. IS_SRVROLEMEMBER is NULL on Azure SQL Database, where server roles + * do not exist for a contained user; NULL is read as "not a member". + * HAS_PERMS_BY_NAME on the database covers grants made outside the fixed roles. + */ +export const MSSQL_PRIVILEGE_QUERY = `SELECT + USER_NAME() AS principal, + IS_ROLEMEMBER('db_owner') AS db_owner, + IS_ROLEMEMBER('db_datawriter') AS db_datawriter, + IS_ROLEMEMBER('db_ddladmin') AS db_ddladmin, + IS_SRVROLEMEMBER('sysadmin') AS sysadmin, + HAS_PERMS_BY_NAME(DB_NAME(), 'DATABASE', 'CREATE TABLE') AS create_table, + HAS_PERMS_BY_NAME(DB_NAME(), 'DATABASE', 'INSERT') AS db_insert, + HAS_PERMS_BY_NAME(DB_NAME(), 'DATABASE', 'UPDATE') AS db_update, + HAS_PERMS_BY_NAME(DB_NAME(), 'DATABASE', 'DELETE') AS db_delete, + (SELECT COUNT(*) FROM sys.tables t JOIN sys.schemas s ON s.schema_id = t.schema_id + WHERE HAS_PERMS_BY_NAME(QUOTENAME(s.name) + '.' + QUOTENAME(t.name), 'OBJECT', 'INSERT') = 1 + OR HAS_PERMS_BY_NAME(QUOTENAME(s.name) + '.' + QUOTENAME(t.name), 'OBJECT', 'UPDATE') = 1 + OR HAS_PERMS_BY_NAME(QUOTENAME(s.name) + '.' + QUOTENAME(t.name), 'OBJECT', 'DELETE') = 1 + ) AS writable_tables`; + +/** Map the SQL Server probe's row. */ +export function mssqlPrivileges(result: QueryResult): PrivilegeReport { + const row = firstRow(result); + const principal = text(row.principal); + const reasons: string[] = []; + if (truthy(row.sysadmin)) reasons.push('sysadmin'); + if (truthy(row.db_owner)) reasons.push('db_owner'); + // dbo owns the database whatever its role membership says. + else if (principal === 'dbo') reasons.push('database owner'); + if (truthy(row.db_datawriter)) reasons.push('db_datawriter'); + if (truthy(row.db_ddladmin)) reasons.push('db_ddladmin'); + // The roles above imply these; only say them when nothing else did. + if (reasons.length === 0) { + const granted = ['INSERT', 'UPDATE', 'DELETE'].filter((p) => + truthy(row[`db_${p.toLowerCase()}`]) + ); + if (granted.length > 0) reasons.push(`${granted.join('/')} on the database`); + if (truthy(row.create_table)) reasons.push('CREATE TABLE'); + const tables = count(row.writable_tables); + if (tables > 0) reasons.push(`INSERT/UPDATE/DELETE on ${plural(tables, 'table')}`); + } + return { canWrite: reasons.length > 0, principal, reasons, notes: [], checkedAt: now() }; +} + +// ============================================================================ +// PostgreSQL +// ============================================================================ + +/** + * One row. The predefined roles are looked up by name in pg_roles so the query + * still runs on versions that do not have them. Tables are counted in every + * schema the role can use, catalogs excluded. + */ +export const POSTGRES_PRIVILEGE_QUERY = `SELECT + current_user AS principal, + (SELECT rolsuper FROM pg_roles WHERE rolname = current_user) AS is_superuser, + COALESCE((SELECT string_agg(g.rolname, ',' ORDER BY g.rolname) FROM pg_roles g + WHERE g.rolname IN ('pg_execute_server_program', 'pg_read_server_files', 'pg_write_server_files', 'pg_write_all_data') + AND pg_has_role(current_user, g.oid, 'MEMBER')), '') AS server_roles, + (SELECT count(*) FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE c.relkind IN ('r', 'p') + AND n.nspname NOT IN ('pg_catalog', 'information_schema') AND n.nspname NOT LIKE 'pg\\_toast%' + AND has_schema_privilege(n.oid, 'USAGE') + AND has_table_privilege(c.oid, 'INSERT, UPDATE, DELETE, TRUNCATE')) AS writable_tables, + COALESCE((SELECT string_agg(n.nspname, ',' ORDER BY n.nspname) FROM pg_namespace n + WHERE n.nspname NOT IN ('pg_catalog', 'information_schema') AND n.nspname NOT LIKE 'pg\\_%' + AND has_schema_privilege(n.oid, 'CREATE')), '') AS create_schemas, + current_setting('default_transaction_read_only') AS default_read_only`; + +/** Map the PostgreSQL probe's row. */ +export function postgresPrivileges(result: QueryResult): PrivilegeReport { + const row = firstRow(result); + const reasons: string[] = []; + const notes: string[] = []; + if (truthy(row.is_superuser)) reasons.push('superuser'); + const roles = (text(row.server_roles) ?? '').split(',').filter((r) => r !== ''); + // pg_read_server_files reads, the rest write or run programs: all of them reach past the tables. + for (const role of roles) reasons.push(role); + const tables = count(row.writable_tables); + if (tables > 0) reasons.push(`INSERT/UPDATE/DELETE/TRUNCATE on ${plural(tables, 'table')}`); + const schemas = (text(row.create_schemas) ?? '').split(',').filter((s) => s !== ''); + if (schemas.length > 0) reasons.push(`CREATE in schema ${schemas.join(', ')}`); + if (truthy(row.default_read_only)) { + notes.push('default_transaction_read_only is on, but a session can turn it off'); + } + return { + canWrite: reasons.length > 0, + principal: text(row.principal), + reasons, + notes, + checkedAt: now(), + }; +} + +// ============================================================================ +// MySQL +// ============================================================================ + +export const MYSQL_PRIVILEGE_QUERY = 'SHOW GRANTS FOR CURRENT_USER()'; + +/** Privileges that only read. USAGE is "no privileges". */ +const MYSQL_READ_PRIVILEGES = new Set(['SELECT', 'SHOW VIEW', 'USAGE', 'SHOW DATABASES']); + +/** + * Split a GRANT's privilege list on top-level commas: column privileges carry + * their own comma lists, as in `SELECT (a, b), INSERT (c)`. + */ +function splitPrivileges(list: string): string[] { + const out: string[] = []; + let depth = 0; + let current = ''; + for (const ch of list) { + if (ch === '(') depth++; + if (ch === ')') depth = Math.max(0, depth - 1); + if (ch === ',' && depth === 0) { + out.push(current); + current = ''; + } else current += ch; + } + out.push(current); + return out + .map((p) => + p + .replace(/\(.*\)/, '') + .trim() + .toUpperCase() + ) + .filter((p) => p !== ''); +} + +/** Map SHOW GRANTS: one row per GRANT statement, in a column named `Grants for user@host`. */ +export function mysqlPrivileges(result: QueryResult): PrivilegeReport { + const reasons: string[] = []; + const notes: string[] = []; + let principal: string | null = null; + for (const row of result.rows) { + const [column, value] = Object.entries(row)[0] ?? []; + if (principal === null && column?.startsWith('Grants for ')) + principal = column.slice('Grants for '.length); + if (typeof value !== 'string') continue; + const grant = /^GRANT\s+(.+?)\s+ON\s+(.+?)\s+TO\s+/i.exec(value); + if (!grant) { + // A role grant (`GRANT role TO user`): its privileges are not listed here, so the + // role may write. Unknown is not read-only: it counts, and require_readonly_role refuses. + const role = /^GRANT\s+(.+?)\s+TO\s+/i.exec(value); + if (role) reasons.push(`role ${role[1]} (its privileges are not checked)`); + continue; + } + const target = grant[2]!.trim(); + for (const privilege of splitPrivileges(grant[1]!)) { + if (MYSQL_READ_PRIVILEGES.has(privilege)) continue; + if (privilege === 'PROXY') reasons.push(`PROXY on ${target}`); + else if (privilege === 'FILE') reasons.push('FILE (reads and writes files on the server)'); + else reasons.push(`${privilege} on ${target}`); + } + } + return { + canWrite: reasons.length > 0, + principal, + reasons: [...new Set(reasons)], + notes, + checkedAt: now(), + }; +} + +// ============================================================================ +// SQLite +// ============================================================================ + +/** SQLite has no roles: the boundary is whether the file was opened read-only. */ +export function sqlitePrivileges(readOnly: boolean): PrivilegeReport { + return { + canWrite: !readOnly, + principal: null, + reasons: readOnly ? [] : ['the file is opened read-write'], + notes: readOnly ? ['the file is opened read-only'] : [], + checkedAt: now(), + }; +} + +// ============================================================================ +// The warning +// ============================================================================ + +/** + * The one-line warning for a select_only database whose connection can write, + * or null when there is nothing to warn about. + */ +export function privilegeWarning(probe: PrivilegeProbe | undefined): string | null { + if (!isPrivilegeReport(probe) || !probe.canWrite) return null; + const who = probe.principal === null ? '' : ` as ${probe.principal}`; + return ( + `select_only is on, but this connection can write${who} (${probe.reasons.join('; ')}). ` + + "Argos's filter is the only guard. Connect as a read-only role." + ); +} + +/** + * The privilege check as lines for a tool response. Nothing for a database + * that is not select_only: full access is what it says. + */ +export function describePrivileges( + selectOnly: boolean, + probe: PrivilegeProbe | undefined +): string[] { + if (!selectOnly) return []; + if (probe === undefined) + return ['Database role: not checked yet (it is checked when Argos connects)']; + if (!isPrivilegeReport(probe)) return [`Database role: could not be checked (${probe.error})`]; + const notes = probe.notes.map((n) => `Note: ${n}`); + const warning = privilegeWarning(probe); + if (warning) return [`Warning: ${warning}`, ...notes]; + const who = probe.principal === null ? '' : ` (${probe.principal})`; + return [`Database role: read-only${who}`, ...notes]; +} diff --git a/src/pane/contract.ts b/src/pane/contract.ts index cf6e25c..26bbbef 100644 --- a/src/pane/contract.ts +++ b/src/pane/contract.ts @@ -49,6 +49,19 @@ export interface ConnectionView { selectOnly: boolean; mcpConfigurable: boolean; schemaCapturedAt: string | null; + /** The server's last check of a select_only connection's database role; null when none ran. */ + role: RoleView | null; +} + +/** + * What the database role may do, as the MCP server last found it. `canWrite` is + * null when the check could not run. + */ +export interface RoleView { + checkedAt: string; + canWrite: boolean | null; + principal: string | null; + reasons: string[]; } export interface SchemaView { diff --git a/src/pane/store.ts b/src/pane/store.ts index dc549d8..5b71f81 100644 --- a/src/pane/store.ts +++ b/src/pane/store.ts @@ -12,7 +12,9 @@ import { } from 'node:fs/promises'; import { dirname, join, resolve } from 'node:path'; import type { QueryResult } from '../types/database.js'; -import type { JournalEntry, Pin, SpoolPage } from './contract.js'; +import type { JournalEntry, Pin, RoleView, SpoolPage } from './contract.js'; +// Type only: the store is also loaded on its own, outside the build, by a multi-process test. +import type { PrivilegeProbe } from '../database/privileges.js'; const DIR_MODE = 0o700; const FILE_MODE = 0o600; @@ -42,6 +44,7 @@ export class PaneStore { private readonly spoolDays: number; private readonly now: () => number; private ensured = false; + private roleChanges: Promise = Promise.resolve(); constructor( private readonly dir: string, @@ -64,6 +67,9 @@ export class PaneStore { private get checksPath(): string { return join(this.dir, 'schema-checks.json'); } + private get rolesPath(): string { + return join(this.dir, 'roles.json'); + } /** * @@ -252,8 +258,77 @@ export class PaneStore { } private async readChecks(): Promise> { + return this.readJsonObject(this.checksPath); + } + + /** + * Change roles.json, one change at a time: each reads the file as the previous + * change left it, so two checks finishing together cannot overwrite each other. + * A failed change is the caller's to see; the queue goes on after it. + */ + private updateRoles(change: (roles: Record) => boolean): Promise { + const run = this.roleChanges.then(async () => { + await this.ensureDirs(); + const roles = await this.readJsonObject(this.rolesPath); + if (change(roles)) await this.writeAtomic(this.rolesPath, JSON.stringify(roles)); + }); + this.roleChanges = run.catch(() => undefined); + return run; + } + + /** Record the MCP server's privilege check of a connection, for the pane to show. */ + recordRole(database: string, probe: PrivilegeProbe): Promise { + const role: RoleView = + 'canWrite' in probe + ? { + checkedAt: probe.checkedAt, + canWrite: probe.canWrite, + principal: probe.principal, + reasons: probe.reasons, + } + : { checkedAt: probe.checkedAt, canWrite: null, principal: null, reasons: [] }; + return this.updateRoles((roles) => { + roles[database] = role; + return true; + }); + } + + /** Drop a connection's recorded role check, after its config changed or it was removed. */ + forgetRole(database: string): Promise { + return this.updateRoles((roles) => { + if (!(database in roles)) return false; + delete roles[database]; + return true; + }); + } + + /** Every recorded role check, by database name. A malformed entry is left out. */ + async roles(): Promise> { + const out: Record = {}; + for (const [db, raw] of Object.entries(await this.readJsonObject(this.rolesPath))) { + const r = raw as Partial | null; + if ( + r && + typeof r.checkedAt === 'string' && + (r.canWrite === null || typeof r.canWrite === 'boolean') && + (r.principal === null || typeof r.principal === 'string') && + Array.isArray(r.reasons) && + r.reasons.every((x) => typeof x === 'string') + ) { + out[db] = { + checkedAt: r.checkedAt, + canWrite: r.canWrite, + principal: r.principal, + reasons: r.reasons, + }; + } + } + return out; + } + + private async readJsonObject(path: string): Promise> { try { - const parsed = JSON.parse(await readFile(this.checksPath, 'utf8')); + const parsed = JSON.parse(await readFile(path, 'utf8')); return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {}; } catch { return {}; diff --git a/src/tools/handlers/schema-handlers.ts b/src/tools/handlers/schema-handlers.ts index 792e96d..6800321 100644 --- a/src/tools/handlers/schema-handlers.ts +++ b/src/tools/handlers/schema-handlers.ts @@ -3,6 +3,7 @@ * Handles sql_get_schema, sql_refresh_schema, sql_list_databases, sql_test_connection */ +import { describePrivileges } from '../../database/privileges.js'; import type { SQLGetSchemaArgs, SQLTestConnectionArgs, @@ -96,6 +97,7 @@ export async function handleListDatabases(ctx: ToolHandlerContext): Promise ({ + error: sanitizeError(error), + checkedAt: new Date().toISOString(), + })); + // Capture schema if not cached (schema failure is non-fatal) if (!ctx.schemaManager.hasSchema(database)) { try { @@ -162,6 +170,9 @@ export async function handleTestConnection( let responseText = ` Connection successful to ${database}\n`; if (ctx.sshTunnelManager.hasTunnel(database)) responseText += ` SSH tunnel established\n`; if (dbConfig.select_only) responseText += ` SELECT-only mode active\n`; + for (const line of describePrivileges(!!dbConfig.select_only, privileges)) { + responseText += ` ${line}\n`; + } if (schema) { responseText += ` Schema captured: ${schema.summary.table_count} tables, ${schema.summary.total_columns} columns\n`; } diff --git a/src/types/database.ts b/src/types/database.ts index 50b0c20..8c40a1f 100644 --- a/src/types/database.ts +++ b/src/types/database.ts @@ -9,6 +9,7 @@ import type { } from 'mysql2/promise'; import type { Database as SQLiteConnection } from 'sqlite3'; import type { ConnectionPool as MSSQLConnection } from 'mssql'; +import type { PrivilegeProbe } from '../database/privileges.js'; // ============================================================================ // Database Types @@ -49,17 +50,25 @@ export interface DatabaseConfig { ssl_verify?: boolean; // Verify SSL certificates (default: true) select_only?: boolean; name_check?: boolean; // Check table/column names against the cached schema before running a query + // Refuse a select_only connection whose database role can write, or whose + // privileges could not be checked. Off by default: the check then only warns. + require_readonly_role?: boolean; // Ask the database itself to refuse writes for the whole session (PostgreSQL and // MySQL only). Never read from config.ini: the pane CLI sets it on its own copy of // each connection so the MCP server's behaviour is unchanged. read_only_session?: boolean; + // The database's own hostname, set by ConnectionManager on the copy of the config it + // points at an SSH tunnel (host then reads 127.0.0.1). A verified TLS connection checks + // the certificate against this name instead. Never read from config.ini. + tls_servername?: string; timeout?: number; file?: string; // For SQLite encrypt?: boolean; // For MSSQL - // Authentication mode. Only meaningful for MSSQL; omitted means SQL - // authentication with username/password. 'azure-cli' delegates to the - // signed-in Azure CLI, so no credentials live in config.ini. + // Authentication mode, for MSSQL and PostgreSQL; omitted means username and + // password. 'azure-cli' takes an Entra access token from the signed-in Azure + // CLI, so no secret lives in config.ini. On PostgreSQL the username is still + // needed: it is the Entra principal's name as mapped in the database. authentication?: MSSQLAuthenticationMode; // Tenant to acquire the Azure CLI token from. Only meaningful alongside @@ -68,6 +77,11 @@ export interface DatabaseConfig { // case for an account with access to several. azure_tenant_id?: string; + // Azure CLI profile directory to take the token from, as AZURE_CONFIG_DIR, so + // this database can use its own (reader) identity. Only alongside + // authentication='azure-cli'; unset, the server's own profile is used. + azure_config_dir?: string; + // SSH Tunnel Configuration ssh_host?: string; ssh_port?: number; @@ -230,6 +244,8 @@ export interface DatabaseListItem { select_only_mode: boolean; mcp_configurable: boolean; schema_cached: boolean; + /** The last privilege check of a select_only database, if one ran. */ + privileges?: PrivilegeProbe; schema_info?: { table_count: number; view_count: number; diff --git a/src/utils/config.ts b/src/utils/config.ts index ec022e7..ddae56d 100644 --- a/src/utils/config.ts +++ b/src/utils/config.ts @@ -4,7 +4,8 @@ */ import { readFileSync, existsSync, writeFileSync, statSync, mkdirSync, renameSync } from 'fs'; -import { join, dirname } from 'path'; +import { join, dirname, isAbsolute } from 'path'; +import { homedir } from 'os'; import { parse as parseIni } from 'ini'; import type { @@ -62,14 +63,25 @@ export type FullyParsedConfig = ParsedServerConfig & { const SHELL_METACHAR_RE = /[;&|$()><]/; const EMBEDDED_CREDENTIALS_RE = /[^@]+:[^@]+@/; +/** The engines that can take an Entra access token from the Azure CLI. */ +const AZURE_CLI_TYPES: readonly string[] = ['mssql', 'postgresql', 'postgres']; + /** - * Azure CLI authentication takes its identity from the signed-in `az` session, - * so a username and password are not merely optional but absent by design. - * Every credential check has to agree on that, or a config valid at parse time - * fails at connect time (or the reverse). + * Azure CLI authentication takes its credential from the signed-in `az` session, + * so a password is not merely optional but absent by design. Every credential + * check has to agree on that, or a config valid at parse time fails at connect + * time (or the reverse). */ export function usesAzureCliAuth(config: Pick): boolean { - return config.type === 'mssql' && config.authentication === 'azure-cli'; + return AZURE_CLI_TYPES.includes(config.type) && config.authentication === 'azure-cli'; +} + +/** + * Whether the database still needs a username. SQL Server takes the identity + * from the token; PostgreSQL needs the Entra principal's name as its user. + */ +export function needsUsername(config: Pick): boolean { + return !(usesAzureCliAuth(config) && config.type === 'mssql'); } /** @@ -82,9 +94,11 @@ export function validateDatabaseConfig(config: DatabaseConfig): ValidationResult if (t === 'mysql' || t === 'postgresql' || t === 'mssql') { if (!config.host) errors.push({ field: 'host', message: 'host is required' }); if (!config.port) errors.push({ field: 'port', message: 'port is required' }); - if (!usesAzureCliAuth(config)) { + if (needsUsername(config)) { if (!(config as unknown as Record).user && !config.username) errors.push({ field: 'user', message: 'user is required' }); + } + if (!usesAzureCliAuth(config)) { if (!config.password) errors.push({ field: 'password', message: 'password is required' }); } if (!config.database) errors.push({ field: 'database', message: 'database is required' }); @@ -244,6 +258,13 @@ export function parseDatabaseConfig(name: string, config: Record config.name_check === undefined ? true : parseBool(config.name_check, 'name_check', name), mcp_configurable: parseBool(config.mcp_configurable, 'mcp_configurable', name), }; + if (config.require_readonly_role !== undefined) { + dbConfig.require_readonly_role = parseBool( + config.require_readonly_role, + 'require_readonly_role', + name + ); + } // Handle SQLite specific configuration if (dbConfig.type === 'sqlite') { @@ -255,6 +276,17 @@ export function parseDatabaseConfig(name: string, config: Record ); } dbConfig.file = config.file; + // The networked path validates these; SQLite has no login, so any of them is a mistake. + const field = (['authentication', 'azure_tenant_id', 'azure_config_dir'] as const).find( + (key) => config[key] !== undefined + ); + if (field) { + throw new ConfigValidationError( + `Database '${name}' sets '${field}' but that is only supported for types 'mssql' and 'postgresql'`, + field, + name + ); + } } else { // Handle other database types validateNetworkedDatabase(name, config, dbConfig); @@ -314,11 +346,48 @@ function parseAzureTenantId( dbConfig.azure_tenant_id = tenant; } +/** + * Parse and validate the optional 'azure_config_dir' key: the Azure CLI profile + * this database takes its token from. A leading `~` is the home directory; the + * result must be absolute, because the server's working directory is whatever + * the MCP client started it in. + */ +function parseAzureConfigDir( + name: string, + config: Record, + dbConfig: DatabaseConfig +): void { + if (config.azure_config_dir === undefined) { + return; + } + + if (!usesAzureCliAuth(dbConfig)) { + throw new ConfigValidationError( + `Database '${name}' sets 'azure_config_dir' but that requires authentication=azure-cli`, + 'azure_config_dir', + name + ); + } + + const raw = config.azure_config_dir.trim(); + const dir = raw === '~' ? homedir() : raw.startsWith('~/') ? join(homedir(), raw.slice(2)) : raw; + if (dir === '' || !isAbsolute(dir)) { + throw new ConfigValidationError( + `Database '${name}' has azure_config_dir '${config.azure_config_dir}', which is not an absolute path`, + 'azure_config_dir', + name + ); + } + + dbConfig.azure_config_dir = dir; +} + /** * Parse and validate the optional 'authentication' key. * - * Only the SQL Server adapter can act on it, so accepting it elsewhere would - * mean silently ignoring a key the user believed changed how they authenticate. + * Only the SQL Server and PostgreSQL adapters can act on it, so accepting it + * elsewhere would mean silently ignoring a key the user believed changed how + * they authenticate. */ function parseAuthentication( name: string, @@ -331,9 +400,9 @@ function parseAuthentication( const mode = config.authentication.trim().toLowerCase(); - if (dbConfig.type !== 'mssql') { + if (!AZURE_CLI_TYPES.includes(dbConfig.type)) { throw new ConfigValidationError( - `Database '${name}' sets 'authentication' but that is only supported for type 'mssql'`, + `Database '${name}' sets 'authentication' but that is only supported for types 'mssql' and 'postgresql'`, 'authentication', name ); @@ -353,6 +422,16 @@ function parseAuthentication( // The adapter forces encryption on for token authentication. Accepting // encrypt=false here would mean quietly doing the opposite of what the file // says, so an explicit one is a startup error instead. + if (mode === 'azure-cli' && dbConfig.type !== 'mssql' && config.ssl !== undefined) { + if (!parseBool(config.ssl, 'ssl', name)) { + throw new ConfigValidationError( + `Database '${name}' sets ssl=false with authentication=azure-cli. ` + + 'An access token requires a verified, encrypted connection; remove ssl or set it to true', + 'ssl', + name + ); + } + } if (mode === 'azure-cli' && config.encrypt !== undefined) { if (!parseBool(config.encrypt, 'encrypt', name)) { throw new ConfigValidationError( @@ -383,8 +462,9 @@ function validateNetworkedDatabase( } parseAuthentication(name, config, dbConfig); parseAzureTenantId(name, config, dbConfig); + parseAzureConfigDir(name, config, dbConfig); - if (!config.username && !usesAzureCliAuth(dbConfig)) { + if (!config.username && needsUsername(dbConfig)) { throw new ConfigValidationError( `Database '${name}' missing required 'username' field`, 'username', diff --git a/src/utils/response-formatter.ts b/src/utils/response-formatter.ts index b9bc4f7..73b3740 100644 --- a/src/utils/response-formatter.ts +++ b/src/utils/response-formatter.ts @@ -3,6 +3,7 @@ * Pure functions for formatting query results and database summaries */ +import { describePrivileges } from '../database/privileges.js'; import type { QueryResult, DatabaseListItem, MCPToolResponse } from '../types/index.js'; /** @@ -111,6 +112,7 @@ export function formatDatabaseSummary(db: DatabaseListItem): string { summary += ` Security: SELECT-only mode (production safe)\n`; summary += ` Allows: SELECT, WITH, SHOW, EXPLAIN, DESCRIBE\n`; summary += ` Blocks: INSERT, UPDATE, DELETE, DROP, CREATE, ALTER\n`; + for (const line of describePrivileges(true, db.privileges)) summary += ` ${line}\n`; } else { summary += ` Security: Full access mode (use with caution)\n`; } diff --git a/tests/fixtures/pane-contract/connections.json b/tests/fixtures/pane-contract/connections.json index 8c3e38d..b2926ab 100644 --- a/tests/fixtures/pane-contract/connections.json +++ b/tests/fixtures/pane-contract/connections.json @@ -7,7 +7,13 @@ "ssl": false, "selectOnly": true, "mcpConfigurable": false, - "schemaCapturedAt": null + "schemaCapturedAt": null, + "role": { + "checkedAt": "2000-01-01T00:00:00.000Z", + "canWrite": false, + "principal": null, + "reasons": [] + } }, { "name": "writable", @@ -17,6 +23,7 @@ "ssl": false, "selectOnly": false, "mcpConfigurable": false, - "schemaCapturedAt": null + "schemaCapturedAt": null, + "role": null } ] diff --git a/tests/unit/adapters/adapter-factory.test.ts b/tests/unit/adapters/adapter-factory.test.ts index bd5e9be..7fde6fb 100644 --- a/tests/unit/adapters/adapter-factory.test.ts +++ b/tests/unit/adapters/adapter-factory.test.ts @@ -242,6 +242,19 @@ describe('AdapterFactory', () => { ).toEqual(['host', 'database', 'username', 'password']); }); + it('should drop only the password for postgresql with azure-cli auth', () => { + // The token is the password; the username is the Entra principal's name. + expect( + AdapterFactory.getRequiredFields('postgresql', { + type: 'postgresql', + authentication: 'azure-cli', + host: 'example.postgres.database.azure.com', + database: 'app', + username: 'argos-readers', + } as unknown as DatabaseConfig) + ).toEqual(['host', 'database', 'username']); + }); + it('should accept an azure-cli mssql config that has no username or password', () => { const result = AdapterFactory.validateConfig({ name: 'azure_db', diff --git a/tests/unit/adapters/postgresql-adapter.test.ts b/tests/unit/adapters/postgresql-adapter.test.ts index fd58784..54aff7f 100644 --- a/tests/unit/adapters/postgresql-adapter.test.ts +++ b/tests/unit/adapters/postgresql-adapter.test.ts @@ -34,7 +34,18 @@ jest.mock('pg', () => ({ })), })); +// Mock '@azure/identity': every getToken call answers a new token, as the CLI does once one expires. +const mockAzureCliCredentialCtor = jest.fn(); +const mockGetToken = jest.fn(); +jest.mock('@azure/identity', () => ({ + AzureCliCredential: jest.fn().mockImplementation(function (this: any, ...args: unknown[]) { + mockAzureCliCredentialCtor(...args); + this.getToken = mockGetToken; + }), +})); + import * as pg from 'pg'; +import { AZURE_POSTGRES_SCOPE } from '../../../src/database/adapters/postgresql.js'; // ============================================================================ // Test Suite @@ -919,4 +930,131 @@ describe('PostgreSQLAdapter', () => { expect(result).toEqual([]); }); }); + + describe('azure-cli authentication', () => { + const azureConfig = (extra: Partial = {}): DatabaseConfig => ({ + type: 'postgresql', + host: 'myserver.postgres.database.azure.com', + port: 5432, + database: 'app', + username: 'argos-readers', + authentication: 'azure-cli', + ...extra, + }); + const poolConfig = async (c: DatabaseConfig): Promise => { + await new PostgreSQLAdapter(c).connect(); + const calls = (pg.Pool as unknown as jest.Mock).mock.calls; + return calls[calls.length - 1][0] as pg.PoolConfig; + }; + + beforeEach(() => { + let n = 0; + mockGetToken.mockImplementation(async () => ({ + token: `token-${++n}`, + expiresOnTimestamp: 0, + })); + }); + + it('connects with the Entra principal as user and no password in the config', async () => { + const pool = await poolConfig(azureConfig()); + expect(pool.user).toBe('argos-readers'); + expect(typeof pool.password).toBe('function'); + }); + + it('fetches a fresh token from the Azure CLI for every new connection', async () => { + const pool = await poolConfig(azureConfig()); + const password = pool.password as () => Promise; + await expect(password()).resolves.toBe('token-1'); + await expect(password()).resolves.toBe('token-2'); + expect(mockGetToken).toHaveBeenCalledTimes(2); + expect(mockGetToken).toHaveBeenCalledWith(AZURE_POSTGRES_SCOPE); + expect(AZURE_POSTGRES_SCOPE).toBe('https://ossrdbms-aad.database.windows.net/.default'); + // One credential, built once. + expect(mockAzureCliCredentialCtor).toHaveBeenCalledTimes(1); + }); + + it('passes the configured tenant to AzureCliCredential', async () => { + const pool = await poolConfig( + azureConfig({ azure_tenant_id: 'd958da54-24bc-444a-981b-317de09e73ee' }) + ); + await (pool.password as () => Promise)(); + expect(mockAzureCliCredentialCtor).toHaveBeenCalledWith({ + tenantId: 'd958da54-24bc-444a-981b-317de09e73ee', + }); + }); + + it('forces TLS with certificate verification, whatever ssl and ssl_verify say', async () => { + expect((await poolConfig(azureConfig())).ssl).toEqual({ rejectUnauthorized: true }); + expect((await poolConfig(azureConfig({ ssl_verify: false }))).ssl).toEqual({ + rejectUnauthorized: true, + }); + expect((await poolConfig(azureConfig({ ssl: false }))).ssl).toEqual({ + rejectUnauthorized: true, + }); + }); + + it('through an SSH tunnel, checks the certificate against the database host', async () => { + const ssl = ( + await poolConfig( + azureConfig({ host: '127.0.0.1', tls_servername: 'myserver.postgres.database.azure.com' }) + ) + ).ssl as import('node:tls').ConnectionOptions; + expect(ssl).toMatchObject({ + rejectUnauthorized: true, + servername: 'myserver.postgres.database.azure.com', + }); + const cert = (name: string) => + ({ + subject: { CN: name }, + subjectaltname: `DNS:${name}`, + }) as unknown as import('node:tls').PeerCertificate; + expect( + ssl.checkServerIdentity!('127.0.0.1', cert('myserver.postgres.database.azure.com')) + ).toBeUndefined(); + expect(ssl.checkServerIdentity!('127.0.0.1', cert('attacker.example.com'))?.message).toMatch( + /does not match certificate's altnames/ + ); + }); + + it('does the same on the plain verified-TLS path', async () => { + const ssl = ( + await poolConfig({ ...config, ssl: true, host: '127.0.0.1', tls_servername: 'db.internal' }) + ).ssl as import('node:tls').ConnectionOptions; + expect(ssl).toMatchObject({ rejectUnauthorized: true, servername: 'db.internal' }); + expect( + ( + await poolConfig({ + ...config, + ssl: true, + ssl_verify: false, + tls_servername: 'db.internal', + }) + ).ssl + ).toEqual({ + rejectUnauthorized: false, + }); + }); + + it('refuses an empty token rather than sending no password', async () => { + mockGetToken.mockResolvedValueOnce(null); + const pool = await poolConfig(azureConfig()); + await expect((pool.password as () => Promise)()).rejects.toThrow('no access token'); + }); + + it('points at az login when the token could not be acquired', async () => { + const failure = Object.assign(new Error('Please run az login'), { + name: 'CredentialUnavailableError', + }); + mockPoolConnect.mockRejectedValueOnce(failure); + await expect(new PostgreSQLAdapter(azureConfig()).connect()).rejects.toThrow( + /Azure CLI authentication.*az login/ + ); + }); + + it('keeps the plain password path unchanged', async () => { + const pool = await poolConfig(config); + expect(pool.password).toBe('testpass'); + expect(mockGetToken).not.toHaveBeenCalled(); + }); + }); }); diff --git a/tests/unit/cli/pane-commands.test.ts b/tests/unit/cli/pane-commands.test.ts index b0d3dbf..995374f 100644 --- a/tests/unit/cli/pane-commands.test.ts +++ b/tests/unit/cli/pane-commands.test.ts @@ -6,6 +6,7 @@ import sqlite3 from 'sqlite3'; import { connections, runPaneCommand } from '../../../src/cli/pane-commands.js'; import { openCore } from '../../../src/cli/core.js'; import { PaneStore, dataDirFor } from '../../../src/pane/store.js'; +import { sqlitePrivileges } from '../../../src/database/privileges.js'; const FIXTURES = join(__dirname, '..', '..', 'fixtures', 'pane-contract'); const STAMP = '2000-01-01T00:00:00.000Z'; @@ -57,6 +58,10 @@ describe('pane commands', () => { }); it('lists connections with selectOnly as configured', async () => { + // The MCP server's role checks, as it records them; a full-access connection's is not shown. + const store = new PaneStore(dataDirFor(configPath)); + await store.recordRole('demo', { ...sqlitePrivileges(true), checkedAt: STAMP }); + await store.recordRole('writable', { ...sqlitePrivileges(false), checkedAt: STAMP }); const out = await runPaneCommand('connections', ['--config', configPath], schemas); expect(out.code).toBe(0); const list = out.json as any[]; @@ -67,8 +72,12 @@ describe('pane commands', () => { ssl: false, selectOnly: true, mcpConfigurable: false, + role: { checkedAt: STAMP, canWrite: false, principal: null, reasons: [] }, + }); + expect(list.find((c) => c.name === 'writable')).toMatchObject({ + selectOnly: false, + role: null, }); - expect(list.find((c) => c.name === 'writable').selectOnly).toBe(false); await mkdir(FIXTURES, { recursive: true }); await writeFile( join(FIXTURES, 'connections.json'), diff --git a/tests/unit/config-validation.test.ts b/tests/unit/config-validation.test.ts index 6824ad5..0352fd5 100644 --- a/tests/unit/config-validation.test.ts +++ b/tests/unit/config-validation.test.ts @@ -64,6 +64,29 @@ describe('validateDatabaseConfig - Azure CLI authentication', () => { expect(r.errors.some((e: any) => e.field === 'password')).toBe(true); }); + it('passes postgresql config with azure-cli auth, a username and no password', () => { + const r = validateDatabaseConfig({ + type: 'postgresql', + host: 'myserver.postgres.database.azure.com', + port: 5432, + database: 'db', + username: 'argos-readers', + authentication: 'azure-cli', + } as any); + expect(r.valid).toBe(true); + }); + + it('still requires the username for postgresql with azure-cli auth', () => { + const r = validateDatabaseConfig({ + type: 'postgresql', + host: 'myserver.postgres.database.azure.com', + port: 5432, + database: 'db', + authentication: 'azure-cli', + } as any); + expect(r.errors.map((e: any) => e.field)).toEqual(['user']); + }); + it('still requires username and password for mysql with azure-cli auth', () => { const r = validateDatabaseConfig({ ...base, diff --git a/tests/unit/connection-manager.test.ts b/tests/unit/connection-manager.test.ts index e22f6d8..aef53b6 100644 --- a/tests/unit/connection-manager.test.ts +++ b/tests/unit/connection-manager.test.ts @@ -657,6 +657,28 @@ describe('ConnectionManager', () => { await expect(connectionManager.getConnection('ssh_db')).rejects.toThrow(/SSH tunnel/); }); + test('points a tunnelled adapter at the tunnel, keeping the real host for TLS', async () => { + const config: DatabaseConfig = { + ...TestConfigFixtures.validPostgresConfig, + host: 'myserver.postgres.database.azure.com', + ssh_host: 'bastion.example.com', + ssh_username: 'jump', + ssh_password: 'x', + }; + const built: DatabaseConfig[] = []; + jest.spyOn(connectionManager as any, 'createAdapter').mockImplementation((c) => { + built.push(c as DatabaseConfig); + return MockDatabaseFactory.createPostgresAdapter(c as DatabaseConfig); + }); + connectionManager.registerDatabase('tunnelled', config); + await connectionManager.getConnection('tunnelled'); + expect(built.at(-1)).toMatchObject({ + host: '127.0.0.1', + port: 12345, + tls_servername: 'myserver.postgres.database.azure.com', + }); + }); + test('should not create SSH tunnel for sqlite even with ssh_host set', async () => { const mockAdapter = MockDatabaseFactory.createSqliteAdapter( TestConfigFixtures.validSqliteConfig @@ -1827,4 +1849,145 @@ describe('ConnectionManager', () => { expect(result).toEqual(mockResult); }); }); + + describe('privilege check', () => { + const WRITER = { + canWrite: true, + principal: 'dbo', + reasons: ['db_owner'], + notes: [], + checkedAt: '2026-10-30T00:00:00.000Z', + }; + const READER = { ...WRITER, canWrite: false, principal: 'reader', reasons: [] }; + const selectOnly = (extra: Partial = {}): DatabaseConfig => ({ + ...TestConfigFixtures.validPostgresConfig, + select_only: true, + ...extra, + }); + const withProbe = (config: DatabaseConfig, probe: () => Promise) => { + const adapter = MockDatabaseFactory.createPostgresAdapter(config); + const spy = jest.spyOn(adapter, 'probePrivileges').mockImplementation(probe as never); + jest.spyOn(connectionManager as any, 'createAdapter').mockReturnValue(adapter); + return spy; + }; + + test('checks a select_only connection once on connect and remembers the result', async () => { + const spy = withProbe(selectOnly(), async () => WRITER); + const seen: unknown[] = []; + connectionManager.on('privileges', (db: string, probe: unknown) => seen.push([db, probe])); + connectionManager.registerDatabase('ro', selectOnly()); + await connectionManager.getConnection('ro'); + await connectionManager.getConnection('ro'); + expect(spy).toHaveBeenCalledTimes(1); + expect(connectionManager.getPrivileges('ro')).toEqual(WRITER); + expect(seen).toEqual([['ro', WRITER]]); + }); + + test('does not check a connection that is not select_only', async () => { + const config = { ...selectOnly(), select_only: false }; + const spy = withProbe(config, async () => WRITER); + connectionManager.registerDatabase('rw', config); + await connectionManager.getConnection('rw'); + expect(spy).not.toHaveBeenCalled(); + expect(connectionManager.getPrivileges('rw')).toBeUndefined(); + }); + + test('keeps the connection when the check fails, and remembers the failure', async () => { + withProbe(selectOnly(), async () => { + throw new Error('permission denied for pg_roles'); + }); + connectionManager.registerDatabase('ro', selectOnly()); + await expect(connectionManager.getConnection('ro')).resolves.toBeDefined(); + expect(connectionManager.getPrivileges('ro')).toMatchObject({ + error: 'permission denied for pg_roles', + }); + }); + + test('require_readonly_role refuses a role that can write, and closes the connection', async () => { + const config = selectOnly({ require_readonly_role: true }); + withProbe(config, async () => WRITER); + connectionManager.registerDatabase('strict', config); + await expect(connectionManager.getConnection('strict')).rejects.toThrow( + /require_readonly_role is on and its role can write \(db_owner\)/ + ); + expect(connectionManager.isConnected('strict')).toBe(false); + }); + + test('require_readonly_role publishes nothing while the check runs, and disconnects on refusal', async () => { + const config = selectOnly({ require_readonly_role: true }); + let answer: (probe: unknown) => void = () => undefined; + const adapter = MockDatabaseFactory.createPostgresAdapter(config); + jest + .spyOn(adapter, 'probePrivileges') + .mockImplementation(() => new Promise((resolve) => (answer = resolve as never)) as never); + const disconnect = jest.spyOn(adapter, 'disconnect'); + jest.spyOn(connectionManager as any, 'createAdapter').mockReturnValue(adapter); + connectionManager.registerDatabase('strict', config); + + const probe = adapter.probePrivileges as jest.Mock; + const connecting = connectionManager.getConnection('strict'); + // Wait until the probe has been asked (the mock connect takes a moment). + for (let i = 0; i < 200 && probe.mock.calls.length === 0; i++) { + await new Promise((resolve) => setTimeout(resolve, 5)); + } + expect(probe).toHaveBeenCalledTimes(1); + // The probe is still pending: nothing may hand this connection out yet. + expect(connectionManager.isConnected('strict')).toBe(false); + expect((connectionManager as any).connections.has('strict')).toBe(false); + + answer(WRITER); + await expect(connecting).rejects.toThrow(/require_readonly_role/); + expect(disconnect).toHaveBeenCalledTimes(1); + expect((connectionManager as any).connections.has('strict')).toBe(false); + }); + + test('require_readonly_role refuses when the privileges could not be checked', async () => { + const config = selectOnly({ require_readonly_role: true }); + withProbe(config, async () => { + throw new Error('no privilege probe'); + }); + connectionManager.registerDatabase('strict', config); + await expect(connectionManager.getConnection('strict')).rejects.toThrow( + /could not be checked/ + ); + }); + + test('stores a failed check with the driver error sanitized', async () => { + withProbe(selectOnly(), async () => { + throw new Error('connect to postgres://admin:hunter2@db:5432/app failed, password=hunter2'); + }); + connectionManager.registerDatabase('ro', selectOnly()); + await connectionManager.getConnection('ro'); + const stored = JSON.stringify(connectionManager.getPrivileges('ro')); + expect(stored).not.toContain('hunter2'); + expect(stored).toContain(''); + }); + + test('require_readonly_role lets a reader in', async () => { + const config = selectOnly({ require_readonly_role: true }); + withProbe(config, async () => READER); + connectionManager.registerDatabase('strict', config); + await expect(connectionManager.getConnection('strict')).resolves.toBeDefined(); + }); + + test('forgets the check and says so when the database is unregistered', async () => { + withProbe(selectOnly(), async () => WRITER); + const gone: string[] = []; + connectionManager.on('unregistered', (db: string) => gone.push(db)); + connectionManager.registerDatabase('ro', selectOnly()); + await connectionManager.getConnection('ro'); + connectionManager.unregisterDatabase('ro'); + expect(connectionManager.getPrivileges('ro')).toBeUndefined(); + expect(gone).toEqual(['ro']); + }); + + test('checkPrivileges runs the probe again on an open connection', async () => { + const spy = withProbe(selectOnly(), async () => READER); + connectionManager.registerDatabase('ro', selectOnly()); + await connectionManager.getConnection('ro'); + spy.mockImplementation(async () => WRITER as never); + await expect(connectionManager.checkPrivileges('ro')).resolves.toEqual(WRITER); + expect(spy).toHaveBeenCalledTimes(2); + }); + }); }); diff --git a/tests/unit/database/azure-credential.test.ts b/tests/unit/database/azure-credential.test.ts new file mode 100644 index 0000000..d91384a --- /dev/null +++ b/tests/unit/database/azure-credential.test.ts @@ -0,0 +1,108 @@ +const mockExecFile = jest.fn(); +jest.mock('node:child_process', () => ({ + execFile: (...args: unknown[]) => mockExecFile(...args), +})); +const mockAzureCliCredentialCtor = jest.fn(); +jest.mock('@azure/identity', () => ({ + AzureCliCredential: jest.fn().mockImplementation(function (this: any, ...args: unknown[]) { + mockAzureCliCredentialCtor(...args); + }), +})); + +import { + AzureCliProfileCredential, + azureCliCredential, +} from '../../../src/database/azure-credential.js'; + +type Callback = (error: Error | null, stdout: string, stderr: string) => void; +const answer = (error: Error | null, stdout = '', stderr = '') => + mockExecFile.mockImplementationOnce((_file, _args, _options, callback: Callback) => + callback(error, stdout, stderr) + ); + +const PROFILE = '/home/me/.azure-claude-ro'; +const SCOPE = 'https://ossrdbms-aad.database.windows.net/.default'; + +describe('AzureCliProfileCredential', () => { + beforeEach(() => mockExecFile.mockReset()); + + it('runs az with AZURE_CONFIG_DIR set to its profile, for the scope as a resource', async () => { + answer(null, JSON.stringify({ accessToken: 'tok', expires_on: 1800000000 })); + const token = await new AzureCliProfileCredential(PROFILE).getToken(SCOPE); + + expect(token).toEqual({ token: 'tok', expiresOnTimestamp: 1800000000 * 1000 }); + const [file, args, options] = mockExecFile.mock.calls[0]; + expect(file).toBe('az'); + expect(args).toEqual([ + 'account', + 'get-access-token', + '--output', + 'json', + '--resource', + 'https://ossrdbms-aad.database.windows.net', + ]); + expect(options.env.AZURE_CONFIG_DIR).toBe(PROFILE); + // The rest of the environment (PATH above all) is kept. + expect(options.env.PATH).toBe(process.env.PATH); + }); + + it('leaves the server environment itself alone', async () => { + const before = process.env.AZURE_CONFIG_DIR; + answer(null, JSON.stringify({ accessToken: 'tok', expires_on: '1800000000' })); + await new AzureCliProfileCredential(PROFILE).getToken(SCOPE); + expect(process.env.AZURE_CONFIG_DIR).toBe(before); + }); + + it('passes the tenant and accepts the scope as an array', async () => { + answer(null, JSON.stringify({ accessToken: 'tok', expiresOn: '2026-10-30 12:00:00.000000' })); + const token = await new AzureCliProfileCredential( + PROFILE, + 'd958da54-24bc-444a-981b-317de09e73ee' + ).getToken(['https://database.windows.net/.default']); + expect(mockExecFile.mock.calls[0][1]).toEqual( + expect.arrayContaining([ + '--resource', + 'https://database.windows.net', + '--tenant', + 'd958da54-24bc-444a-981b-317de09e73ee', + ]) + ); + expect(Number.isFinite(token.expiresOnTimestamp)).toBe(true); + }); + + it('says which profile to sign in to when az gives no token', async () => { + answer(new Error('exit 1'), '', "ERROR: Please run 'az login' to setup account.\nmore"); + await expect(new AzureCliProfileCredential(PROFILE).getToken(SCOPE)).rejects.toMatchObject({ + name: 'CredentialUnavailableError', + message: `No token from the Azure CLI profile in ${PROFILE}: run AZURE_CONFIG_DIR="${PROFILE}" az login (ERROR: Please run 'az login' to setup account.)`, + }); + }); + + it('says when az is not installed', async () => { + answer(Object.assign(new Error('spawn az ENOENT'), { code: 'ENOENT' })); + await expect(new AzureCliProfileCredential(PROFILE).getToken(SCOPE)).rejects.toThrow( + 'not installed' + ); + }); + + it('refuses an answer without a token', async () => { + answer(null, JSON.stringify({ tokenType: 'Bearer' })); + await expect(new AzureCliProfileCredential(PROFILE).getToken(SCOPE)).rejects.toThrow( + 'no access token' + ); + answer(null, 'not json'); + await expect(new AzureCliProfileCredential(PROFILE).getToken(SCOPE)).rejects.toThrow('JSON'); + }); +}); + +describe('azureCliCredential', () => { + it('uses the database profile when azure_config_dir is set, else AzureCliCredential', async () => { + expect(await azureCliCredential({ azure_config_dir: PROFILE })).toBeInstanceOf( + AzureCliProfileCredential + ); + await azureCliCredential({ azure_tenant_id: 'd958da54-24bc-444a-981b-317de09e73ee' }); + expect(mockAzureCliCredentialCtor).toHaveBeenCalledWith({ + tenantId: 'd958da54-24bc-444a-981b-317de09e73ee', + }); + }); +}); diff --git a/tests/unit/database/privileges.test.ts b/tests/unit/database/privileges.test.ts new file mode 100644 index 0000000..96e9857 --- /dev/null +++ b/tests/unit/database/privileges.test.ts @@ -0,0 +1,217 @@ +import { + isPrivilegeReport, + mssqlPrivileges, + mysqlPrivileges, + postgresPrivileges, + privilegeWarning, + sqlitePrivileges, +} from '../../../src/database/privileges.js'; +import type { QueryResult } from '../../../src/types/database.js'; + +const rows = (...r: Record[]): QueryResult => ({ + rows: r, + rowCount: r.length, + fields: Object.keys(r[0] ?? {}), + truncated: false, + execution_time_ms: 1, +}); + +const MSSQL_READER = { + principal: 'reader@contoso.com', + db_owner: 0, + db_datawriter: 0, + db_ddladmin: 0, + sysadmin: null, + create_table: 0, + db_insert: 0, + db_update: 0, + db_delete: 0, + writable_tables: 0, +}; + +describe('mssqlPrivileges', () => { + it('reads a db_datareader as unable to write, with sysadmin NULL as on Azure SQL Database', () => { + const report = mssqlPrivileges(rows(MSSQL_READER)); + expect(report).toMatchObject({ canWrite: false, principal: 'reader@contoso.com', reasons: [] }); + }); + + it('reads the Entra admin, entering as dbo with db_owner, as able to write', () => { + const report = mssqlPrivileges( + rows({ ...MSSQL_READER, principal: 'dbo', db_owner: 1, create_table: 1, db_insert: 1 }) + ); + expect(report.canWrite).toBe(true); + expect(report.principal).toBe('dbo'); + // The roles imply the database grants; they are not listed twice. + expect(report.reasons).toEqual(['db_owner']); + }); + + it('reads dbo without db_owner membership as the database owner', () => { + expect(mssqlPrivileges(rows({ ...MSSQL_READER, principal: 'dbo' })).reasons).toEqual([ + 'database owner', + ]); + }); + + it('lists sysadmin, db_datawriter and db_ddladmin', () => { + const report = mssqlPrivileges( + rows({ ...MSSQL_READER, sysadmin: 1, db_datawriter: 1, db_ddladmin: true }) + ); + expect(report.reasons).toEqual(['sysadmin', 'db_datawriter', 'db_ddladmin']); + }); + + it('catches grants made outside the fixed roles', () => { + const report = mssqlPrivileges( + rows({ ...MSSQL_READER, db_delete: 1, create_table: 1, writable_tables: 3 }) + ); + expect(report.reasons).toEqual([ + 'DELETE on the database', + 'CREATE TABLE', + 'INSERT/UPDATE/DELETE on 3 tables', + ]); + }); + + it('refuses an empty result instead of calling it safe', () => { + expect(() => mssqlPrivileges(rows())).toThrow(/no row/); + }); +}); + +const PG_READER = { + principal: 'reader', + is_superuser: false, + server_roles: '', + writable_tables: '0', + create_schemas: '', + default_read_only: 'off', +}; + +describe('postgresPrivileges', () => { + it('reads a role with SELECT only as unable to write', () => { + expect(postgresPrivileges(rows(PG_READER))).toMatchObject({ + canWrite: false, + principal: 'reader', + reasons: [], + notes: [], + }); + }); + + it('reads a superuser and the server-file roles as able to write', () => { + const report = postgresPrivileges( + rows({ + ...PG_READER, + is_superuser: true, + server_roles: 'pg_execute_server_program,pg_write_server_files', + }) + ); + expect(report.canWrite).toBe(true); + expect(report.reasons).toEqual([ + 'superuser', + 'pg_execute_server_program', + 'pg_write_server_files', + ]); + }); + + it('counts writable tables (count(*) arrives as a string) and schemas it can create in', () => { + const report = postgresPrivileges( + rows({ ...PG_READER, writable_tables: '1', create_schemas: 'public' }) + ); + expect(report.reasons).toEqual([ + 'INSERT/UPDATE/DELETE/TRUNCATE on 1 table', + 'CREATE in schema public', + ]); + }); + + it('notes default_transaction_read_only without treating it as a boundary', () => { + const report = postgresPrivileges( + rows({ ...PG_READER, writable_tables: 4, default_read_only: 'on' }) + ); + expect(report.canWrite).toBe(true); + expect(report.notes).toEqual([ + 'default_transaction_read_only is on, but a session can turn it off', + ]); + }); +}); + +const grants = (user: string, ...g: string[]): QueryResult => + rows(...g.map((v) => ({ [`Grants for ${user}`]: v }))); + +describe('mysqlPrivileges', () => { + it('reads SELECT and SHOW VIEW as unable to write', () => { + const report = mysqlPrivileges( + grants( + 'reader@%', + 'GRANT USAGE ON *.* TO `reader`@`%`', + 'GRANT SELECT, SHOW VIEW ON `shop`.* TO `reader`@`%`' + ) + ); + expect(report).toMatchObject({ canWrite: false, principal: 'reader@%', reasons: [] }); + }); + + it('flags anything beyond SELECT, and FILE in particular', () => { + const report = mysqlPrivileges( + grants( + 'app@%', + 'GRANT FILE ON *.* TO `app`@`%`', + 'GRANT SELECT, INSERT, UPDATE ON `shop`.* TO `app`@`%`' + ) + ); + expect(report.canWrite).toBe(true); + expect(report.reasons).toEqual([ + 'FILE (reads and writes files on the server)', + 'INSERT on `shop`.*', + 'UPDATE on `shop`.*', + ]); + }); + + it('reads ALL PRIVILEGES and column grants with their own comma lists', () => { + const report = mysqlPrivileges( + grants( + 'root@localhost', + 'GRANT ALL PRIVILEGES ON *.* TO `root`@`localhost` WITH GRANT OPTION', + 'GRANT SELECT (id, name), UPDATE (name) ON `shop`.`users` TO `root`@`localhost`' + ) + ); + expect(report.reasons).toEqual(['ALL PRIVILEGES on *.*', 'UPDATE on `shop`.`users`']); + }); + + it('counts a role grant it cannot expand as able to write', () => { + const report = mysqlPrivileges( + grants( + 'reader@%', + 'GRANT SELECT ON `shop`.* TO `reader`@`%`', + 'GRANT `ro_role`@`%` TO `reader`@`%`' + ) + ); + expect(report.canWrite).toBe(true); + expect(report.reasons).toEqual(['role `ro_role`@`%` (its privileges are not checked)']); + }); +}); + +describe('sqlitePrivileges', () => { + it('reads a read-only file as unable to write, a read-write one as able', () => { + expect(sqlitePrivileges(true)).toMatchObject({ + canWrite: false, + reasons: [], + notes: ['the file is opened read-only'], + }); + expect(sqlitePrivileges(false)).toMatchObject({ + canWrite: true, + reasons: ['the file is opened read-write'], + }); + }); +}); + +describe('privilegeWarning', () => { + it('names the principal and the reasons, and says the filter is the only guard', () => { + const report = mssqlPrivileges(rows({ ...MSSQL_READER, principal: 'dbo', db_owner: 1 })); + expect(privilegeWarning(report)).toBe( + "select_only is on, but this connection can write as dbo (db_owner). Argos's filter is the only guard. " + + 'Connect as a read-only role.' + ); + }); + + it('says nothing for a reader, a failed probe or no probe', () => { + expect(privilegeWarning(mssqlPrivileges(rows(MSSQL_READER)))).toBeNull(); + expect(privilegeWarning({ error: 'permission denied', checkedAt: 'now' })).toBeNull(); + expect(privilegeWarning(undefined)).toBeNull(); + expect(isPrivilegeReport({ error: 'x', checkedAt: 'now' })).toBe(false); + }); +}); diff --git a/tests/unit/pane/store.test.ts b/tests/unit/pane/store.test.ts index c2054cd..6f3043a 100644 --- a/tests/unit/pane/store.test.ts +++ b/tests/unit/pane/store.test.ts @@ -187,6 +187,61 @@ describe('PaneStore', () => { expect((await stat(join(dir, '.argos', 'schema-checks.json'))).mode & 0o777).toBe(0o600); }); + it('records role checks per connection, a failed check with canWrite null', async () => { + expect(await store.roles()).toEqual({}); + await store.recordRole('az', { + canWrite: true, + principal: 'dbo', + reasons: ['db_owner'], + notes: ['ignored by the pane'], + checkedAt: 't1', + }); + await store.recordRole('pg', { error: 'permission denied', checkedAt: 't2' }); + const again = new PaneStore(join(dir, '.argos')); + expect(await again.roles()).toEqual({ + az: { checkedAt: 't1', canWrite: true, principal: 'dbo', reasons: ['db_owner'] }, + pg: { checkedAt: 't2', canWrite: null, principal: null, reasons: [] }, + }); + expect((await stat(join(dir, '.argos', 'roles.json'))).mode & 0o777).toBe(0o600); + }); + + it('keeps every role when checks finish together, and forgets one on request', async () => { + const reader = { canWrite: false, principal: null, reasons: [], notes: [], checkedAt: 't' }; + await Promise.all(['a', 'b', 'c', 'd', 'e'].map((db) => store.recordRole(db, reader))); + expect(Object.keys(await store.roles()).sort()).toEqual(['a', 'b', 'c', 'd', 'e']); + await store.forgetRole('c'); + await store.forgetRole('absent'); + expect(Object.keys(await store.roles()).sort()).toEqual(['a', 'b', 'd', 'e']); + }); + + it('reports a failed role write to its caller and goes on with the next', async () => { + const reader = { canWrite: false, principal: null, reasons: [], notes: [], checkedAt: 't' }; + const broken = store as unknown as { writeAtomic: (p: string, t: string) => Promise }; + const write = broken.writeAtomic.bind(store); + broken.writeAtomic = async () => { + throw new Error('disk full'); + }; + await expect(store.recordRole('a', reader)).rejects.toThrow('disk full'); + broken.writeAtomic = write; + await store.recordRole('b', reader); + expect(Object.keys(await store.roles())).toEqual(['b']); + }); + + it('leaves out a malformed role entry', async () => { + await store.recordRole('ok', { + canWrite: false, + principal: null, + reasons: [], + notes: [], + checkedAt: 't', + }); + const path = join(dir, '.argos', 'roles.json'); + const roles = JSON.parse(await readFile(path, 'utf8')); + roles.bad = { checkedAt: 't', canWrite: 'yes', principal: null, reasons: [] }; + await writeFile(path, JSON.stringify(roles)); + expect(Object.keys(await store.roles())).toEqual(['ok']); + }); + it('two processes appending 500 entries each yield 1000 parseable lines', async () => { const src = await readFile(join(__dirname, '../../../src/pane/store.ts'), 'utf8'); const js = transformSync(src, { diff --git a/tests/unit/security-bypass-regression.test.ts b/tests/unit/security-bypass-regression.test.ts new file mode 100644 index 0000000..f71523c --- /dev/null +++ b/tests/unit/security-bypass-regression.test.ts @@ -0,0 +1,163 @@ +/** + * The published read-only bypass families, pinned against SELECT-only mode. + * + * Sources: Maximilian Hildebrand, "read-only bypasses in 14 SQL MCP servers" + * (m10x.de, 2026-07-04), and AWS bulletin 2026-104 / CVE-2026-87911 (COPY ... TO + * PROGRAM through read-only validation). Every case here must be rejected. This + * filter is the second net: the database role is the boundary (see the privilege + * check in src/database/privileges.ts). + */ +import { SecurityManager } from '../../src/classes/SecurityManager.js'; + +type Dialect = 'postgresql' | 'mysql' | 'mssql' | 'sqlite'; +const ALL: Dialect[] = ['postgresql', 'mysql', 'mssql', 'sqlite']; + +/** [family, sql, dialects it must be rejected on] */ +const BYPASSES: Array<[string, string, Dialect[]]> = [ + // Stacked statements + ['stacked', 'SELECT 1; DELETE FROM t', ALL], + ['stacked', 'BEGIN TRANSACTION READ ONLY; SELECT 1; COMMIT; DELETE FROM t', ALL], + ['stacked without a semicolon (T-SQL)', 'SELECT 1 DELETE FROM t', ['mssql']], + + // Comments as whitespace, or hiding a second statement + ['comment as whitespace', 'DROP/**/TABLE t', ALL], + ['comment as whitespace', 'SELECT 1;/**/DELETE FROM t', ALL], + ['line comment hides a statement', 'SELECT 1 --\n; DELETE FROM t', ALL], + ['line comment hides a statement', 'SELECT 1 -- ; \n DELETE FROM t', ALL], + ['# comment hides a statement', 'SELECT 1 #\n; DELETE FROM t', ALL], + ['# comment hides a statement', "SELECT '#' ; DELETE FROM t", ALL], + ['nested block comment', '/* a /* b */ ; DROP TABLE users */ SELECT 1', ALL], + ['MySQL version comment', 'SELECT 1 /*!50000 ; DELETE FROM t */', ALL], + + // SET in every shape + ['SET', 'SET default_transaction_read_only = off', ALL], + ['SET', 'SET SESSION CHARACTERISTICS AS TRANSACTION READ WRITE', ALL], + ['SET', "SET PASSWORD = 'x'", ALL], + ['SET', "SET PASSWORD FOR 'root'@'%' = 'x'", ALL], + ['SET', 'SET GLOBAL max_connections = 1', ALL], + ['SET', 'SET IDENTITY_INSERT t ON', ALL], + ['SET', 'SELECT 1; SET GLOBAL read_only = 0', ALL], + + // Data-modifying CTEs + ['CTE DML', 'WITH x AS (DELETE FROM t RETURNING *) SELECT * FROM x', ALL], + ['CTE DML', 'WITH x AS (INSERT INTO t VALUES (1) RETURNING *) SELECT * FROM x', ALL], + ['CTE DML', 'WITH x AS (UPDATE t SET a = 1 RETURNING *) SELECT * FROM x', ALL], + ['CTE DML', 'WITH x AS (SELECT 1) DELETE FROM t', ALL], + ['CTE DML', 'WITH x AS (SELECT 1) MERGE INTO t USING x ON 1 = 1 WHEN MATCHED THEN DELETE', ALL], + + // SELECT ... INTO + ['SELECT INTO', 'SELECT * INTO new_table FROM t', ALL], + ['SELECT INTO', 'SELECT * INTO TEMP new_table FROM t', ALL], + ['SELECT INTO', "SELECT * FROM t INTO OUTFILE '/tmp/x'", ALL], + ['SELECT INTO', "SELECT * FROM t INTO DUMPFILE '/tmp/x'", ALL], + ['SELECT INTO', 'SELECT 1 INTO @v', ALL], + + // COPY (CVE-2026-87911) + ['COPY', "COPY (SELECT 1) TO PROGRAM 'id'", ALL], + ['COPY', "COPY t FROM PROGRAM 'curl attacker'", ALL], + ['COPY', "COPY t TO '/tmp/x'", ALL], + + // Side-effect functions inside a plain SELECT (PostgreSQL) + ['side-effect function', "SELECT set_config('default_transaction_read_only', 'off', false)", ALL], + ['side-effect function', "SELECT set_config('transaction_read_only', 'off', true)", ALL], + ['side-effect function', 'SELECT pg_terminate_backend(pid) FROM pg_stat_activity', ALL], + ['side-effect function', 'SELECT pg_cancel_backend(pid) FROM pg_stat_activity', ALL], + ['side-effect function', 'SELECT pg_reload_conf()', ALL], + ['side-effect function', "SELECT lo_export(16409, '/tmp/x')", ALL], + ['side-effect function', "SELECT lo_import('/etc/passwd')", ALL], + ['side-effect function', "SELECT lo_from_bytea(0, 'x')", ALL], + ['side-effect function', 'SELECT lo_unlink(16409)', ALL], + // lo_get reads; a write after it in the same statement is still caught. + ['side-effect function', 'SELECT lo_get(16409), lo_unlink(16409)', ALL], + ['side-effect function', "SELECT pg_read_file('/etc/passwd')", ALL], + ['side-effect function', "SELECT pg_read_binary_file('/etc/passwd')", ALL], + ['side-effect function', "SELECT pg_ls_dir('/')", ALL], + ['side-effect function', "SELECT pg_file_write('/tmp/x', 'y', false)", ALL], + ['side-effect function', "SELECT dblink_exec('dbname=app', 'DELETE FROM t')", ALL], + ['side-effect function', "SELECT * FROM dblink('dbname=app', 'SELECT 1') AS x(a int)", ALL], + ['side-effect function', "SELECT dblink_connect('c', 'dbname=app')", ALL], + // A sequence advance is a write that survives a rollback. + ['side-effect function', "SELECT nextval('seq')", ALL], + ['side-effect function', "SELECT setval('seq', 1)", ALL], + ['side-effect function', 'SELECT pg_sleep(100)', ALL], + + // SQL Server + ['SQL Server', "EXEC xp_cmdshell 'whoami'", ALL], + ['SQL Server', "EXECUTE xp_cmdshell 'whoami'", ALL], + ['SQL Server', "EXEC('DELETE FROM t')", ALL], + ['SQL Server', "SELECT 1 EXEC('DELETE FROM t')", ALL], + ['SQL Server', "SELECT * FROM OPENROWSET('SQLNCLI', 'Server=x;', 'SELECT 1')", ALL], + ['SQL Server', "SELECT * FROM OPENQUERY(linked, 'DELETE FROM t')", ALL], + ['SQL Server', "SELECT * FROM OPENDATASOURCE('SQLNCLI', 'Data Source=x').db.dbo.t", ALL], + ['SQL Server', "SELECT 1 WAITFOR DELAY '00:01:00'", ALL], + ['SQL Server', "sp_helpdesk_reset 'x'", ALL], + ['SQL Server', 'sp_help; DROP TABLE t', ALL], + + // MySQL + ['MySQL', 'SELECT SLEEP(100)', ALL], + ['MySQL', "SELECT BENCHMARK(100000000, MD5('x'))", ALL], + ['MySQL', "SELECT LOAD_FILE('/etc/passwd')", ALL], + ['MySQL', "LOAD DATA INFILE '/etc/passwd' INTO TABLE t", ALL], + ['MySQL', 'HANDLER t OPEN', ALL], + ['MySQL', 'DO SLEEP(100)', ALL], + + // Other lead commands that write or execute + ['lead command', 'DO $$ BEGIN DELETE FROM t; END $$', ALL], + ['lead command', 'PREPARE p AS DELETE FROM t', ALL], + ['lead command', 'CALL proc()', ALL], + ['lead command', 'LOCK TABLE t', ALL], + ['lead command', 'VACUUM', ALL], + ['lead command', 'ANALYZE t', ALL], + ['lead command', 'EXPLAIN ANALYZE DELETE FROM t', ALL], + ['lead command', 'EXPLAIN ANALYZE SELECT 1', ALL], + ['lead command', "ATTACH DATABASE '/tmp/x.db' AS x", ALL], + ['lead command', 'PRAGMA writable_schema = 1', ALL], + ['row locks', 'SELECT * FROM t FOR UPDATE', ALL], + + // Case and Unicode tricks + ['case', 'dElEtE FROM t', ALL], + ['case', 'SeLeCt 1; dElEtE FROM t', ALL], + ['case', 'WITH x AS (dElEtE FROM t RETURNING *) SELECT * FROM x', ALL], + ['unicode', 'DELETE FROM t', ALL], + ['unicode', 'SELECT 1; DELETE FROM t', ALL], + ['unicode', 'SELECT 1;​DELETE FROM t', ALL], + ['unicode', 'WITH x AS (DEL​ETE FROM t RETURNING *) SELECT * FROM x', ALL], + ['unicode', 'DEL​ETE FROM t', ALL], + ['unicode', 'SELECT 1 ; DELETE FROM t', ALL], + ['unicode', 'SELECT 1;
DELETE FROM t', ALL], +]; + +/** Reads that must keep working, so the fixes do not overreach. */ +const READS: Array<[string, Dialect[]]> = [ + ['SELECT 1', ALL], + ['SELECT 1;', ALL], + ["SELECT 'DELETE FROM t' AS text", ALL], + ['SELECT description, setting FROM t', ALL], + ['SELECT currval_view, next_value FROM t', ALL], + ["SELECT current_setting('default_transaction_read_only')", ALL], + ['SELECT pid, state FROM pg_stat_activity', ALL], + ['SELECT lo_get(24528)', ALL], + ["SELECT 'naïve café' AS word", ALL], + ['SELECT "Straße" FROM t', ALL], + ['WITH x AS (SELECT 1 AS a) SELECT a FROM x', ALL], + ['SHOW TABLES', ['mysql']], + ['EXPLAIN SELECT * FROM t', ALL], +]; + +describe('SELECT-only mode against the published bypass families', () => { + const security = new SecurityManager(); + + const cases = BYPASSES.flatMap(([family, sql, dialects]) => + dialects.map((d) => [family, d, sql] as const) + ); + test.each(cases)('%s on %s is rejected: %j', (_family, dialect, sql) => { + const result = security.validateSelectOnlyQuery(sql, dialect); + expect(result.allowed).toBe(false); + }); + + const reads = READS.flatMap(([sql, dialects]) => dialects.map((d) => [d, sql] as const)); + test.each(reads)('a read on %s still passes: %j', (dialect, sql) => { + const result = security.validateSelectOnlyQuery(sql, dialect); + expect(result).toMatchObject({ allowed: true }); + }); +}); diff --git a/tests/unit/tools/schema-handlers.test.ts b/tests/unit/tools/schema-handlers.test.ts index 6feb45a..7c4b745 100644 --- a/tests/unit/tools/schema-handlers.test.ts +++ b/tests/unit/tools/schema-handlers.test.ts @@ -37,6 +37,8 @@ function createMockContext( executeQuery: jest.fn(), executeBatch: jest.fn(), analyzePerformance: jest.fn(), + getPrivileges: jest.fn().mockReturnValue(undefined), + checkPrivileges: jest.fn().mockResolvedValue(undefined), } as any, securityManager: { validateSelectOnlyQuery: jest.fn(), @@ -476,4 +478,85 @@ describe('schema-handlers', () => { expect(ctx.logger.info).toHaveBeenCalledWith(expect.stringContaining('SSH tunnel')); }); }); + + describe('privilege check', () => { + const WRITER = { + canWrite: true, + principal: 'dbo', + reasons: ['db_owner'], + notes: [], + checkedAt: '2026-10-30T00:00:00.000Z', + }; + const connected = (ctx: ToolHandlerContext) => { + (ctx.connectionManager.getConnection as jest.Mock).mockResolvedValue({ isConnected: true }); + (ctx.connectionManager.executeQuery as jest.Mock).mockResolvedValue({ rows: [{ 1: 1 }] }); + }; + + it('sql_test_connection warns when a select_only connection can write', async () => { + const ctx = createMockContext({ + az: { type: 'mssql', host: 'h', select_only: true } as DatabaseConfig, + }); + connected(ctx); + (ctx.connectionManager.checkPrivileges as jest.Mock).mockResolvedValue(WRITER); + + const text = (await handleTestConnection(ctx, { database: 'az' })).content[0].text; + + expect(ctx.connectionManager.checkPrivileges).toHaveBeenCalledWith('az'); + expect(text).toContain( + 'Warning: select_only is on, but this connection can write as dbo (db_owner).' + ); + expect(text).toContain("Argos's filter is the only guard."); + }); + + it('sql_test_connection says when the role is read-only, and when it could not be checked', async () => { + const ctx = createMockContext({ + ro: { type: 'postgresql', host: 'h', select_only: true } as DatabaseConfig, + }); + connected(ctx); + (ctx.connectionManager.checkPrivileges as jest.Mock).mockResolvedValue({ + ...WRITER, + canWrite: false, + principal: 'reader', + reasons: [], + }); + expect((await handleTestConnection(ctx, { database: 'ro' })).content[0].text).toContain( + 'Database role: read-only (reader)' + ); + + (ctx.connectionManager.checkPrivileges as jest.Mock).mockRejectedValueOnce( + new Error('password=hunter2 rejected') + ); + const leaked = (await handleTestConnection(ctx, { database: 'ro' })).content[0].text; + expect(leaked).toContain('could not be checked (password=[REDACTED] rejected)'); + expect(leaked).not.toContain('hunter2'); + + (ctx.connectionManager.checkPrivileges as jest.Mock).mockRejectedValue( + new Error('timed out') + ); + const text = (await handleTestConnection(ctx, { database: 'ro' })).content[0].text; + expect(text).toContain('Connection successful'); + expect(text).toContain('Database role: could not be checked (timed out)'); + }); + + it('sql_test_connection says nothing about the role of a full-access database', async () => { + const ctx = createMockContext({ + rw: { type: 'postgresql', host: 'h', select_only: false } as DatabaseConfig, + }); + connected(ctx); + expect((await handleTestConnection(ctx, { database: 'rw' })).content[0].text).not.toContain( + 'Database role' + ); + }); + + it('sql_list_databases hands the last check to the summary', async () => { + const ctx = createMockContext({ + az: { type: 'mssql', host: 'h', select_only: true } as DatabaseConfig, + }); + (ctx.connectionManager.getPrivileges as jest.Mock).mockReturnValue(WRITER); + await handleListDatabases(ctx); + expect(formatDatabaseSummary).toHaveBeenCalledWith( + expect.objectContaining({ name: 'az', privileges: WRITER }) + ); + }); + }); }); diff --git a/tests/unit/utils/config.test.ts b/tests/unit/utils/config.test.ts index bdc7b27..cc39446 100644 --- a/tests/unit/utils/config.test.ts +++ b/tests/unit/utils/config.test.ts @@ -26,6 +26,7 @@ jest.mock('fs', () => ({ jest.mock('path', () => ({ join: jest.fn((...args: string[]) => args.join('/')), dirname: jest.fn((p) => p.substring(0, p.lastIndexOf('/')) || '/'), + isAbsolute: jest.fn((p: string) => p.startsWith('/')), })); jest.mock('ini', () => ({ @@ -296,6 +297,101 @@ describe('config', () => { ).toThrow('authentication'); }); + it('should accept azure-cli authentication for postgresql with a username and no password', () => { + for (const type of ['postgresql', 'postgres']) { + const config = parseDatabaseConfig('db', { + type, + host: 'myserver.postgres.database.azure.com', + database: 'db', + username: 'argos-readers', + authentication: 'azure-cli', + azure_tenant_id: 'd958da54-24bc-444a-981b-317de09e73ee', + }); + expect(config.authentication).toBe('azure-cli'); + expect(config.username).toBe('argos-readers'); + expect(config.password).toBeUndefined(); + } + }); + + it('should require the Entra principal as username for postgresql azure-cli', () => { + expect(() => + parseDatabaseConfig('db', { + type: 'postgresql', + host: 'myserver.postgres.database.azure.com', + database: 'db', + authentication: 'azure-cli', + }) + ).toThrow("missing required 'username'"); + }); + + it('should reject ssl=false alongside azure-cli authentication on postgresql', () => { + expect(() => + parseDatabaseConfig('db', { + type: 'postgresql', + host: 'myserver.postgres.database.azure.com', + database: 'db', + username: 'u', + authentication: 'azure-cli', + ssl: 'false', + }) + ).toThrow('ssl=false'); + }); + + it('should reject azure-cli authentication and azure_tenant_id for sqlite', () => { + expect(() => + parseDatabaseConfig('db', { + type: 'sqlite', + file: '/tmp/x.db', + authentication: 'azure-cli', + }) + ).toThrow("only supported for types 'mssql' and 'postgresql'"); + expect(() => + parseDatabaseConfig('db', { + type: 'sqlite', + file: '/tmp/x.db', + azure_tenant_id: 'd958da54-24bc-444a-981b-317de09e73ee', + }) + ).toThrow('azure_tenant_id'); + }); + + it('should accept azure_config_dir with azure-cli and expand a leading ~', () => { + const config = parseDatabaseConfig('db', { + type: 'mssql', + host: 'myserver.database.windows.net', + database: 'db', + authentication: 'azure-cli', + azure_config_dir: '~/.azure-claude-ro', + }); + expect(config.azure_config_dir).toBe(`${require('os').homedir()}/.azure-claude-ro`); + }); + + it('should reject azure_config_dir without azure-cli, or as a relative path', () => { + expect(() => + parseDatabaseConfig('db', { + type: 'postgresql', + host: 'h', + username: 'u', + azure_config_dir: '/home/me/.azure-ro', + }) + ).toThrow('requires authentication=azure-cli'); + expect(() => + parseDatabaseConfig('db', { + type: 'postgresql', + host: 'h', + username: 'u', + authentication: 'azure-cli', + azure_config_dir: '.azure-ro', + }) + ).toThrow('not an absolute path'); + expect(() => + parseDatabaseConfig('db', { + type: 'sqlite', + file: '/tmp/x.db', + azure_config_dir: '/home/me/.azure-ro', + }) + ).toThrow('azure_config_dir'); + }); + it('should reject an unknown authentication value', () => { expect(() => parseDatabaseConfig('db', { diff --git a/tests/unit/utils/response-formatter.test.ts b/tests/unit/utils/response-formatter.test.ts index 70b1c88..61e2710 100644 --- a/tests/unit/utils/response-formatter.test.ts +++ b/tests/unit/utils/response-formatter.test.ts @@ -584,6 +584,41 @@ describe('response-formatter', () => { expect(result).toContain('INSERT, UPDATE, DELETE, DROP, CREATE, ALTER'); }); + it('says the database role has not been checked before Argos connects', () => { + const db: DatabaseListItem = { + name: 'mydb', + type: 'mssql', + ssh_enabled: false, + ssl_enabled: false, + select_only_mode: true, + mcp_configurable: false, + schema_cached: false, + }; + expect(formatDatabaseSummary(db)).toContain('Database role: not checked yet'); + }); + + it('warns under SELECT-only when the role can write', () => { + const db: DatabaseListItem = { + name: 'mydb', + type: 'mssql', + ssh_enabled: false, + ssl_enabled: false, + select_only_mode: true, + mcp_configurable: false, + schema_cached: false, + privileges: { + canWrite: true, + principal: 'dbo', + reasons: ['db_owner'], + notes: [], + checkedAt: 'now', + }, + }; + expect(formatDatabaseSummary(db)).toContain( + ' Warning: select_only is on, but this connection can write as dbo (db_owner).' + ); + }); + it('should show MCP configurable when true', () => { const db: DatabaseListItem = { name: 'mydb',