From a765872a46c666267b9175cf3d98ef52170b25e3 Mon Sep 17 00:00:00 2001 From: Juan Castillo Date: Fri, 27 Nov 2026 06:51:22 -0500 Subject: [PATCH 1/4] Finish the .NET packaging, CI matrix, Node recipes CI and embedded-engine docs (#74-#79) Co-Authored-By: Claude Opus 5.5 --- .github/workflows/dotnet-client.yml | 120 +++++++++++++++++- .github/workflows/recipes.yml | 44 +++++++ .github/workflows/release.yml | 56 ++++++-- CHANGELOG.md | 9 ++ README.es.md | 10 +- README.md | 10 +- clients/dotnet/.gitignore | 1 + clients/dotnet/Directory.Build.props | 12 ++ clients/dotnet/README.md | 4 + clients/dotnet/smoke/Dockerfile | 7 + clients/dotnet/smoke/Program.cs | 13 ++ clients/dotnet/smoke/Smoke.csproj | 16 +++ clients/dotnet/smoke/nuget.config | 7 + .../SqlGuardLlm.EntityFrameworkCore.csproj | 1 - .../SqlGuardLlm.Extensions.csproj | 1 - .../SqlGuardLlm.SemanticKernel.csproj | 1 - .../dotnet/src/SqlGuardLlm/SqlGuardLlm.csproj | 17 +-- clients/node/src/local.ts | 11 +- clients/node/test/local.test.ts | 16 +++ docs/RECIPES.md | 2 +- docs/es/guide-dotnet.md | 86 ++++++------- docs/es/guide-node.md | 76 ++++++----- docs/es/packages.md | 6 +- docs/es/quickstart.md | 2 +- docs/guide-dotnet.md | 87 ++++++------- docs/guide-node.md | 78 ++++++------ docs/packages.md | 6 +- docs/quickstart.md | 2 +- examples/node/run.mjs | 4 +- examples/node/test/recipes.test.mjs | 54 +++++++- 30 files changed, 536 insertions(+), 223 deletions(-) create mode 100644 clients/dotnet/Directory.Build.props create mode 100644 clients/dotnet/smoke/Dockerfile create mode 100644 clients/dotnet/smoke/Program.cs create mode 100644 clients/dotnet/smoke/Smoke.csproj create mode 100644 clients/dotnet/smoke/nuget.config diff --git a/.github/workflows/dotnet-client.yml b/.github/workflows/dotnet-client.yml index 65593f6..4d69a7c 100644 --- a/.github/workflows/dotnet-client.yml +++ b/.github/workflows/dotnet-client.yml @@ -3,26 +3,132 @@ name: dotnet-client on: push: branches: [main] - paths: ["clients/dotnet/**", ".github/workflows/dotnet-client.yml"] + paths: + - "clients/dotnet/**" + - "examples/dotnet/**" + - "scripts/build-engine.py" + - "scripts/engine_main.py" + - ".github/workflows/dotnet-client.yml" pull_request: - paths: ["clients/dotnet/**", ".github/workflows/dotnet-client.yml"] + paths: + - "clients/dotnet/**" + - "examples/dotnet/**" + - "scripts/build-engine.py" + - "scripts/engine_main.py" + - ".github/workflows/dotnet-client.yml" permissions: contents: read jobs: + # Unit tests and the whole conformance corpus, in remote mode and in local mode (the engine over stdio), on the + # three operating systems. SQLGUARD_REQUIRE_CONFORMANCE makes a missing engine a failure instead of a skip. test: - runs-on: ubuntu-latest - defaults: - run: - working-directory: clients/dotnet + name: test (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + env: + SQLGUARD_REQUIRE_CONFORMANCE: "1" steps: - uses: actions/checkout@v4 + - uses: astral-sh/setup-uv@v6 + with: + python-version: "3.12" - uses: actions/setup-dotnet@v4 with: dotnet-version: | 8.0.x 10.0.x + - name: Python environment of the engine and the server (warms uv so the tests do not time out on it) + run: uv sync --locked --extra serve - run: dotnet build -c Release + working-directory: clients/dotnet - run: dotnet test -c Release --no-build - - run: dotnet pack src/SqlGuardLlm -c Release -o out + working-directory: clients/dotnet + + # The package as a user gets it: the engine of this platform is built, staged, packed, and then a consumer project + # restores the PACKED package and runs with `dotnet run`, `dotnet publish -r ` (framework-dependent, then + # self-contained single-file, then trimmed, then Native AOT, each with trimming and AOT warnings as errors), and, on + # Linux, in a container image with no .NET installed. The SHA-256 check is exercised by tampering with a file. + package: + name: package (${{ matrix.rid }}) + runs-on: ${{ matrix.os }} + timeout-minutes: 45 + strategy: + fail-fast: false + matrix: + include: + - { os: ubuntu-24.04, rid: linux-x64, platform: linux-x64 } + - { os: macos-15, rid: osx-arm64, platform: macos-arm64 } + - { os: windows-2022, rid: win-x64, platform: windows-x64 } + defaults: + run: + shell: bash + env: + WARNINGS: "IL2026;IL2046;IL2057;IL2060;IL2062;IL2067;IL2070;IL2072;IL2075;IL2087;IL2091;IL3050;IL3051;IL3053" + steps: + - uses: actions/checkout@v4 + - uses: astral-sh/setup-uv@v6 + with: + python-version: "3.12" + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: | + 8.0.x + 10.0.x + - name: Native AOT toolchain (Linux) + if: startsWith(matrix.rid, 'linux') + run: sudo apt-get update && sudo apt-get install -y clang zlib1g-dev + - name: Build the engine of this platform (PyInstaller one-dir, as in engine-binaries.yml) + run: | + uv run --isolated --no-dev --with "pyinstaller==6.22.3" python scripts/build-engine.py --out dist-engine + mkdir -p "engines/${{ matrix.platform }}" + cp -R "dist-engine/sqlguardllm-engine-${{ matrix.platform }}" "engines/${{ matrix.platform }}/" + - name: Stage the engine and pack the four packages + run: | + set -e + V=$(sed -nE 's#.*(.*).*#\1#p' clients/dotnet/Directory.Build.props) + python3 clients/dotnet/build/stage-engines.py --engines engines --platform "${{ matrix.platform }}" + for p in SqlGuardLlm SqlGuardLlm.Extensions SqlGuardLlm.EntityFrameworkCore SqlGuardLlm.SemanticKernel; do + dotnet pack "clients/dotnet/src/$p" -c Release -o clients/dotnet/out + done + ls -l clients/dotnet/out + python3 clients/dotnet/build/stage-engines.py --check-nupkg clients/dotnet/out/SqlGuardLlm.$V.nupkg --allow-partial + # the symbols package exists and SourceLink points at this commit + ls clients/dotnet/out/SqlGuardLlm.$V.snupkg + unzip -p clients/dotnet/out/SqlGuardLlm.$V.nupkg SqlGuardLlm.nuspec | grep -q "commit=\"$GITHUB_SHA\"" + - name: dotnet run, framework-dependent publish, self-contained single-file publish + run: | + set -e + V=$(sed -nE 's#.*(.*).*#\1#p' clients/dotnet/Directory.Build.props) + echo "SQLGUARD_PKG_VERSION=$V" >> "$GITHUB_ENV" + S=clients/dotnet/smoke + dotnet run --project $S -c Release -p:SqlGuardLlmVersion=$V + dotnet publish $S -c Release -r ${{ matrix.rid }} --no-self-contained -p:SqlGuardLlmVersion=$V -o out-fdd + ./out-fdd/Smoke + dotnet publish $S -c Release -r ${{ matrix.rid }} --self-contained -p:PublishSingleFile=true -p:SqlGuardLlmVersion=$V -o out-single + ./out-single/Smoke + - name: A tampered engine file refuses to start + run: | + set -e + echo x >> out-single/sqlguardllm-engine/_internal/base_library.zip + if ./out-single/Smoke > tamper.txt 2>&1; then echo "tampered engine started"; exit 1; fi + cat tamper.txt; grep -q "SHA-256 mismatch" tamper.txt + - name: Trimmed and Native AOT publish, warnings as errors + run: | + set -e + S=clients/dotnet/smoke; V=$SQLGUARD_PKG_VERSION + dotnet publish $S -c Release -r ${{ matrix.rid }} --self-contained -p:PublishTrimmed=true -p:TrimmerSingleWarn=false "-p:WarningsAsErrors=$WARNINGS" -p:SqlGuardLlmVersion=$V -o out-trim + ./out-trim/Smoke + dotnet publish $S -c Release -r ${{ matrix.rid }} -p:PublishAot=true "-p:WarningsAsErrors=$WARNINGS" -p:SqlGuardLlmVersion=$V -o out-aot + ./out-aot/Smoke + - name: Linux container image (no .NET inside) + if: startsWith(matrix.rid, 'linux') + run: | + set -e + dotnet publish clients/dotnet/smoke -c Release -r ${{ matrix.rid }} --self-contained -p:PublishSingleFile=true -p:SqlGuardLlmVersion=$SQLGUARD_PKG_VERSION -o out-container + docker build -f clients/dotnet/smoke/Dockerfile -t sqlguard-smoke out-container + docker run --rm sqlguard-smoke diff --git a/.github/workflows/recipes.yml b/.github/workflows/recipes.yml index b03d8cc..00d6f26 100644 --- a/.github/workflows/recipes.yml +++ b/.github/workflows/recipes.yml @@ -38,3 +38,47 @@ jobs: --with "llama-index-core>=0.14,<0.15" --with "vanna>=2.0,<2.1" python -m pytest tests/test_examples.py -W ignore::DeprecationWarning + + # The Node.js recipes (examples/node: LangChain.js, Vercel AI SDK, pg, mysql2, Prisma), with the real engine in local + # mode, executing on SQLite (node:sqlite) and on a PostgreSQL 16 service container. + node-recipes: + name: Node.js recipes + runs-on: ubuntu-latest + services: + postgres: + image: postgres:16 + env: + POSTGRES_PASSWORD: postgres # throwaway container of this job, not a secret + ports: ["5432:5432"] + options: >- + --health-cmd "pg_isready -U postgres" --health-interval 5s --health-timeout 5s --health-retries 10 + steps: + - uses: actions/checkout@v4 + - uses: astral-sh/setup-uv@v6 + with: + python-version: "3.12" + enable-cache: true + - uses: actions/setup-node@v4 + with: + node-version: "24" + - name: Engine from this checkout + run: uv sync --locked + - name: Build the Node client the recipes import + working-directory: clients/node + run: | + npm ci + npm run build + - name: Recipes (a missing framework fails instead of skipping) + working-directory: examples/node + env: + SQLGUARDLLM_RECIPES: "1" + SQLGUARD_ENGINE_CMD: uv run --project ${{ github.workspace }} sqlguardllm engine --stdio + DATABASE_URL: postgres://postgres:postgres@localhost:5432/postgres + run: | + npm install + npm test + - name: The runnable demo (npm start) with the real engine, on SQLite + working-directory: examples/node + env: + SQLGUARD_ENGINE_CMD: uv run --project ${{ github.workspace }} sqlguardllm engine --stdio + run: node run.mjs diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 8685398..42ee05d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -40,9 +40,13 @@ jobs: if [ "$npm_version" != "$node_version" ]; then echo "clients/node/package.json has $node_version, expected $npm_version"; exit 1 fi - dotnet_version=$(sed -nE 's#.*(.*).*#\1#p' clients/dotnet/src/SqlGuardLlm/SqlGuardLlm.csproj) + # The four .NET packages share one version, in clients/dotnet/Directory.Build.props. + dotnet_version=$(sed -nE 's#.*(.*).*#\1#p' clients/dotnet/Directory.Build.props) if [ "$npm_version" != "$dotnet_version" ]; then - echo "SqlGuardLlm.csproj has $dotnet_version, expected $npm_version"; exit 1 + echo "clients/dotnet/Directory.Build.props has $dotnet_version, expected $npm_version"; exit 1 + fi + if grep -rq '' clients/dotnet/src --include=*.csproj; then + echo "a .csproj under clients/dotnet/src sets its own ; it must come from Directory.Build.props"; exit 1 fi # Before 1.0 every release is a prerelease, so `latest` (what `npm install sqlguardllm` # and the npm page use) follows the newest one. From 1.0 on, prereleases get their own tag. @@ -176,9 +180,13 @@ jobs: TAG: ${{ needs.build.outputs.npm_tag }} run: node npm/publish.mjs --out npm/dist --tag "$TAG" + # The four packages (SqlGuardLlm with the five engines as runtimes/{rid}/native assets, then the three integration + # packages that depend on it), same version, symbols (.snupkg) with them. The engines are the attested archives of + # this same run, verified before anything is unpacked. Before the push, the packed package is restored by a consumer + # project and the engine of this runner is started from it (SHA-256 check included). nuget: - name: Publish the .NET client to NuGet - needs: [build, engines] + name: Publish the .NET packages to NuGet + needs: [build, engines, attest] runs-on: ubuntu-latest environment: name: nuget @@ -186,9 +194,6 @@ jobs: permissions: contents: read id-token: write - defaults: - run: - working-directory: clients/dotnet steps: - uses: actions/checkout@v4 - uses: actions/setup-dotnet@v4 @@ -196,18 +201,49 @@ jobs: dotnet-version: | 8.0.x 10.0.x + - uses: actions/download-artifact@v4 + with: + name: engine-release + path: engine-release/ + - name: Verify the engine archives (attestation, then checksums), unpack and stage them + env: + GH_TOKEN: ${{ github.token }} + VERSION: ${{ needs.build.outputs.version }} + run: | + set -e + for f in engine-release/*; do + gh attestation verify "$f" --repo "$GITHUB_REPOSITORY" + done + python3 scripts/fetch-engine.py "$VERSION" --base-url engine-release --no-attestation --out engines + python3 clients/dotnet/build/stage-engines.py --engines engines - run: dotnet build -c Release + working-directory: clients/dotnet - run: dotnet test -c Release --no-build - - run: dotnet pack src/SqlGuardLlm -c Release --no-build -o out + working-directory: clients/dotnet + - name: Pack (deterministic, SourceLink, symbols) and check size and contents + env: + NPM_VERSION: ${{ needs.build.outputs.npm_version }} + run: | + set -e + for p in SqlGuardLlm SqlGuardLlm.Extensions SqlGuardLlm.EntityFrameworkCore SqlGuardLlm.SemanticKernel; do + dotnet pack "clients/dotnet/src/$p" -c Release --no-build -o clients/dotnet/out + test -f "clients/dotnet/out/$p.$NPM_VERSION.nupkg" + test -f "clients/dotnet/out/$p.$NPM_VERSION.snupkg" + done + python3 clients/dotnet/build/stage-engines.py --check-nupkg "clients/dotnet/out/SqlGuardLlm.$NPM_VERSION.nupkg" + - name: Consumer check, restoring the packed package and starting its engine + env: + NPM_VERSION: ${{ needs.build.outputs.npm_version }} + run: dotnet run --project clients/dotnet/smoke -c Release -p:SqlGuardLlmVersion="$NPM_VERSION" # Exchanges the job's OIDC token for an API key that lives one hour. - name: NuGet login (Trusted Publishing) id: login uses: NuGet/login@v1 with: user: ${{ vars.NUGET_USER }} - - name: Push (the .snupkg symbols go with it) + - name: Push the four packages (each .snupkg goes with its .nupkg) run: >- - dotnet nuget push "out/*.nupkg" + dotnet nuget push "clients/dotnet/out/*.nupkg" --api-key "${{ steps.login.outputs.NUGET_API_KEY }}" --source https://api.nuget.org/v3/index.json --skip-duplicate diff --git a/CHANGELOG.md b/CHANGELOG.md index dc70313..798921f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,9 +4,18 @@ All notable changes to sqlguardllm are documented here. The format follows [Keep ## [Unreleased] +### Fixed +- Node.js: a program that ends with a top-level `await guard.close()` on a local-mode guard exited with an unsettled await (code 13), because the engine process is unref'd and nothing kept the event loop alive while `close()` waited for it to exit. `close()` now keeps the loop alive until the engine exits (at most 2 s). +- .NET: `dotnet pack` failed with NU5123 once the engines were staged, and a RID-specific publish (`dotnet publish -r `, self-contained, single-file, container images) failed with NETSDK1152 or lost the engine folder, because the SDK flattens native assets. The package now ships `build/SqlGuardLlm.targets`, which keeps the `sqlguardllm-engine/` folder intact next to the app (#76). +- The NuGet release job pushed `SqlGuardLlm` without the engines (nothing staged them) and did not push the integration packages (#76, #79). + ### Added +- .NET release and CI (#76, #77, #79): `clients/dotnet/build/stage-engines.py` (it was documented but missing) stages the attested engine archives with an `engine.sha256` manifest and fails when the package passes 150 MB; `clients/dotnet/Directory.Build.props` holds one version for the four packages, with SourceLink, deterministic builds and `.snupkg` symbols for all of them, and `release.yml` checks it against the engine release, verifies the engine archives, packs and pushes `SqlGuardLlm`, `SqlGuardLlm.Extensions`, `SqlGuardLlm.EntityFrameworkCore` and `SqlGuardLlm.SemanticKernel`, after a consumer project restored the packed package and started its engine. `dotnet-client.yml` now runs the unit tests and the whole conformance corpus in local mode on Linux, macOS and Windows (a missing engine fails instead of skipping), and a `package` job builds the engine of each platform, packs, and runs `clients/dotnet/smoke` with `dotnet run`, `dotnet publish -r ` (framework-dependent, self-contained single-file, trimmed and Native AOT with trimming and AOT warnings as errors), a tampered-engine check and, on Linux, a container image. +- Node.js recipes (#74): the `Recipes` workflow has a `node-recipes` job that runs `examples/node` with the real engine in local mode on SQLite and on a PostgreSQL 16 service container. `examples/node/run.mjs` and the tests accept `SQLGUARD_ENGINE_CMD`. +- Node.js and .NET guides, quickstart pointers, package chooser and READMEs (English and Spanish) now describe the embedded engine (`SqlGuard.local`, `SqlGuard.CreateLocalAsync`) as the default path and the server as the remote mode. - **.NET integrations (#78).** `SqlGuardLlm.Extensions` (`services.AddSqlGuard(...)` with options bound from configuration, ADO.NET and Dapper helpers, a Microsoft.Extensions.AI `GuardedSqlFunction`), `SqlGuardLlm.EntityFrameworkCore` (a `DbCommandInterceptor` that enforces raw SQL) and `SqlGuardLlm.SemanticKernel` (a function invocation filter), plus runnable examples in `examples/dotnet/`. - Node.js recipes (#74) in `examples/node/`: a guarded `sql_db_query` tool for LangChain.js, a guarded `tool()` for the Vercel AI SDK and runners for `pg`, `mysql2` and Prisma `$queryRawUnsafe`, all through `enforce()`, with SQLite and (with `DATABASE_URL`) PostgreSQL tests. See `docs/RECIPES.md`. + ## [0.5.0a5] - 2026-11-27 First release whose npm package carries the embedded engine: `npm install sqlguardllm` can run it with no Python and no server (`SqlGuard.local`). The .NET package ships the engine as runtime assets with a local mode. diff --git a/README.es.md b/README.es.md index aaf7a40..246662f 100644 --- a/README.es.md +++ b/README.es.md @@ -44,25 +44,25 @@ Documentación completa: https://jmmana.github.io/sqlguardllm/ pip install --pre sqlguardllm ``` -**Node.js / TypeScript** 18+: un cliente de `sqlguardllm serve`. +**Node.js / TypeScript** 18+: ejecuta el motor embebido (sin Python ni servidor) o habla con `sqlguardllm serve`. ```bash npm install sqlguardllm ``` -**.NET** 8 o 10: un cliente de `sqlguardllm serve`, en NuGet desde la 0.5.0-alpha.2. +**.NET** 8 o 10: ejecuta el motor embebido (sin Python ni servidor) o habla con `sqlguardllm serve`. ```bash dotnet add package SqlGuardLlm --prerelease ``` -**El servidor** con el que hablan los clientes de Node.js y .NET, en otra terminal (Python 3.10+). No hay imagen de Docker publicada; el [Dockerfile](Dockerfile) construye una si la necesitas. +**El servidor** es opcional en Node.js y .NET: sus paquetes llevan el motor y lo ejecutan en local (`SqlGuard.local` / `SqlGuard.CreateLocalAsync`). Ejecútalo, en otra terminal (Python 3.10+), cuando varios servicios comparten una política o tu plataforma no tiene motor embebido. No hay imagen de Docker publicada; el [Dockerfile](Dockerfile) construye una si la necesitas. ```bash uvx sqlguardllm serve --policy policy.json --port 8787 # o: pipx run sqlguardllm serve ... ``` -**Paso a paso** para cada lenguaje, de la instalación a un programa y su salida exacta: [Python](https://jmmana.github.io/sqlguardllm/es/guide-python/) · [Node.js / TypeScript](https://jmmana.github.io/sqlguardllm/es/guide-node/) · [.NET](https://jmmana.github.io/sqlguardllm/es/guide-dotnet/) · [qué paquete elegir](https://jmmana.github.io/sqlguardllm/es/packages/). Están previstos motores embebidos para Node.js ([#85](https://github.com/jmmana/sqlguardllm/issues/85)) y .NET ([#86](https://github.com/jmmana/sqlguardllm/issues/86)), sin servidor. +**Paso a paso** para cada lenguaje, de la instalación a un programa y su salida exacta: [Python](https://jmmana.github.io/sqlguardllm/es/guide-python/) · [Node.js / TypeScript](https://jmmana.github.io/sqlguardllm/es/guide-node/) · [.NET](https://jmmana.github.io/sqlguardllm/es/guide-dotnet/) · [qué paquete elegir](https://jmmana.github.io/sqlguardllm/es/packages/). Las guías de Node.js y .NET usan el motor embebido: sin Python y sin servidor. ## Pruébalo: entrada, decisión y SQL devuelto @@ -288,7 +288,7 @@ Un motor, varios clientes. El motor es de Python porque está construido sobre [ - **.NET:** `dotnet add package SqlGuardLlm --prerelease` ([`clients/dotnet`](clients/dotnet/README.md)), en NuGet desde la 0.5.0-alpha.2: net8.0 y net10.0, falla cerrado. - **Cualquier otro lenguaje:** la [API HTTP](docs/SERVER.md), el [servidor MCP](docs/MCP.md) o la CLI. -Los pasos de instalación de cada lenguaje están en [Instalación](#instalación). Están previstos motores embebidos, para que los paquetes de Node.js y .NET funcionen sin Python y sin servidor, en [#85](https://github.com/jmmana/sqlguardllm/issues/85) y [#86](https://github.com/jmmana/sqlguardllm/issues/86). +Los pasos de instalación de cada lenguaje están en [Instalación](#instalación). Los paquetes de Node.js y .NET llevan el motor para linux-x64, linux-arm64, macOS (x64, arm64) y win-x64, así que funcionan sin Python y sin servidor; en otras plataformas usan el modo remoto. ## Playground: intenta romperlo diff --git a/README.md b/README.md index 5d8dd88..58bcb02 100644 --- a/README.md +++ b/README.md @@ -42,25 +42,25 @@ Full documentation: https://jmmana.github.io/sqlguardllm/ pip install --pre sqlguardllm ``` -**Node.js / TypeScript** 18+: a client for `sqlguardllm serve`. +**Node.js / TypeScript** 18+: runs the embedded engine (no Python, no server) or talks to `sqlguardllm serve`. ```bash npm install sqlguardllm ``` -**.NET** 8 or 10: a client for `sqlguardllm serve`, on NuGet from 0.5.0-alpha.2. +**.NET** 8 or 10: runs the embedded engine (no Python, no server) or talks to `sqlguardllm serve`. ```bash dotnet add package SqlGuardLlm --prerelease ``` -**The server** that the Node.js and .NET clients talk to, in another terminal (Python 3.10+). No Docker image is published; the [Dockerfile](Dockerfile) builds one if you need it. +**The server** is optional for Node.js and .NET: their packages carry the engine and run it locally (`SqlGuard.local` / `SqlGuard.CreateLocalAsync`). Run it, in another terminal (Python 3.10+), when several services share one policy or your platform has no embedded engine. No Docker image is published; the [Dockerfile](Dockerfile) builds one if you need it. ```bash uvx sqlguardllm serve --policy policy.json --port 8787 # or: pipx run sqlguardllm serve ... ``` -**Step by step** for each language, from install to a program and its exact output: [Python](https://jmmana.github.io/sqlguardllm/guide-python/) · [Node.js / TypeScript](https://jmmana.github.io/sqlguardllm/guide-node/) · [.NET](https://jmmana.github.io/sqlguardllm/guide-dotnet/) · [which package to choose](https://jmmana.github.io/sqlguardllm/packages/). Embedded engines for Node.js ([#85](https://github.com/jmmana/sqlguardllm/issues/85)) and .NET ([#86](https://github.com/jmmana/sqlguardllm/issues/86)), with no server, are planned. +**Step by step** for each language, from install to a program and its exact output: [Python](https://jmmana.github.io/sqlguardllm/guide-python/) · [Node.js / TypeScript](https://jmmana.github.io/sqlguardllm/guide-node/) · [.NET](https://jmmana.github.io/sqlguardllm/guide-dotnet/) · [which package to choose](https://jmmana.github.io/sqlguardllm/packages/). The Node.js and .NET guides use the embedded engine: no Python and no server. ## Try it: input, decision and returned SQL @@ -286,7 +286,7 @@ One engine, many clients. The engine is Python because it is built on [sqlglot]( - **.NET:** `dotnet add package SqlGuardLlm --prerelease` ([`clients/dotnet`](clients/dotnet/README.md)), on NuGet from 0.5.0-alpha.2: net8.0 and net10.0, fails closed. - **Any other language:** the [HTTP API](docs/SERVER.md), the [MCP server](docs/MCP.md) or the CLI. -Install steps for each language are in [Install](#install). Embedded engines, so the Node.js and .NET packages work with no Python and no server, are planned in [#85](https://github.com/jmmana/sqlguardllm/issues/85) and [#86](https://github.com/jmmana/sqlguardllm/issues/86). +Install steps for each language are in [Install](#install). The Node.js and .NET packages carry the engine for linux-x64, linux-arm64, macOS (x64, arm64) and win-x64, so they work with no Python and no server; elsewhere they use the remote mode. ## Playground: try to break it diff --git a/clients/dotnet/.gitignore b/clients/dotnet/.gitignore index 9695643..c2a3ee2 100644 --- a/clients/dotnet/.gitignore +++ b/clients/dotnet/.gitignore @@ -1,3 +1,4 @@ bin/ +out/ obj/ src/SqlGuardLlm/engines/ diff --git a/clients/dotnet/Directory.Build.props b/clients/dotnet/Directory.Build.props new file mode 100644 index 0000000..44b7136 --- /dev/null +++ b/clients/dotnet/Directory.Build.props @@ -0,0 +1,12 @@ + + + + 0.5.0-alpha.5 + + true + true + snupkg + true + + diff --git a/clients/dotnet/README.md b/clients/dotnet/README.md index 4606995..944ca58 100644 --- a/clients/dotnet/README.md +++ b/clients/dotnet/README.md @@ -65,6 +65,10 @@ The library uses source-generated `System.Text.Json` and no reflection; it is an Before it starts, the client recomputes the SHA-256 of every engine file against `engine.sha256` and refuses to run on any mismatch (`SqlGuardException`, code `engine_integrity`); it also refuses an engine whose version or protocol does not match the package. On an unsupported runtime (another OS or CPU, Alpine/musl) it throws `engine_unsupported`, whose message points to remote mode: use `SqlGuardClient` against `sqlguardllm serve`. The hashes ship in the same package as the binaries, so they catch corruption and tampering after install; the supply chain (checksums and attestations of the release) is verified by `scripts/fetch-engine.py` when the package is built. Unix permissions are not kept by NuGet, so the client sets the executable bit on first start: a read-only file system needs it set at image build time. +### Publishing + +It works with `dotnet run`, `dotnet publish -r `, self-contained and single-file publishes, Native AOT and Linux container images (glibc based, such as `mcr.microsoft.com/dotnet/runtime-deps`; Alpine/musl is not supported). The package ships `build/SqlGuardLlm.targets`, which keeps the engine folder intact in a RID-specific publish (the SDK would otherwise flatten native assets): it ends up as `sqlguardllm-engine/` next to your executable, which is where the client looks. Copy the whole publish folder, not just the executable. CI proves each of these with the packed package (`clients/dotnet/smoke`, `.github/workflows/dotnet-client.yml`). + ## API | Member | Returns | diff --git a/clients/dotnet/smoke/Dockerfile b/clients/dotnet/smoke/Dockerfile new file mode 100644 index 0000000..3007415 --- /dev/null +++ b/clients/dotnet/smoke/Dockerfile @@ -0,0 +1,7 @@ +# Runs the self-contained single-file publish of Smoke in a plain Linux image (glibc, no .NET installed). +# dotnet publish smoke -r linux-x64 --self-contained -p:PublishSingleFile=true -o smoke/publish +# docker build -f smoke/Dockerfile -t sqlguard-smoke smoke/publish && docker run --rm sqlguard-smoke +FROM mcr.microsoft.com/dotnet/runtime-deps:10.0 +WORKDIR /app +COPY . . +ENTRYPOINT ["/app/Smoke"] diff --git a/clients/dotnet/smoke/Program.cs b/clients/dotnet/smoke/Program.cs new file mode 100644 index 0000000..29018b1 --- /dev/null +++ b/clients/dotnet/smoke/Program.cs @@ -0,0 +1,13 @@ +// Smoke test of the packed NuGet package: starts the embedded engine (SHA-256 verified), allows one query, rejects one. +// Exit code 0 only if both behave. Used by dotnet-client.yml for `dotnet run`, `dotnet publish -r ` (self-contained, +// single-file, Native AOT) and a Linux container image. +using SqlGuardLlm; + +await using var guard = await SqlGuard.CreateLocalAsync(new SqlGuardLocalOptions +{ + PolicyJson = """{"dialect":"postgres","tables":["invoices"]}""", +}); +var safe = await guard.EnforceAsync("SELECT id FROM invoices"); +var bad = await guard.CheckAsync("DELETE FROM invoices"); +Console.WriteLine($"safe={safe} rejected={!bad.Ok} codes={string.Join(",", bad.Violations.Select(v => v.Code))}"); +return safe == "SELECT id FROM invoices LIMIT 1000" && !bad.Ok ? 0 : 1; diff --git a/clients/dotnet/smoke/Smoke.csproj b/clients/dotnet/smoke/Smoke.csproj new file mode 100644 index 0000000..1cc03aa --- /dev/null +++ b/clients/dotnet/smoke/Smoke.csproj @@ -0,0 +1,16 @@ + + + + Exe + net10.0 + enable + enable + 0.5.0-alpha.5 + false + + + + + + diff --git a/clients/dotnet/smoke/nuget.config b/clients/dotnet/smoke/nuget.config new file mode 100644 index 0000000..5014191 --- /dev/null +++ b/clients/dotnet/smoke/nuget.config @@ -0,0 +1,7 @@ + + + + + + + diff --git a/clients/dotnet/src/SqlGuardLlm.EntityFrameworkCore/SqlGuardLlm.EntityFrameworkCore.csproj b/clients/dotnet/src/SqlGuardLlm.EntityFrameworkCore/SqlGuardLlm.EntityFrameworkCore.csproj index f598b64..8dd9872 100644 --- a/clients/dotnet/src/SqlGuardLlm.EntityFrameworkCore/SqlGuardLlm.EntityFrameworkCore.csproj +++ b/clients/dotnet/src/SqlGuardLlm.EntityFrameworkCore/SqlGuardLlm.EntityFrameworkCore.csproj @@ -8,7 +8,6 @@ true true SqlGuardLlm.EntityFrameworkCore - 0.5.0-alpha.4 jmmana EF Core DbCommandInterceptor that sends raw SQL (FromSql, SqlQuery, ExecuteSql) through sqlguardllm before it reaches the database. sql;llm;security;firewall;sqlguardllm;efcore diff --git a/clients/dotnet/src/SqlGuardLlm.Extensions/SqlGuardLlm.Extensions.csproj b/clients/dotnet/src/SqlGuardLlm.Extensions/SqlGuardLlm.Extensions.csproj index 6274233..27f2267 100644 --- a/clients/dotnet/src/SqlGuardLlm.Extensions/SqlGuardLlm.Extensions.csproj +++ b/clients/dotnet/src/SqlGuardLlm.Extensions/SqlGuardLlm.Extensions.csproj @@ -8,7 +8,6 @@ true true SqlGuardLlm.Extensions - 0.5.0-alpha.4 jmmana sqlguardllm for the .NET stack: AddSqlGuard for dependency injection, ADO.NET and Dapper helpers, and a Microsoft.Extensions.AI function that checks SQL before running it. sql;llm;security;firewall;text-to-sql;sqlguardllm;dapper;ado.net;extensions-ai diff --git a/clients/dotnet/src/SqlGuardLlm.SemanticKernel/SqlGuardLlm.SemanticKernel.csproj b/clients/dotnet/src/SqlGuardLlm.SemanticKernel/SqlGuardLlm.SemanticKernel.csproj index b26e52d..133782f 100644 --- a/clients/dotnet/src/SqlGuardLlm.SemanticKernel/SqlGuardLlm.SemanticKernel.csproj +++ b/clients/dotnet/src/SqlGuardLlm.SemanticKernel/SqlGuardLlm.SemanticKernel.csproj @@ -8,7 +8,6 @@ true true SqlGuardLlm.SemanticKernel - 0.5.0-alpha.4 jmmana Semantic Kernel function invocation filter that checks the SQL a model sends to a function with sqlguardllm before the function runs. sql;llm;security;firewall;sqlguardllm;semantic-kernel diff --git a/clients/dotnet/src/SqlGuardLlm/SqlGuardLlm.csproj b/clients/dotnet/src/SqlGuardLlm/SqlGuardLlm.csproj index 1d08d8a..2934ec5 100644 --- a/clients/dotnet/src/SqlGuardLlm/SqlGuardLlm.csproj +++ b/clients/dotnet/src/SqlGuardLlm/SqlGuardLlm.csproj @@ -10,30 +10,27 @@ true true SqlGuardLlm - 0.5.0-alpha.5 jmmana - Official .NET client for sqlguardllm, a SQL firewall for LLM apps. Talks to `sqlguardllm serve` over HTTP and fails closed. + Official .NET client for sqlguardllm, a SQL firewall for LLM apps. Runs the embedded engine in-process (no Python, no server) or talks to `sqlguardllm serve` over HTTP, and fails closed. sql;llm;security;firewall;text-to-sql;sqlguardllm Apache-2.0 README.md https://github.com/jmmana/sqlguardllm https://github.com/jmmana/sqlguardllm git - true - true - snupkg true true + - - - - - + + + + + diff --git a/clients/node/src/local.ts b/clients/node/src/local.ts index 992e567..41308de 100644 --- a/clients/node/src/local.ts +++ b/clients/node/src/local.ts @@ -224,7 +224,16 @@ export class LocalEngine { const proc = this.proc; this.kill(fail("closed", "the engine was closed")); if (proc && proc.exitCode === null && proc.signalCode === null) { - await new Promise((done) => proc.once("exit", () => done())); + // The process was unref'd so an idle engine never keeps the app alive; waiting for its exit has to keep it alive, + // or a program that ends with `await guard.close()` would exit with an unsettled await (code 13). + proc.ref(); + await new Promise((done) => { + const timer = setTimeout(done, 2000); + proc.once("exit", () => { + clearTimeout(timer); + done(); + }); + }); } } } diff --git a/clients/node/test/local.test.ts b/clients/node/test/local.test.ts index db4b750..7cc792a 100644 --- a/clients/node/test/local.test.ts +++ b/clients/node/test/local.test.ts @@ -140,4 +140,20 @@ describe("local mode", () => { const out = execFileSync(process.execPath, [file], { stdio: "pipe", timeout: 20000 }).toString(); expect(out.trim()).toBe("true"); }); + + it("a program that ends with a top-level `await guard.close()` finishes normally (no unsettled await)", () => { + const script = ` + const { SqlGuard } = await import(${JSON.stringify(join(__dirname, "../dist/index.js"))}); + const g = await SqlGuard.local({ policy: {}, engine: [process.execPath, ${JSON.stringify(fake)}] }); + console.log((await g.check("SELECT 1")).ok); + await g.close(); + console.log("closed");`; + const file = join(tmp, "close.mjs"); + writeFileSync(file, script); + let built = true; + try { execFileSync(process.execPath, ["-e", `require("fs").accessSync(${JSON.stringify(join(__dirname, "../dist/index.js"))})`]); } catch { built = false; } + if (!built) return; // needs `npm run build`; CI builds first + const out = execFileSync(process.execPath, [file], { stdio: "pipe", timeout: 20000 }).toString(); + expect(out.trim().split("\n")).toEqual(["true", "closed"]); + }); }); diff --git a/docs/RECIPES.md b/docs/RECIPES.md index 83d87a4..ce9b642 100644 --- a/docs/RECIPES.md +++ b/docs/RECIPES.md @@ -169,7 +169,7 @@ tools.register_local_tool( ## Node.js -The Node recipes live in [`examples/node/`](../examples/node) and use the [`sqlguardllm` npm package](../clients/node/README.md), in local mode (the embedded engine, no server) or remote mode. They need Node 22.5+ for the SQLite demo. Run `npm install` in that folder, then `npm start` (SQLite) or `DATABASE_URL=postgres://… npm start` (PostgreSQL through `pg`). Tests: `npm test`; frameworks that aren't installed are skipped (`SQLGUARDLLM_RECIPES=1` makes that a failure) and the PostgreSQL test runs only with `DATABASE_URL`. +The Node recipes live in [`examples/node/`](../examples/node) and use the [`sqlguardllm` npm package](../clients/node/README.md), in local mode (the embedded engine, no server) or remote mode. They need Node 22.5+ for the SQLite demo. Run `npm install` in that folder, then `npm start` (SQLite) or `DATABASE_URL=postgres://… npm start` (PostgreSQL through `pg`). Tests: `npm test`; frameworks that aren't installed are skipped (`SQLGUARDLLM_RECIPES=1` makes that a failure) and the PostgreSQL tests run only with `DATABASE_URL`. With `SQLGUARD_ENGINE_CMD="uv run sqlguardllm engine --stdio"` (or any engine command) the last two tests drive the real engine in local mode with the demo policy, executing on SQLite and on PostgreSQL, and `node run.mjs` uses it too. The `Recipes` workflow (`.github/workflows/recipes.yml`, job `node-recipes`) runs all of it against a PostgreSQL 16 service container on every pull request. Everything is in [`guarded-tools.mjs`](../examples/node/guarded-tools.mjs). `guardedQuery(guard, run, getContext)` calls `guard.enforce()` and only then `run()`. A rejected query comes back as `{ ok: false, feedback }` for the model to repair; a failure to reach the guard throws, so nothing runs (fail closed). diff --git a/docs/es/guide-dotnet.md b/docs/es/guide-dotnet.md index 56e8acc..0159e49 100644 --- a/docs/es/guide-dotnet.md +++ b/docs/es/guide-dotnet.md @@ -2,18 +2,19 @@ [Read in English](../guide-dotnet.md) · [Elige un paquete](packages.md) · [Python](guide-python.md) · [Node.js](guide-node.md) -El paquete de NuGet `SqlGuardLlm` es un cliente pequeño, sin más dependencias que `HttpClient` y `System.Text.Json`. El motor se ejecuta en `sqlguardllm serve`, un servidor HTTP junto a tu aplicación, así que .NET recibe exactamente las mismas respuestas que Python. Necesitas el SDK de .NET 8 o .NET 10, y Python 3.10 o posterior para el servidor. +El paquete NuGet `SqlGuardLlm` incluye el motor para linux-x64, linux-arm64, osx-x64, osx-arm64 y win-x64 (en `runtimes/{rid}/native/`), así que el guard corre como proceso hijo de tu app **sin Python y sin servidor**. Es el modo local, y es el que usa esta guía. Necesitas el SDK de .NET 8 o .NET 10. Si tu plataforma no tiene motor (otro sistema u otra CPU, o Linux musl como Alpine), usa el [modo remoto](#modo-remoto-un-servidor-en-lugar-del-motor-embebido) con un servidor en marcha. -!!! note "Hoy el cliente necesita un servidor en marcha" - Un motor embebido, para que el paquete funcione sin Python y sin servidor, está previsto en [#86](https://github.com/jmmana/sqlguardllm/issues/86). - -## 1. Escribe una política +## 1. Crea el proyecto y escribe una política ```bash -mkdir guard-demo && cd guard-demo +dotnet new console -n GuardDemo +cd GuardDemo +dotnet add package SqlGuardLlm --prerelease ``` -Guarda esto como `policy.json` en esa carpeta. Lo lee el servidor; el cliente nunca lo lee. +`--prerelease` hace falta mientras el paquete esté en alfa. El paquete está en [NuGet](https://www.nuget.org/packages/SqlGuardLlm). + +Guarda esto como `policy.json` en la carpeta `GuardDemo`: ```json { @@ -30,45 +31,19 @@ Guarda esto como `policy.json` en esa carpeta. Lo lee el servidor; el cliente nu El modelo puede leer tres tablas ([`tables`](../policy-reference.md#tables)), nunca `customers.email` ([`hidden_columns`](../policy-reference.md#hidden_columns)), solo las facturas y sucursales de las sucursales del usuario ([`row_filters`](../policy-reference.md#row_filters)) y como máximo 100 filas ([`max_rows`](../policy-reference.md#max_rows)). -## 2. Inicia el servidor, en otra terminal - -Desde la misma carpeta, con [uv](https://docs.astral.sh/uv/): - -```bash -uvx sqlguardllm serve --policy policy.json --port 8787 --language es -``` - -Con [pipx](https://pipx.pypa.io/) es `pipx run sqlguardllm serve --policy policy.json --port 8787 --language es`. Con pip: - -```bash -python -m venv .venv -source .venv/bin/activate # Windows: .venv\Scripts\activate -pip install --pre sqlguardllm -sqlguardllm serve --policy policy.json --port 8787 --language es -``` - -Imprime una línea como `sqlguardllm 0.5.0a5 listening on http://127.0.0.1:8787 (no token)` y sigue ejecutándose: deja esa terminal abierta. Solo escucha en tu equipo. Antes de exponerlo a otros equipos, configura un [token](../SERVER.md#token). Todavía no hay una imagen de Docker publicada; puedes construir una con el [Dockerfile](../SERVER.md#docker) del repositorio. `--language es` hace que los mensajes de las violaciones salgan en español. - -## 3. Instala el cliente - -En la primera terminal, en `guard-demo`: - -```bash -dotnet new console -n GuardDemo -cd GuardDemo -dotnet add package SqlGuardLlm --prerelease -``` - -`--prerelease` hace falta mientras el paquete esté en fase alfa. El paquete está en [NuGet](https://www.nuget.org/packages/SqlGuardLlm) desde la 0.5.0-alpha.2. - -## 4. Revisa una consulta permitida y una rechazada +## 2. Revisa una consulta permitida y una rechazada Reemplaza `Program.cs` por: ```csharp using SqlGuardLlm; -using var guard = new SqlGuardClient("http://localhost:8787"); +// Inicia el motor embebido (antes verifica el SHA-256 de sus archivos) y carga la política. +await using var guard = await SqlGuard.CreateLocalAsync(new SqlGuardLocalOptions +{ + PolicyJson = await File.ReadAllTextAsync("policy.json"), + Language = "es", +}); // El gerente de la sucursal 1. En tu app viene del usuario que inició sesión, nunca del modelo. var context = new Dictionary @@ -83,7 +58,9 @@ var emails = await guard.CheckAsync("SELECT name, email FROM customers", context Console.WriteLine($"{emails.Ok} {string.Join("; ", emails.Violations.Select(v => $"{v.Code}: {v.Message}"))}"); ``` -## 5. Ejecútalo +`SqlGuard.CreateLocalAsync` devuelve un `ISqlGuard`, la misma interfaz (`CheckAsync`, `EnforceAsync`, `ExplainAsync`, cada una con un `CancellationToken`) que el `SqlGuardClient` remoto. Es seguro entre hilos: comparte una sola instancia en toda la app. `Language = "es"` hace que los mensajes salgan en español. + +## 3. Ejecútalo ```bash dotnet run @@ -98,9 +75,11 @@ False hidden_column: customers.email es una columna oculta La primera consulta se permite y se reescribe: solo las facturas de la sucursal 1, con un `LIMIT`. Ejecuta `invoices.Sql`, nunca el texto original, con un usuario de base de datos de solo lectura. La segunda se rechaza porque la política oculta `customers.email`. -Si ves `SqlGuardException: Could not reach the sqlguardllm server.`, el servidor no está en marcha. El cliente **falla cerrado**: lanza una excepción en vez de dejar pasar la consulta, así que nunca la captures para ejecutar el SQL de todos modos. +El cliente **falla cerrado**: si el motor no puede iniciar, un archivo no coincide con su SHA-256, el motor se cae o una llamada se pasa del tiempo, la llamada lanza una `SqlGuardException` (y el motor se reinicia con espera creciente) en vez de dejar pasar la consulta, así que nunca captures esa excepción para ejecutar el SQL de todos modos. En una plataforma no soportada la excepción tiene el código `engine_unsupported` y su mensaje nombra el modo remoto. + +También funciona con `dotnet publish -r `, publicaciones autocontenidas y de archivo único (la carpeta `sqlguardllm-engine` queda junto al ejecutable), Native AOT e imágenes de contenedor Linux (basadas en glibc, como `mcr.microsoft.com/dotnet/runtime-deps`; no Alpine). -## 6. Cambia una regla +## 4. Cambia una regla Para que el modelo lea el email enmascarado, reemplaza la línea de `hidden_columns` de `policy.json` por: @@ -108,10 +87,27 @@ Para que el modelo lea el email enmascarado, reemplaza la línea de `hidden_colu "masked_columns": {"customers.email": "partial"}, ``` -Detén el servidor (Ctrl+C), inícialo de nuevo y ejecuta `dotnet run`. La segunda línea pasa a ser `True` sin violaciones: la consulta se permite y `ceo@acme.example` vuelve como `ce***` ([`masked_columns`](../policy-reference.md#masked_columns)). Puedes activar y desactivar estas reglas sin instalar nada en el [playground](https://jmmana.github.io/sqlguardllm/playground/). +Ejecuta `dotnet run` de nuevo. La segunda línea pasa a ser `True` sin violaciones: la consulta se permite y `ceo@acme.example` vuelve como `ce***` ([`masked_columns`](../policy-reference.md#masked_columns)). Puedes activar y desactivar estas reglas sin instalar nada en el [playground](https://jmmana.github.io/sqlguardllm/playground/). + +## Modo remoto: un servidor en lugar del motor embebido + +Úsalo cuando varios servicios comparten una política, o en una plataforma sin motor embebido. El motor corre entonces en `sqlguardllm serve`, un servidor HTTP junto a tu aplicación (Python 3.10 o posterior). En otra terminal, desde la misma carpeta, con [uv](https://docs.astral.sh/uv/): + +```bash +uvx sqlguardllm serve --policy policy.json --port 8787 --language es +``` + +Con [pipx](https://pipx.pypa.io/) es `pipx run sqlguardllm serve --policy policy.json --port 8787 --language es`. Con pip: `pip install --pre sqlguardllm` y luego `sqlguardllm serve --policy policy.json --port 8787 --language es`. Solo escucha en tu equipo; antes de exponerlo a otros equipos, configura un [token](../SERVER.md#token). En `Program.cs`, reemplaza la instrucción `await using var guard = ...` por: + +```csharp +using var guard = new SqlGuardClient("http://localhost:8787"); +``` + +La salida es la misma. Si ves `SqlGuardException: Could not reach the sqlguardllm server.`, el servidor no está en marcha; ahí también el cliente falla cerrado. Tras editar `policy.json`, reinicia el servidor. ## Siguiente -- [README del cliente](https://github.com/jmmana/sqlguardllm/blob/main/clients/dotnet/README.md) (en inglés): `EnforceAsync`, inyección de dependencias con tu propio `HttpClient`, Dapper y ADO.NET, tokens y errores. +- [README del cliente](https://github.com/jmmana/sqlguardllm/blob/main/clients/dotnet/README.md) (en inglés): modo local y remoto, `EnforceAsync`, inyección de dependencias, Dapper y ADO.NET, tokens y errores. +- [Recetas](../RECIPES.md#net) (en inglés): `AddSqlGuard`, EF Core, Dapper, Semantic Kernel y Microsoft.Extensions.AI. - [Servidor HTTP](../SERVER.md): opciones, el contrato `/v1` y notas de seguridad. - [Referencia de políticas](../policy-reference.md): todos los campos. diff --git a/docs/es/guide-node.md b/docs/es/guide-node.md index 653a47e..a73b9b8 100644 --- a/docs/es/guide-node.md +++ b/docs/es/guide-node.md @@ -2,10 +2,7 @@ [Read in English](../guide-node.md) · [Elige un paquete](packages.md) · [Python](guide-python.md) · [.NET](guide-dotnet.md) -El paquete de npm `sqlguardllm` es un cliente pequeño y sin dependencias. El motor se ejecuta en `sqlguardllm serve`, un servidor HTTP junto a tu aplicación, así que Node.js recibe exactamente las mismas respuestas que Python. Necesitas Node.js 18 o posterior, y Python 3.10 o posterior para el servidor. - -!!! note "Modo local o modo remoto" - `npm install sqlguardllm` también instala el motor de tu plataforma (linux x64/arm64, macOS x64/arm64, Windows x64), así que `await SqlGuard.local({ policyPath: "policy.json" })` ejecuta el guard sin Python y sin servidor (consulta el [README del paquete](https://github.com/jmmana/sqlguardllm/tree/main/clients/node#local-mode)). Esta guía usa el modo remoto, más abajo. Si tu plataforma no tiene paquete de motor (por ejemplo Alpine/musl), o usas Deno, un navegador o un entorno edge, usa el modo remoto con un servidor en marcha. +El paquete de npm `sqlguardllm` ejecuta el motor por ti: `npm install sqlguardllm` también instala el motor de tu plataforma (linux x64/arm64, macOS x64/arm64, Windows x64), así que el guard corre junto a tu proceso de Node.js **sin Python y sin servidor**. Es el modo local, y es el que usa esta guía. Necesitas Node.js 18 o posterior. Si tu plataforma no tiene paquete de motor (por ejemplo Alpine/musl), o usas Deno, un navegador o un entorno edge, usa el [modo remoto](#modo-remoto-un-servidor-en-lugar-del-motor-embebido) con un servidor en marcha. ## 1. Escribe una política @@ -13,7 +10,7 @@ El paquete de npm `sqlguardllm` es un cliente pequeño y sin dependencias. El mo mkdir guard-demo && cd guard-demo ``` -Guarda esto como `policy.json` en esa carpeta. Lo lee el servidor; el cliente nunca lo lee. +Guarda esto como `policy.json` en esa carpeta. ```json { @@ -30,56 +27,40 @@ Guarda esto como `policy.json` en esa carpeta. Lo lee el servidor; el cliente nu El modelo puede leer tres tablas ([`tables`](../policy-reference.md#tables)), nunca `customers.email` ([`hidden_columns`](../policy-reference.md#hidden_columns)), solo las facturas y sucursales de las sucursales del usuario ([`row_filters`](../policy-reference.md#row_filters)) y como máximo 100 filas ([`max_rows`](../policy-reference.md#max_rows)). -## 2. Inicia el servidor, en otra terminal - -Desde la misma carpeta, con [uv](https://docs.astral.sh/uv/): - -```bash -uvx sqlguardllm serve --policy policy.json --port 8787 --language es -``` - -Con [pipx](https://pipx.pypa.io/) es `pipx run sqlguardllm serve --policy policy.json --port 8787 --language es`. Con pip: - -```bash -python -m venv .venv -source .venv/bin/activate # Windows: .venv\Scripts\activate -pip install --pre sqlguardllm -sqlguardllm serve --policy policy.json --port 8787 --language es -``` - -Imprime una línea como `sqlguardllm 0.5.0a5 listening on http://127.0.0.1:8787 (no token)` y sigue ejecutándose: deja esa terminal abierta. Solo escucha en tu equipo. Antes de exponerlo a otros equipos, configura un [token](../SERVER.md#token). Todavía no hay una imagen de Docker publicada; puedes construir una con el [Dockerfile](../SERVER.md#docker) del repositorio. `--language es` hace que los mensajes de las violaciones salgan en español. - -## 3. Instala el cliente - -En la primera terminal, en `guard-demo`: +## 2. Instala el cliente ```bash npm init -y npm install sqlguardllm ``` -## 4. Revisa una consulta permitida y una rechazada +## 3. Revisa una consulta permitida y una rechazada Guarda esto como `check.mjs`: ```js import { SqlGuard } from "sqlguardllm"; -const guard = new SqlGuard({ baseUrl: "http://localhost:8787" }); +// Inicia el motor embebido (antes verifica su SHA-256) y carga la política. +const guard = await SqlGuard.local({ policyPath: "policy.json", language: "es" }); // El gerente de la sucursal 1. En tu app viene del usuario que inició sesión, nunca del modelo. const context = { user: { branches: [1] } }; -const invoices = await guard.check("SELECT id, total FROM invoices ORDER BY id", context); -console.log(invoices.ok, invoices.sql); +try { + const invoices = await guard.check("SELECT id, total FROM invoices ORDER BY id", context); + console.log(invoices.ok, invoices.sql); -const emails = await guard.check("SELECT name, email FROM customers", context); -console.log(emails.ok, emails.violations.map((v) => `${v.code}: ${v.message}`)); + const emails = await guard.check("SELECT name, email FROM customers", context); + console.log(emails.ok, emails.violations.map((v) => `${v.code}: ${v.message}`)); +} finally { + await guard.close(); // detiene el motor +} ``` -El paquete incluye sus declaraciones de tipos, así que el mismo código funciona en TypeScript. +`language: "es"` hace que los mensajes de las violaciones salgan en español. El paquete incluye sus declaraciones de tipos, así que el mismo código funciona en TypeScript (`import { SqlGuard } from "sqlguardllm"`, `const guard: SqlGuard = await SqlGuard.local(...)`). -## 5. Ejecútalo +## 4. Ejecútalo ```bash node check.mjs @@ -94,9 +75,9 @@ false [ 'hidden_column: customers.email es una columna oculta' ] La primera consulta se permite y se reescribe: solo las facturas de la sucursal 1, con un `LIMIT`. Ejecuta `invoices.sql`, nunca el texto original, con un usuario de base de datos de solo lectura. La segunda se rechaza porque la política oculta `customers.email`. -Si ves `SqlGuardError: cannot reach the sqlguardllm server`, el servidor no está en marcha. El cliente **falla cerrado**: lanza un error en vez de dejar pasar la consulta, así que nunca captures ese error para ejecutar el SQL de todos modos. +El cliente **falla cerrado**: si el motor no puede iniciar, se cae o se pasa del tiempo, la llamada lanza un `SqlGuardError` (y el motor se reinicia con espera creciente) en vez de dejar pasar la consulta, así que nunca captures ese error para ejecutar el SQL de todos modos. En una plataforma no soportada el error es `unsupported_platform` y su mensaje nombra el modo remoto. -## 6. Cambia una regla +## 5. Cambia una regla Para que el modelo lea el email enmascarado, reemplaza la línea de `hidden_columns` de `policy.json` por: @@ -104,10 +85,27 @@ Para que el modelo lea el email enmascarado, reemplaza la línea de `hidden_colu "masked_columns": {"customers.email": "partial"}, ``` -Detén el servidor (Ctrl+C), inícialo de nuevo y ejecuta `node check.mjs`. La segunda línea pasa a ser `true []`: la consulta se permite y `ceo@acme.example` vuelve como `ce***` ([`masked_columns`](../policy-reference.md#masked_columns)). Puedes activar y desactivar estas reglas sin instalar nada en el [playground](https://jmmana.github.io/sqlguardllm/playground/). +Ejecuta `node check.mjs` de nuevo. La segunda línea pasa a ser `true []`: la consulta se permite y `ceo@acme.example` vuelve como `ce***` ([`masked_columns`](../policy-reference.md#masked_columns)). Puedes activar y desactivar estas reglas sin instalar nada en el [playground](https://jmmana.github.io/sqlguardllm/playground/). + +## Modo remoto: un servidor en lugar del motor embebido + +Úsalo cuando varios servicios comparten una política, o en una plataforma sin motor embebido. El motor corre entonces en `sqlguardllm serve`, un servidor HTTP junto a tu aplicación (Python 3.10 o posterior). En otra terminal, desde la misma carpeta, con [uv](https://docs.astral.sh/uv/): + +```bash +uvx sqlguardllm serve --policy policy.json --port 8787 --language es +``` + +Con [pipx](https://pipx.pypa.io/) es `pipx run sqlguardllm serve --policy policy.json --port 8787 --language es`. Con pip: `pip install --pre sqlguardllm` y luego `sqlguardllm serve --policy policy.json --port 8787 --language es`. Solo escucha en tu equipo; antes de exponerlo a otros equipos, configura un [token](../SERVER.md#token). En `check.mjs`, reemplaza la primera línea de código por: + +```js +const guard = new SqlGuard({ baseUrl: "http://localhost:8787" }); +``` + +(y quita el bloque `finally`: no hay motor que cerrar). La salida es la misma. Si ves `SqlGuardError: cannot reach the sqlguardllm server`, el servidor no está en marcha; ahí también el cliente falla cerrado. Tras editar `policy.json`, reinicia el servidor. ## Siguiente -- [README del cliente](https://github.com/jmmana/sqlguardllm/blob/main/clients/node/README.md) (en inglés): `enforce`, `wrap` para `pg` y `mysql2`, tokens, tiempos de espera y errores. +- [README del cliente](https://github.com/jmmana/sqlguardllm/blob/main/clients/node/README.md) (en inglés): modo local y remoto, `enforce`, `wrap` para `pg` y `mysql2`, tokens, tiempos de espera y errores. +- [Recetas](../RECIPES.md#nodejs) (en inglés): LangChain.js, Vercel AI SDK, `pg`, `mysql2` y Prisma. - [Servidor HTTP](../SERVER.md): opciones, el contrato `/v1` y notas de seguridad. - [Referencia de políticas](../policy-reference.md): todos los campos. diff --git a/docs/es/packages.md b/docs/es/packages.md index 69465ef..63c8bac 100644 --- a/docs/es/packages.md +++ b/docs/es/packages.md @@ -7,12 +7,12 @@ Usa el paquete de Python para ejecutar el guard en tu aplicación. Usa un client | Lenguaje | Instalación | Modo y entorno | | --- | --- | --- | | [Python](guide-python.md) | `pip install --pre sqlguardllm` | Motor local en el mismo proceso o servidor HTTP. Python 3.10+ en Linux, macOS y Windows. | -| [Node.js / TypeScript](guide-node.md) | `npm install sqlguardllm` | Remoto por HTTP. Node.js 18+ en Linux, macOS y Windows. | -| [.NET](guide-dotnet.md) | `dotnet add package SqlGuardLlm --prerelease` | Remoto por HTTP. El cliente en el repositorio es compatible con .NET 8 y .NET 10 en Linux, macOS y Windows. | +| [Node.js / TypeScript](guide-node.md) | `npm install sqlguardllm` | Local (el motor viene en el paquete: sin Python ni servidor) o remoto por HTTP. Node.js 18+; motor embebido en linux x64/arm64, macOS x64/arm64 y Windows x64. | +| [.NET](guide-dotnet.md) | `dotnet add package SqlGuardLlm --prerelease` | Local (el motor viene en el paquete: sin Python ni servidor) o remoto por HTTP. .NET 8 y .NET 10; motor embebido en linux-x64, linux-arm64, osx-x64, osx-arm64 y win-x64. | **Paso a paso**, de la instalación a un programa que revisa una consulta permitida y una rechazada, con su salida exacta: [Python](guide-python.md), [Node.js / TypeScript](guide-node.md), [.NET](guide-dotnet.md). -Los clientes de Node.js y .NET necesitan una [instancia de `sqlguardllm serve`](../SERVER.md) activa. Iníciala en un entorno de Python o en un contenedor. Los motores embebidos para [Node.js](https://github.com/jmmana/sqlguardllm/issues/73) y [.NET](https://github.com/jmmana/sqlguardllm/issues/77) están previstos. +Los paquetes de Node.js y .NET llevan el motor y lo ejecutan como proceso hijo de tu aplicación (`SqlGuard.local`, `SqlGuard.CreateLocalAsync`), con la misma API que sus clientes remotos. En una plataforma sin motor embebido (Linux musl como Alpine, otras CPU), con Deno, navegadores o entornos edge, o para compartir un motor entre servicios, usa una [instancia de `sqlguardllm serve`](../SERVER.md) activa, que inicias en un entorno de Python o en un contenedor. Para Python, consulta el [inicio rápido](quickstart.md). Instala `sqlguardllm[yaml]` para cargar políticas YAML, `sqlguardllm[serve]` para cargar YAML en el servidor HTTP o `sqlguardllm[mcp]` para ejecutar el [servidor MCP](../MCP.md). Durante la fase alfa, usa también la opción `--pre` al instalar un extra. diff --git a/docs/es/quickstart.md b/docs/es/quickstart.md index 13b149f..7d2d9d9 100644 --- a/docs/es/quickstart.md +++ b/docs/es/quickstart.md @@ -2,7 +2,7 @@ [Read in English](../quickstart.md) · [Elige un paquete](packages.md) -Esta página es para Python. Para **Node.js / TypeScript** o **.NET**, sigue las guías paso a paso de [Node.js](guide-node.md) y [.NET](guide-dotnet.md): instalan el cliente, inician `sqlguardllm serve` y revisan el mismo tipo de consultas. La [guía de Python](guide-python.md) hace lo mismo con un archivo de política. +Esta página es para Python. Para **Node.js / TypeScript** o **.NET**, sigue las guías paso a paso de [Node.js](guide-node.md) y [.NET](guide-dotnet.md): instalan el paquete, que lleva el motor (sin Python ni servidor), y revisan el mismo tipo de consultas; el modo remoto con `sqlguardllm serve` es la última sección de cada una. La [guía de Python](guide-python.md) hace lo mismo con un archivo de política. ```bash pip install --pre sqlguardllm diff --git a/docs/guide-dotnet.md b/docs/guide-dotnet.md index de8f3db..c012612 100644 --- a/docs/guide-dotnet.md +++ b/docs/guide-dotnet.md @@ -2,18 +2,19 @@ [Leer en español](es/guide-dotnet.md) · [Choose a package](packages.md) · [Python](guide-python.md) · [Node.js](guide-node.md) -The NuGet package `SqlGuardLlm` is a small client with no dependencies beyond `HttpClient` and `System.Text.Json`. The engine runs in `sqlguardllm serve`, an HTTP server next to your application, so .NET gets exactly the same answers as Python. You need the .NET 8 or .NET 10 SDK, and Python 3.10 or later for the server. +The NuGet package `SqlGuardLlm` carries the engine for linux-x64, linux-arm64, osx-x64, osx-arm64 and win-x64 (under `runtimes/{rid}/native/`), so the guard runs as a child process of your app with **no Python and no server**. This is the local mode, and it is what this guide uses. You need the .NET 8 or .NET 10 SDK. If your platform has no engine (another OS or CPU, or musl Linux such as Alpine), use the [remote mode](#remote-mode-a-server-instead-of-the-embedded-engine) with a running server. -!!! note "Today the client needs a running server" - An embedded engine, so that the package works with no Python and no server, is planned in [#86](https://github.com/jmmana/sqlguardllm/issues/86). - -## 1. Write a policy +## 1. Create the project and write a policy ```bash -mkdir guard-demo && cd guard-demo +dotnet new console -n GuardDemo +cd GuardDemo +dotnet add package SqlGuardLlm --prerelease ``` -Save this as `policy.json` in that folder. The server reads it; the client never does. +`--prerelease` is needed while the package is in alpha. The package is on [NuGet](https://www.nuget.org/packages/SqlGuardLlm). + +Save this as `policy.json` in the `GuardDemo` folder: ```json { @@ -30,45 +31,18 @@ Save this as `policy.json` in that folder. The server reads it; the client never The model may read three tables ([`tables`](policy-reference.md#tables)), never `customers.email` ([`hidden_columns`](policy-reference.md#hidden_columns)), only the invoices and branches of the user's branches ([`row_filters`](policy-reference.md#row_filters)), and at most 100 rows ([`max_rows`](policy-reference.md#max_rows)). -## 2. Start the server, in another terminal - -From the same folder, with [uv](https://docs.astral.sh/uv/): - -```bash -uvx sqlguardllm serve --policy policy.json --port 8787 -``` - -With [pipx](https://pipx.pypa.io/) it is `pipx run sqlguardllm serve --policy policy.json --port 8787`. With plain pip: - -```bash -python -m venv .venv -source .venv/bin/activate # Windows: .venv\Scripts\activate -pip install --pre sqlguardllm -sqlguardllm serve --policy policy.json --port 8787 -``` - -It prints a line like `sqlguardllm 0.5.0a5 listening on http://127.0.0.1:8787 (no token)` and keeps running: leave that terminal open. It only listens on your machine. Before exposing it to other hosts, set a [token](SERVER.md#token). There is no published Docker image yet; you can build one from the repository's [Dockerfile](SERVER.md#docker). - -## 3. Install the client - -In the first terminal, in `guard-demo`: - -```bash -dotnet new console -n GuardDemo -cd GuardDemo -dotnet add package SqlGuardLlm --prerelease -``` - -`--prerelease` is needed while the package is in alpha. The package is on [NuGet](https://www.nuget.org/packages/SqlGuardLlm) since 0.5.0-alpha.2. - -## 4. Check one allowed and one rejected query +## 2. Check one allowed and one rejected query Replace `Program.cs` with: ```csharp using SqlGuardLlm; -using var guard = new SqlGuardClient("http://localhost:8787"); +// Starts the embedded engine (the SHA-256 of its files is verified first) and loads the policy. +await using var guard = await SqlGuard.CreateLocalAsync(new SqlGuardLocalOptions +{ + PolicyJson = await File.ReadAllTextAsync("policy.json"), +}); // The manager of branch 1. In your app this comes from the signed-in user, never from the model. var context = new Dictionary @@ -83,7 +57,9 @@ var emails = await guard.CheckAsync("SELECT name, email FROM customers", context Console.WriteLine($"{emails.Ok} {string.Join("; ", emails.Violations.Select(v => $"{v.Code}: {v.Message}"))}"); ``` -## 5. Run it +`SqlGuard.CreateLocalAsync` returns an `ISqlGuard`, the same interface (`CheckAsync`, `EnforceAsync`, `ExplainAsync`, each with a `CancellationToken`) as the remote `SqlGuardClient`. It is thread-safe: share one instance for the whole app. + +## 3. Run it ```bash dotnet run @@ -96,11 +72,13 @@ True SELECT id, total FROM (SELECT * FROM invoices WHERE branch_id IN (1)) AS in False hidden_column: customers.email is a hidden column ``` -The first query is allowed and rewritten: only branch 1's invoices, with a `LIMIT`. Run `invoices.Sql`, never the original text, with a read-only database user. The second is rejected because the policy hides `customers.email`. Start the server with `--language es` for messages in Spanish. +The first query is allowed and rewritten: only branch 1's invoices, with a `LIMIT`. Run `invoices.Sql`, never the original text, with a read-only database user. The second is rejected because the policy hides `customers.email`. Set `Language = "es"` in `SqlGuardLocalOptions` for messages in Spanish. + +The client **fails closed**: if the engine cannot start, a file does not match its SHA-256, the engine crashes or a call times out, the call throws a `SqlGuardException` (and the engine is restarted with a backoff) instead of letting the query through, so never catch that exception and run the SQL anyway. On an unsupported platform the exception has code `engine_unsupported` and its message names the remote mode. -If you see `SqlGuardException: Could not reach the sqlguardllm server.`, the server is not running. The client **fails closed**: it throws instead of letting the query through, so never catch that exception and run the SQL anyway. +It also works with `dotnet publish -r `, self-contained and single-file publishes (the `sqlguardllm-engine` folder sits next to the executable), Native AOT, and Linux container images (glibc based, such as `mcr.microsoft.com/dotnet/runtime-deps`; not Alpine). -## 6. Change a rule +## 4. Change a rule To let the model read the email masked, replace the `hidden_columns` line of `policy.json` with: @@ -108,10 +86,27 @@ To let the model read the email masked, replace the `hidden_columns` line of `po "masked_columns": {"customers.email": "partial"}, ``` -Stop the server (Ctrl+C), start it again, and run `dotnet run`. The second line becomes `True` with no violations: the query is allowed, and `ceo@acme.example` comes back as `ce***` ([`masked_columns`](policy-reference.md#masked_columns)). You can flip these rules without installing anything in the [playground](https://jmmana.github.io/sqlguardllm/playground/). +Run `dotnet run` again. The second line becomes `True` with no violations: the query is allowed, and `ceo@acme.example` comes back as `ce***` ([`masked_columns`](policy-reference.md#masked_columns)). You can flip these rules without installing anything in the [playground](https://jmmana.github.io/sqlguardllm/playground/). + +## Remote mode: a server instead of the embedded engine + +Use it when several services share one policy, or on a platform that has no embedded engine. The engine then runs in `sqlguardllm serve`, an HTTP server next to your application (Python 3.10 or later). In another terminal, from the same folder, with [uv](https://docs.astral.sh/uv/): + +```bash +uvx sqlguardllm serve --policy policy.json --port 8787 +``` + +With [pipx](https://pipx.pypa.io/) it is `pipx run sqlguardllm serve --policy policy.json --port 8787`. With plain pip: `pip install --pre sqlguardllm`, then `sqlguardllm serve --policy policy.json --port 8787`. It only listens on your machine; before exposing it to other hosts, set a [token](SERVER.md#token). In `Program.cs`, replace the `await using var guard = ...` statement with: + +```csharp +using var guard = new SqlGuardClient("http://localhost:8787"); +``` + +The output is the same. If you see `SqlGuardException: Could not reach the sqlguardllm server.`, the server is not running; the client fails closed there too. Start the server with `--language es` for messages in Spanish. After editing `policy.json`, restart the server. ## Next -- [Client README](../clients/dotnet/README.md): `EnforceAsync`, dependency injection with your own `HttpClient`, Dapper and ADO.NET, tokens and errors. +- [Client README](../clients/dotnet/README.md): local and remote mode, `EnforceAsync`, dependency injection, Dapper and ADO.NET, tokens and errors. +- [Recipes](RECIPES.md#net): `AddSqlGuard`, EF Core, Dapper, Semantic Kernel and Microsoft.Extensions.AI. - [HTTP server](SERVER.md): flags, the `/v1` contract and security notes. - [Policy reference](policy-reference.md): every field. diff --git a/docs/guide-node.md b/docs/guide-node.md index 9afa176..33914b4 100644 --- a/docs/guide-node.md +++ b/docs/guide-node.md @@ -2,10 +2,7 @@ [Leer en español](es/guide-node.md) · [Choose a package](packages.md) · [Python](guide-python.md) · [.NET](guide-dotnet.md) -The npm package `sqlguardllm` is a small client with no dependencies. The engine runs in `sqlguardllm serve`, an HTTP server next to your application, so Node.js gets exactly the same answers as Python. You need Node.js 18 or later, and Python 3.10 or later for the server. - -!!! note "Local mode or remote mode" - `npm install sqlguardllm` also installs the engine for your platform (linux x64/arm64, macOS x64/arm64, Windows x64), so `await SqlGuard.local({ policyPath: "policy.json" })` runs the guard with no Python and no server (see the [package README](https://github.com/jmmana/sqlguardllm/tree/main/clients/node#local-mode)). This guide uses the remote mode below. If your platform has no engine package (for example Alpine/musl), or you run on Deno, a browser or an edge runtime, use the remote mode with a running server. +The npm package `sqlguardllm` runs the engine for you: `npm install sqlguardllm` also installs the engine for your platform (linux x64/arm64, macOS x64/arm64, Windows x64), so the guard runs inside your Node.js process tree with **no Python and no server**. This is the local mode, and it is what this guide uses. You need Node.js 18 or later. If your platform has no engine package (for example Alpine/musl), or you run on Deno, a browser or an edge runtime, use the [remote mode](#remote-mode-a-server-instead-of-the-embedded-engine) with a running server. ## 1. Write a policy @@ -13,7 +10,7 @@ The npm package `sqlguardllm` is a small client with no dependencies. The engine mkdir guard-demo && cd guard-demo ``` -Save this as `policy.json` in that folder. The server reads it; the client never does. +Save this as `policy.json` in that folder. ```json { @@ -30,56 +27,40 @@ Save this as `policy.json` in that folder. The server reads it; the client never The model may read three tables ([`tables`](policy-reference.md#tables)), never `customers.email` ([`hidden_columns`](policy-reference.md#hidden_columns)), only the invoices and branches of the user's branches ([`row_filters`](policy-reference.md#row_filters)), and at most 100 rows ([`max_rows`](policy-reference.md#max_rows)). -## 2. Start the server, in another terminal - -From the same folder, with [uv](https://docs.astral.sh/uv/): - -```bash -uvx sqlguardllm serve --policy policy.json --port 8787 -``` - -With [pipx](https://pipx.pypa.io/) it is `pipx run sqlguardllm serve --policy policy.json --port 8787`. With plain pip: - -```bash -python -m venv .venv -source .venv/bin/activate # Windows: .venv\Scripts\activate -pip install --pre sqlguardllm -sqlguardllm serve --policy policy.json --port 8787 -``` - -It prints a line like `sqlguardllm 0.5.0a5 listening on http://127.0.0.1:8787 (no token)` and keeps running: leave that terminal open. It only listens on your machine. Before exposing it to other hosts, set a [token](SERVER.md#token). There is no published Docker image yet; you can build one from the repository's [Dockerfile](SERVER.md#docker). - -## 3. Install the client - -In the first terminal, in `guard-demo`: +## 2. Install the client ```bash npm init -y npm install sqlguardllm ``` -## 4. Check one allowed and one rejected query +## 3. Check one allowed and one rejected query Save this as `check.mjs`: ```js import { SqlGuard } from "sqlguardllm"; -const guard = new SqlGuard({ baseUrl: "http://localhost:8787" }); +// Starts the embedded engine (its SHA-256 is verified first) and loads the policy. +const guard = await SqlGuard.local({ policyPath: "policy.json" }); // The manager of branch 1. In your app this comes from the signed-in user, never from the model. const context = { user: { branches: [1] } }; -const invoices = await guard.check("SELECT id, total FROM invoices ORDER BY id", context); -console.log(invoices.ok, invoices.sql); +try { + const invoices = await guard.check("SELECT id, total FROM invoices ORDER BY id", context); + console.log(invoices.ok, invoices.sql); -const emails = await guard.check("SELECT name, email FROM customers", context); -console.log(emails.ok, emails.violations.map((v) => `${v.code}: ${v.message}`)); + const emails = await guard.check("SELECT name, email FROM customers", context); + console.log(emails.ok, emails.violations.map((v) => `${v.code}: ${v.message}`)); +} finally { + await guard.close(); // stops the engine +} ``` -The package ships its type declarations, so the same code works in TypeScript. +The package ships its type declarations, so the same code works in TypeScript (`import { SqlGuard } from "sqlguardllm"`, `const guard: SqlGuard = await SqlGuard.local(...)`). -## 5. Run it +## 4. Run it ```bash node check.mjs @@ -92,11 +73,11 @@ true SELECT id, total FROM (SELECT * FROM invoices WHERE branch_id IN (1)) AS in false [ 'hidden_column: customers.email is a hidden column' ] ``` -The first query is allowed and rewritten: only branch 1's invoices, with a `LIMIT`. Run `invoices.sql`, never the original text, with a read-only database user. The second is rejected because the policy hides `customers.email`. Start the server with `--language es` for messages in Spanish. +The first query is allowed and rewritten: only branch 1's invoices, with a `LIMIT`. Run `invoices.sql`, never the original text, with a read-only database user. The second is rejected because the policy hides `customers.email`. Pass `language: "es"` to `SqlGuard.local` for messages in Spanish. -If you see `SqlGuardError: cannot reach the sqlguardllm server`, the server is not running. The client **fails closed**: it throws instead of letting the query through, so never catch that error and run the SQL anyway. +The client **fails closed**: if the engine cannot start, crashes or times out, the call throws a `SqlGuardError` (and the engine is restarted with a backoff) instead of letting the query through, so never catch that error and run the SQL anyway. On an unsupported platform the error is `unsupported_platform` and its message names the remote mode. -## 6. Change a rule +## 5. Change a rule To let the model read the email masked, replace the `hidden_columns` line of `policy.json` with: @@ -104,10 +85,27 @@ To let the model read the email masked, replace the `hidden_columns` line of `po "masked_columns": {"customers.email": "partial"}, ``` -Stop the server (Ctrl+C), start it again, and run `node check.mjs`. The second line becomes `true []`: the query is allowed, and `ceo@acme.example` comes back as `ce***` ([`masked_columns`](policy-reference.md#masked_columns)). You can flip these rules without installing anything in the [playground](https://jmmana.github.io/sqlguardllm/playground/). +Run `node check.mjs` again. The second line becomes `true []`: the query is allowed, and `ceo@acme.example` comes back as `ce***` ([`masked_columns`](policy-reference.md#masked_columns)). You can flip these rules without installing anything in the [playground](https://jmmana.github.io/sqlguardllm/playground/). + +## Remote mode: a server instead of the embedded engine + +Use it when several services share one policy, or on a platform that has no embedded engine. The engine then runs in `sqlguardllm serve`, an HTTP server next to your application (Python 3.10 or later). In another terminal, from the same folder, with [uv](https://docs.astral.sh/uv/): + +```bash +uvx sqlguardllm serve --policy policy.json --port 8787 +``` + +With [pipx](https://pipx.pypa.io/) it is `pipx run sqlguardllm serve --policy policy.json --port 8787`. With plain pip: `pip install --pre sqlguardllm`, then `sqlguardllm serve --policy policy.json --port 8787`. It only listens on your machine; before exposing it to other hosts, set a [token](SERVER.md#token). In `check.mjs`, replace the first line of code with: + +```js +const guard = new SqlGuard({ baseUrl: "http://localhost:8787" }); +``` + +(and drop the `finally` block: there is no engine to close). The output is the same. If you see `SqlGuardError: cannot reach the sqlguardllm server`, the server is not running; the client fails closed there too. Start the server with `--language es` for messages in Spanish. After editing `policy.json`, restart the server. ## Next -- [Client README](../clients/node/README.md): `enforce`, `wrap` for `pg` and `mysql2`, tokens, timeouts and errors. +- [Client README](../clients/node/README.md): local and remote mode, `enforce`, `wrap` for `pg` and `mysql2`, tokens, timeouts and errors. +- [Recipes](RECIPES.md#nodejs): LangChain.js, the Vercel AI SDK, `pg`, `mysql2` and Prisma. - [HTTP server](SERVER.md): flags, the `/v1` contract and security notes. - [Policy reference](policy-reference.md): every field. diff --git a/docs/packages.md b/docs/packages.md index b497b36..fb05b57 100644 --- a/docs/packages.md +++ b/docs/packages.md @@ -7,12 +7,12 @@ Use the Python package to run the guard in your application. Use an HTTP client | Language | Install | Mode and runtime | | --- | --- | --- | | [Python](guide-python.md) | `pip install --pre sqlguardllm` | Local in-process engine or HTTP server. Python 3.10+ on Linux, macOS and Windows. | -| [Node.js / TypeScript](guide-node.md) | `npm install sqlguardllm` | Remote over HTTP. Node.js 18+ on Linux, macOS and Windows. | -| [.NET](guide-dotnet.md) | `dotnet add package SqlGuardLlm --prerelease` | Remote over HTTP. The source client targets .NET 8 and .NET 10 on Linux, macOS and Windows. | +| [Node.js / TypeScript](guide-node.md) | `npm install sqlguardllm` | Local (the engine ships in the package: no Python, no server) or remote over HTTP. Node.js 18+; embedded engine on linux x64/arm64, macOS x64/arm64 and Windows x64. | +| [.NET](guide-dotnet.md) | `dotnet add package SqlGuardLlm --prerelease` | Local (the engine ships in the package: no Python, no server) or remote over HTTP. .NET 8 and .NET 10; embedded engine on linux-x64, linux-arm64, osx-x64, osx-arm64 and win-x64. | **Step by step**, from install to a program that checks one allowed and one rejected query, with its exact output: [Python](guide-python.md), [Node.js / TypeScript](guide-node.md), [.NET](guide-dotnet.md). -The Node.js and .NET clients use a running [`sqlguardllm serve` instance](SERVER.md). Start it in a Python environment or a container. Embedded engines for [Node.js](https://github.com/jmmana/sqlguardllm/issues/73) and [.NET](https://github.com/jmmana/sqlguardllm/issues/77) are planned. +The Node.js and .NET packages carry the engine and run it as a child process of your application (`SqlGuard.local`, `SqlGuard.CreateLocalAsync`), with the same API as their remote clients. On a platform without an embedded engine (musl Linux such as Alpine, other CPUs), Deno, browsers or edge runtimes, or to share one engine between services, use a running [`sqlguardllm serve` instance](SERVER.md), which you start in a Python environment or a container. For Python, start with the [quickstart](quickstart.md). Install `sqlguardllm[yaml]` to load YAML policies, `sqlguardllm[serve]` to load YAML in the HTTP server, or `sqlguardllm[mcp]` to run the [MCP server](MCP.md). Use the same `--pre` flag when installing an extra during the alpha. diff --git a/docs/quickstart.md b/docs/quickstart.md index 4c4fcf1..1b8b378 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -2,7 +2,7 @@ [Leer en español](es/quickstart.md) · [Choose a package](packages.md) -This page is for Python. For **Node.js / TypeScript** or **.NET**, follow the step-by-step guides for [Node.js](guide-node.md) and [.NET](guide-dotnet.md): they install the client, start `sqlguardllm serve` and check the same kind of queries. The [Python guide](guide-python.md) does the same with a policy file. +This page is for Python. For **Node.js / TypeScript** or **.NET**, follow the step-by-step guides for [Node.js](guide-node.md) and [.NET](guide-dotnet.md): they install the package, which carries the engine (no Python, no server), and check the same kind of queries; the remote mode with `sqlguardllm serve` is the last section of each. The [Python guide](guide-python.md) does the same with a policy file. ```bash pip install --pre sqlguardllm diff --git a/examples/node/run.mjs b/examples/node/run.mjs index e9a7e71..431c12b 100644 --- a/examples/node/run.mjs +++ b/examples/node/run.mjs @@ -7,7 +7,9 @@ import { ALLOWED_SQL, CONTEXT, HIDDEN_COLUMN_SQL, POLICY, WRITE_SQL, createDemoD import { guardedQuery, pgRunner } from "./guarded-tools.mjs"; // Local mode: the embedded engine, no server. For a server use `new SqlGuard({ baseUrl, token })`. -const guard = await SqlGuard.local({ policy: process.env.DATABASE_URL ? { ...POLICY, dialect: "postgres" } : POLICY }); +// SQLGUARD_ENGINE_CMD (e.g. "uv run sqlguardllm engine --stdio") runs another engine, such as a source checkout. +const engine = process.env.SQLGUARD_ENGINE_CMD?.split(" "); +const guard = await SqlGuard.local({ policy: process.env.DATABASE_URL ? { ...POLICY, dialect: "postgres" } : POLICY, engine }); let run; let pool; if (process.env.DATABASE_URL) { diff --git a/examples/node/test/recipes.test.mjs b/examples/node/test/recipes.test.mjs index d221e34..4846403 100644 --- a/examples/node/test/recipes.test.mjs +++ b/examples/node/test/recipes.test.mjs @@ -3,11 +3,12 @@ // The guard is the real client talking to a stand-in server (a fake `fetch`) that applies the demo // policy in miniature, so no engine binary is needed. Framework recipes are skipped when the framework // isn't installed; SQLGUARDLLM_RECIPES=1 turns a missing framework into a failure. PostgreSQL runs -// when DATABASE_URL is set. +// when DATABASE_URL is set. With SQLGUARD_ENGINE_CMD (the engine command, e.g. "uv run sqlguardllm engine --stdio") +// the last tests use the REAL engine in local mode, on SQLite and, with DATABASE_URL, on PostgreSQL. import assert from "node:assert/strict"; import { test } from "node:test"; import { SqlGuard } from "sqlguardllm"; -import { ALLOWED_SQL, CONTEXT, HIDDEN_COLUMN_SQL, WRITE_SQL, createDemoDatabase, sqliteRunner } from "../demo-data.mjs"; +import { ALLOWED_SQL, CONTEXT, HIDDEN_COLUMN_SQL, POLICY, SCRIPT, WRITE_SQL, createDemoDatabase, sqliteRunner } from "../demo-data.mjs"; import { guardedQuery, langchainSqlTool, mysql2Runner, pgRunner, prismaRunner, vercelSqlTool } from "../guarded-tools.mjs"; const violation = (code, message) => ({ code, message, detail: "" }); @@ -126,3 +127,52 @@ test("PostgreSQL through pg", async (t) => { await pool.end(); } }); + +// The real engine (local mode) with the real demo policy, executing on a real database. CI sets SQLGUARD_ENGINE_CMD. +const engineCmd = process.env.SQLGUARD_ENGINE_CMD?.split(" "); + +async function realGuard(t, policy) { + if (!engineCmd) { + if (process.env.SQLGUARDLLM_RECIPES === "1") throw new Error("SQLGUARDLLM_RECIPES=1 but SQLGUARD_ENGINE_CMD is not set"); + t.skip("SQLGUARD_ENGINE_CMD is not set"); + return null; + } + return SqlGuard.local({ policy, engine: engineCmd, timeoutMs: 60_000 }); +} + +async function exerciseRealGuard(guard, run) { + const query = guardedQuery(guard, run, () => CONTEXT); + const ok = await query(ALLOWED_SQL); + assert.equal(ok.ok, true); + assert.equal(Number(ok.rows[0].revenue), 350); // invoice 12 (branch 3) is filtered out by the row filter + const hidden = await query(HIDDEN_COLUMN_SQL); + assert.equal(hidden.ok, false); + assert.match(hidden.feedback, /email/); + assert.equal((await query(WRITE_SQL)).ok, false); +} + +test("real engine on SQLite", async (t) => { + const guard = await realGuard(t, POLICY); + if (!guard) return; + try { + await exerciseRealGuard(guard, sqliteRunner(createDemoDatabase())); + } finally { + await guard.close(); + } +}); + +test("real engine on PostgreSQL through pg", async (t) => { + if (!process.env.DATABASE_URL) return t.skip("DATABASE_URL is not set"); + const guard = await realGuard(t, { ...POLICY, dialect: "postgres" }); + if (!guard) return; + const pg = (await import("pg")).default; + const client = new pg.Client({ connectionString: process.env.DATABASE_URL }); // one connection: the tables are TEMP + await client.connect(); + try { + await client.query(SCRIPT.replace(/CREATE TABLE/g, "CREATE TEMP TABLE")); + await exerciseRealGuard(guard, pgRunner(client)); + } finally { + await guard.close(); + await client.end(); + } +}); From 645d03f2c2ace5e35ec7abefd99402cf852ff5a1 Mon Sep 17 00:00:00 2001 From: Juan Castillo Date: Fri, 27 Nov 2026 07:08:13 -0500 Subject: [PATCH 2/4] Track clients/dotnet/build (the root .gitignore ignored it) stage-engines.py and SqlGuardLlm.targets, needed by the NuGet packing job, were never committed because build/ is ignored. Add the exception and the files. Co-Authored-By: Claude Sonnet 5.5 --- .gitignore | 1 + clients/dotnet/build/SqlGuardLlm.targets | 19 +++++ clients/dotnet/build/stage-engines.py | 88 ++++++++++++++++++++++++ 3 files changed, 108 insertions(+) create mode 100644 clients/dotnet/build/SqlGuardLlm.targets create mode 100644 clients/dotnet/build/stage-engines.py diff --git a/.gitignore b/.gitignore index f4bcbc8..c36c599 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,7 @@ __pycache__/ htmlcov/ dist/ build/ +!clients/dotnet/build/ *.egg-info/ site/ .env diff --git a/clients/dotnet/build/SqlGuardLlm.targets b/clients/dotnet/build/SqlGuardLlm.targets new file mode 100644 index 0000000..d38ba5b --- /dev/null +++ b/clients/dotnet/build/SqlGuardLlm.targets @@ -0,0 +1,19 @@ + + + + + <_SqlGuardEngineFile Include="@(NativeCopyLocalItems)" + Condition="$([System.Text.RegularExpressions.Regex]::IsMatch('%(FullPath)', 'native[/\\]sqlguardllm-engine[/\\]'))"> + $([System.Text.RegularExpressions.Regex]::Replace('%(RelativeDir)', '^.*native[/\\](?=sqlguardllm-engine[/\\])', '')) + + + + + + diff --git a/clients/dotnet/build/stage-engines.py b/clients/dotnet/build/stage-engines.py new file mode 100644 index 0000000..773b325 --- /dev/null +++ b/clients/dotnet/build/stage-engines.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python3 +"""Stage the standalone engines for the NuGet package. + + python clients/dotnet/build/stage-engines.py --engines engines # all five platforms + python clients/dotnet/build/stage-engines.py --engines engines --platform macos-arm64 + python clients/dotnet/build/stage-engines.py --check-nupkg clients/dotnet/out/SqlGuardLlm.0.5.0-alpha.5.nupkg + +--engines is the folder scripts/fetch-engine.py unpacked (``//sqlguardllm-engine``), +or any folder with that shape. Each engine is copied (symbolic links resolved) to +``clients/dotnet/src/SqlGuardLlm/engines//sqlguardllm-engine/`` next to an ``engine.sha256`` that lists the SHA-256 +of every file; SqlGuardLlm.csproj packs that folder to ``runtimes//native/sqlguardllm-engine/`` and the client +recomputes every hash before it starts the engine. ``--check-nupkg`` fails when a package passes 150 MB (the point at +which the engines must be split into SqlGuardLlm.Engine. packages) or lacks one of the five engines. +Standard library only. Exit 1 on any problem. +""" + +from __future__ import annotations + +import argparse +import hashlib +import shutil +import sys +import zipfile +from pathlib import Path + +RIDS = {"linux-x64": "linux-x64", "linux-arm64": "linux-arm64", "macos-x64": "osx-x64", "macos-arm64": "osx-arm64", "windows-x64": "win-x64"} +FOLDER = "sqlguardllm-engine" +MANIFEST = "engine.sha256" +LIMIT = 150 * 1024 * 1024 +DEST = Path(__file__).resolve().parent.parent / "src" / "SqlGuardLlm" / "engines" + + +def find_engine_folder(root: Path, rid: str) -> Path: + exe = FOLDER + (".exe" if rid.startswith("win-") else "") + found = sorted(p.parent for p in root.rglob(exe) if p.is_file()) + if len(found) != 1: + raise SystemExit(f"expected one {exe} under {root}, found {len(found)}") + return found[0] + + +def write_manifest(folder: Path) -> int: + lines = [] + for path in sorted(folder.rglob("*")): + if path.is_file() and path.name != MANIFEST: + lines.append(f"{hashlib.sha256(path.read_bytes()).hexdigest()} {path.relative_to(folder).as_posix()}") + (folder / MANIFEST).write_text("\n".join(lines) + "\n", encoding="utf-8", newline="\n") + return len(lines) + + +def stage(engines: Path, platforms: list[str]) -> None: + shutil.rmtree(DEST, ignore_errors=True) + for plat in platforms: + rid = RIDS[plat] + source = find_engine_folder(engines / plat, rid) + target = DEST / rid / FOLDER + shutil.copytree(source, target, symlinks=False) + print(f"{rid}: {write_manifest(target)} files from {source}") + + +def check_nupkg(path: Path, partial: bool = False) -> None: + size = path.stat().st_size + print(f"{path.name}: {size / 1024 / 1024:.1f} MiB (limit {LIMIT // 1024 // 1024} MiB)") + with zipfile.ZipFile(path) as z: + names = z.namelist() + missing = [r for r in RIDS.values() if f"runtimes/{r}/native/{FOLDER}/{MANIFEST}" not in names] + if missing and not partial: + raise SystemExit(f"the package carries no engine for: {', '.join(missing)}") + if size > LIMIT: + raise SystemExit("the package is over 150 MB: split the engines into SqlGuardLlm.Engine. packages") + + +def main() -> None: + p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + p.add_argument("--engines", type=Path, help="folder unpacked by scripts/fetch-engine.py") + p.add_argument("--platform", action="append", choices=sorted(RIDS), help="only these (default: all five)") + p.add_argument("--check-nupkg", type=Path, help="check a packed .nupkg instead of staging") + p.add_argument("--allow-partial", action="store_true", help="with --check-nupkg: do not require all five engines") + a = p.parse_args() + if a.check_nupkg: + check_nupkg(a.check_nupkg, a.allow_partial) + elif a.engines: + stage(a.engines, a.platform or list(RIDS)) + else: + p.error("give --engines or --check-nupkg") + + +if __name__ == "__main__": + sys.exit(main()) From 626b0317d41966fbdd7c4f0c9d0aa3b4d70efbe7 Mon Sep 17 00:00:00 2001 From: Juan Castillo Date: Fri, 27 Nov 2026 07:25:06 -0500 Subject: [PATCH 3/4] dotnet-client: escape the WarningsAsErrors list for MSBuild (; -> %3B) Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/dotnet-client.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/dotnet-client.yml b/.github/workflows/dotnet-client.yml index 4d69a7c..595798a 100644 --- a/.github/workflows/dotnet-client.yml +++ b/.github/workflows/dotnet-client.yml @@ -121,9 +121,9 @@ jobs: run: | set -e S=clients/dotnet/smoke; V=$SQLGUARD_PKG_VERSION - dotnet publish $S -c Release -r ${{ matrix.rid }} --self-contained -p:PublishTrimmed=true -p:TrimmerSingleWarn=false "-p:WarningsAsErrors=$WARNINGS" -p:SqlGuardLlmVersion=$V -o out-trim + dotnet publish $S -c Release -r ${{ matrix.rid }} --self-contained -p:PublishTrimmed=true -p:TrimmerSingleWarn=false "-p:WarningsAsErrors=${WARNINGS//;/%3B}" -p:SqlGuardLlmVersion=$V -o out-trim ./out-trim/Smoke - dotnet publish $S -c Release -r ${{ matrix.rid }} -p:PublishAot=true "-p:WarningsAsErrors=$WARNINGS" -p:SqlGuardLlmVersion=$V -o out-aot + dotnet publish $S -c Release -r ${{ matrix.rid }} -p:PublishAot=true "-p:WarningsAsErrors=${WARNINGS//;/%3B}" -p:SqlGuardLlmVersion=$V -o out-aot ./out-aot/Smoke - name: Linux container image (no .NET inside) if: startsWith(matrix.rid, 'linux') From 5538a18902157a4fe43325c9665db8607ff0a973 Mon Sep 17 00:00:00 2001 From: Juan Castillo Date: Fri, 27 Nov 2026 07:43:09 -0500 Subject: [PATCH 4/4] dotnet tests: run sequentially (fake engine scripts hit ETXTBSY on Linux) Co-Authored-By: Claude Sonnet 5.5 --- clients/dotnet/tests/SqlGuardLlm.Tests/AssemblyInfo.cs | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 clients/dotnet/tests/SqlGuardLlm.Tests/AssemblyInfo.cs diff --git a/clients/dotnet/tests/SqlGuardLlm.Tests/AssemblyInfo.cs b/clients/dotnet/tests/SqlGuardLlm.Tests/AssemblyInfo.cs new file mode 100644 index 0000000..9b2b295 --- /dev/null +++ b/clients/dotnet/tests/SqlGuardLlm.Tests/AssemblyInfo.cs @@ -0,0 +1,6 @@ +using Xunit; + +// Tests write small shell scripts and run them as fake engines. On Linux, starting a process while +// another thread still has a script open for writing fails with "text file busy" (ETXTBSY), so the +// tests of this assembly run one after another. +[assembly: CollectionBehavior(DisableTestParallelization = true)]