> ## Documentation Index
> Fetch the complete documentation index at: https://docs.oasm.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Attack Surface Query engine

> How an ASQ request becomes safe SQL: schema validation, the resource catalog, compiled tenant scope, read-only execution, cost gates, keyset cursors, report mode and pre-computed rollups

[Attack Surface Query](https://docs.oasm.io/attack-surface-query/overview.md) (ASQ) lets the console, the REST API, saved reports, the [Security Agent](https://docs.oasm.io/architecture/ai-agent.md) and MCP clients ask arbitrary questions of the inventory in one JSON language. Letting an untrusted caller — including a language model — compose queries over a multi-tenant database is only safe if the engine, not the caller, decides what SQL runs. This page explains how it does that.

The query language itself is documented in the [ASQ guide](https://docs.oasm.io/attack-surface-query/query-structure.md).

```mermaid theme={null}
flowchart LR
    In["JSON batch<br/>console, REST, agent, MCP, report"] --> P["Params<br/>saved-query defaults"]
    P --> S["Schema<br/>strict shape"]
    S --> V["Validator<br/>catalog paths, operators,<br/>limits, permissions"]
    V --> C["Static cost"]
    C --> Pl["Planner<br/>tenant term + joins"]
    Pl --> Pre["EXPLAIN gate<br/>interactive only"]
    Pre --> X["Read-only unit<br/>timeout, RLS role"]
    X --> R["Result shaper<br/>cursors, truncation"]
```

## From JSON to SQL

A request is a batch of named queries. Each one passes through the same stages, and validation, permission and static-cost failures reject the whole batch before any SQL runs:

1. **Parameters.** For saved queries, `{ "$param" }` markers are replaced on the JSON itself — only in value, limit and time positions — so parameters are validated exactly like literals and never reach SQL text.
2. **Schema.** A strict schema checks the shape. Unknown keys are refused anywhere, including any attempt to pass a `workspaceId`.
3. **Validation.** Every field path is resolved against the **catalog** (with "did you mean" hints), every operator is checked against the field's type, and every limit is checked against the caller's budget. The caller's permissions decide which resources they may query.
4. **Static cost.** A cost estimate from the query's shape (includes, relation tests, unindexed searches) refuses obviously expensive requests early, with hints on how to narrow them.
5. **Planning.** The planner builds the SQL: list or aggregate, capped totals, includes as lateral subqueries, relation tests as `EXISTS` or `COUNT` subqueries.

### The catalog

The catalog declares every resource — targets, hosts, services, HTTP responses, technologies, TLS certificates, URLs, IPs, DNS records, findings, rollups — with its fields, the SQL fragment behind each field, and the relations between resources. **Only catalog names reach SQL; every value travels as a bound parameter.** A caller can never name a table, a column or a function.

The catalog is checked when the core API starts: a fragment that uses an undeclared alias, or a resource without a valid relation, stops the boot. What clients and the agent see from it (`describe`) never exposes table names or SQL.

## Tenant scope is compiled, never supplied

The workspace id comes from the permission check or from the agent's run, never from the query. The planner writes it into the SQL as its own term:

* every statement's `WHERE` starts with the root resource's tenant term;
* the caller's filter, the time window, the project scope and the cursor are each **separate, parenthesized `AND` terms**, so an `or` or a `not` in the caller's filter cannot escape the tenant term;
* every join, include, `EXISTS` and `COUNT` subquery re-applies the child's tenant term.

The engine's test suite asserts this for every resource, every field, every operator (including negated ones) and every relation quantifier.

Underneath the compiler, the database enforces the same boundary. When the `asq_reader` role exists, each query runs as that role with the workspace set on the transaction, and row-level security policies hide every other workspace's rows. See [Tenancy](https://docs.oasm.io/architecture/tenancy.md#scoping-in-the-database).

## Execution

* **Read-only units.** Each query runs in its own `BEGIN … READ ONLY` transaction with a `statement_timeout`, and is always rolled back. A batch that asks for a consistent view runs in one `REPEATABLE READ` unit instead.
* **EXPLAIN gate.** Interactive queries are first explained by PostgreSQL; a plan whose estimated cost is above the caller's ceiling, or a bounded sort that would sort too many rows, is refused before it runs.
* **Bounded concurrency.** Each core API process runs at most three ASQ units at a time. A query that waits more than two seconds for a slot gets a `BUSY` error instead of piling up.
* **Errors stay inside.** One query's runtime failure is its own `{ error }` result; the others in the batch still return. Database errors are mapped to ASQ error codes, never passed through.

Budgets differ by caller. The agent gets tighter limits than the console — fewer queries per batch, smaller pages, a lower planner-cost ceiling and a much smaller response size — because its results go into a model's context. See [Paging and limits](https://docs.oasm.io/attack-surface-query/paging-and-limits.md).

## Paging

Lists are paged with **keyset cursors**, not offsets: the cursor encodes the sort key of the last row, so deep pages cost the same as the first one and concurrent inserts do not shift results. Cursors are signed with an HMAC and bound to the query they came from, so a cursor cannot be edited or replayed against a different query.

## Report mode

[Saved queries](https://docs.oasm.io/attack-surface-query/saved-queries-and-reports.md) can run as reports. A report is queued on BullMQ and executed in the background with report budgets, and its result is kept for an hour. When a read replica is configured (`ASQ_READ_REPLICA_URL`), report mode runs there, keeping heavy reporting off the primary database.

## Rollups

Distributions that every dashboard asks for — services per port, technologies, status codes and similar — are pre-computed per workspace every 15 minutes over the latest HTTP response of each service, and exposed as a queryable resource. A chart over a large inventory reads a few hundred rollup rows instead of scanning millions of responses.

## Related

> [card] [Attack Surface Query](https://docs.oasm.io/attack-surface-query/overview.md)
>
> The query language and what you can ask

> [card] [ASQ for the AI agent and MCP](https://docs.oasm.io/attack-surface-query/ai-agent-and-mcp.md)
>
> How the agent learns and uses ASQ

> [card] [Tenancy and access control](https://docs.oasm.io/architecture/tenancy.md)
>
> The layers of the workspace boundary

> [card] [Data model](https://docs.oasm.io/architecture/data-model.md)
>
> The tables ASQ resources map onto


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.