bricksentry 0.1.5__tar.gz → 0.1.6__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {bricksentry-0.1.5 → bricksentry-0.1.6}/CHANGELOG.md +8 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/PKG-INFO +70 -4
- {bricksentry-0.1.5 → bricksentry-0.1.6}/README.md +69 -3
- {bricksentry-0.1.5 → bricksentry-0.1.6}/action.yml +12 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/pyproject.toml +1 -1
- {bricksentry-0.1.5 → bricksentry-0.1.6}/src/bricksentry/__init__.py +1 -1
- {bricksentry-0.1.5 → bricksentry-0.1.6}/src/bricksentry/assess.py +11 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/src/bricksentry/cli.py +44 -4
- {bricksentry-0.1.5 → bricksentry-0.1.6}/src/bricksentry/config.py +13 -2
- bricksentry-0.1.6/src/bricksentry/notify.py +156 -0
- bricksentry-0.1.6/src/bricksentry/policy_templates.py +126 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/src/bricksentry/preview.py +29 -3
- bricksentry-0.1.6/tests/test_notify_templates.py +142 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/.gitignore +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/CONTRIBUTING.md +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/LICENSE +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/SECURITY.md +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/examples/databricks/bricksentry.yml +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/examples/databricks/bricksentry_quickstart.ipynb +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/examples/databricks/bricksentry_quickstart.py +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/examples/databricks/github-workflow.yml +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/examples/databricks/policy.yml +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/examples/demo/agent_loop_demo.py +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/scripts/build_notebook.py +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/src/bricksentry/agent_tools.py +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/src/bricksentry/backends/__init__.py +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/src/bricksentry/backends/base.py +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/src/bricksentry/backends/databricks_backend.py +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/src/bricksentry/backends/duckdb_backend.py +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/src/bricksentry/changes.py +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/src/bricksentry/demo.py +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/src/bricksentry/diff.py +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/src/bricksentry/explain.py +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/src/bricksentry/github.py +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/src/bricksentry/lineage.py +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/src/bricksentry/mcp_server.py +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/src/bricksentry/models.py +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/src/bricksentry/policy.py +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/src/bricksentry/py.typed +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/src/bricksentry/report.py +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/tests/conftest.py +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/tests/test_assess_policy.py +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/tests/test_databricks_and_uc.py +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/tests/test_demo.py +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/tests/test_diff.py +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/tests/test_notebook.py +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/tests/test_preview_agents.py +0 -0
- {bricksentry-0.1.5 → bricksentry-0.1.6}/tests/test_sample_guard_and_store.py +0 -0
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.1.6 (2026-11-11)
|
|
4
|
+
|
|
5
|
+
- Slack and Teams alerts. Set `notify:` in bricksentry.yml (or `BRICKSENTRY_SLACK_WEBHOOK` / `BRICKSENTRY_TEAMS_WEBHOOK`) and `assess` / `preview` post the verdict, the rules that fired, the reviewers and a PR link when the verdict reaches `notify.on` (default `needs_human`). `--no-notify` turns it off; `Sentry.notify()` does it from Python; the GitHub Action takes `slack-webhook`, `teams-webhook` and `notify-on`. A failed webhook never changes the verdict.
|
|
6
|
+
- Policy templates: `default`, `strict`, `pii`, `certified` and `finance`. Use `policy: builtin:<name>`, `bricksentry init --policy <name>`, or list them with `bricksentry policies`.
|
|
7
|
+
- When `preview_write` refuses DROP, TRUNCATE, ALTER, GRANT, REVOKE, VACUUM or RESTORE, the error now says what to do instead.
|
|
8
|
+
- Listed in the official MCP Registry as `io.github.bricksentry/bricksentry` (published automatically on each release).
|
|
9
|
+
- A complete copy-paste GitHub Actions workflow in the README.
|
|
10
|
+
|
|
3
11
|
## 0.1.5 (2026-11-10)
|
|
4
12
|
|
|
5
13
|
- Clearer MCP tool definitions for agents. Each tool now says when to use it versus its sibling tools and what it returns, and every parameter has a description in the tool schema (for example the `candidates` map format for `assess_change`). No behavior changes.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: bricksentry
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.6
|
|
4
4
|
Summary: Change-safety for Databricks pipelines and the AI agents that edit them: data diffs, Unity Catalog blast radius, policy verdicts and rollback plans.
|
|
5
5
|
Project-URL: Homepage, https://bricksentry.org
|
|
6
6
|
Project-URL: Documentation, https://bricksentry.org/docs
|
|
@@ -47,6 +47,8 @@ Description-Content-Type: text/markdown
|
|
|
47
47
|
|
|
48
48
|
# Welcome to bricksentry
|
|
49
49
|
|
|
50
|
+
<!-- mcp-name: io.github.bricksentry/bricksentry -->
|
|
51
|
+
|
|
50
52
|
[](https://pypi.org/project/bricksentry/) [](https://pypi.org/project/bricksentry/) [](https://github.com/bricksentry/bricksentry/actions/workflows/ci.yml) [](https://github.com/bricksentry/bricksentry/actions/workflows/lint.yml) [](https://github.com/bricksentry/bricksentry/actions/workflows/ci.yml) [](LICENSE)
|
|
51
53
|
|
|
52
54
|
***The safety check for data changes in the AI era.***
|
|
@@ -135,6 +137,8 @@ To watch the whole loop, run `bricksentry demo` (see the top of this page). `bri
|
|
|
135
137
|
|
|
136
138
|
```bash
|
|
137
139
|
bricksentry init # starter bricksentry.yml + policy.yml
|
|
140
|
+
bricksentry init --policy finance # ...or start from a policy template
|
|
141
|
+
bricksentry policies # list the policy templates
|
|
138
142
|
bricksentry impact main.sales.orders # blast radius
|
|
139
143
|
bricksentry diff main.sales.orders main.sales_pr_42.orders
|
|
140
144
|
bricksentry preview main.sales.orders --sql "MERGE INTO {{target}} t USING updates u ON t.order_id = u.order_id WHEN MATCHED THEN UPDATE SET *"
|
|
@@ -171,12 +175,60 @@ Check out with `fetch-depth: 0` and give the job `pull-requests: write` permissi
|
|
|
171
175
|
Or use the bundled GitHub Action, which also writes the report to the job summary:
|
|
172
176
|
|
|
173
177
|
```yaml
|
|
174
|
-
- uses: bricksentry/bricksentry@v0.1.
|
|
178
|
+
- uses: bricksentry/bricksentry@v0.1.6
|
|
175
179
|
with:
|
|
176
180
|
config: bricksentry.yml
|
|
177
181
|
fail-on: needs_human
|
|
178
182
|
```
|
|
179
183
|
|
|
184
|
+
A complete workflow you can copy to `.github/workflows/bricksentry.yml`:
|
|
185
|
+
|
|
186
|
+
```yaml
|
|
187
|
+
name: bricksentry
|
|
188
|
+
on: pull_request
|
|
189
|
+
|
|
190
|
+
permissions:
|
|
191
|
+
contents: read
|
|
192
|
+
pull-requests: write
|
|
193
|
+
|
|
194
|
+
jobs:
|
|
195
|
+
check-data:
|
|
196
|
+
runs-on: ubuntu-latest
|
|
197
|
+
steps:
|
|
198
|
+
- uses: actions/checkout@v4
|
|
199
|
+
with:
|
|
200
|
+
fetch-depth: 0
|
|
201
|
+
# Build this PR's version of your pipeline into a per-PR schema first,
|
|
202
|
+
# for example: databricks bundle deploy -t ci && databricks bundle run -t ci
|
|
203
|
+
- uses: bricksentry/bricksentry@v0.1.6
|
|
204
|
+
with:
|
|
205
|
+
config: bricksentry.yml
|
|
206
|
+
fail-on: needs_human
|
|
207
|
+
slack-webhook: ${{ secrets.SLACK_WEBHOOK_URL }} # optional
|
|
208
|
+
teams-webhook: ${{ secrets.TEAMS_WEBHOOK_URL }} # optional
|
|
209
|
+
env:
|
|
210
|
+
DATABRICKS_HOST: ${{ secrets.DATABRICKS_HOST }}
|
|
211
|
+
DATABRICKS_CLIENT_ID: ${{ secrets.DATABRICKS_CLIENT_ID }}
|
|
212
|
+
DATABRICKS_CLIENT_SECRET: ${{ secrets.DATABRICKS_CLIENT_SECRET }}
|
|
213
|
+
DATABRICKS_WAREHOUSE_ID: ${{ secrets.DATABRICKS_WAREHOUSE_ID }}
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
To make the check binding, mark this job as a required status check in your branch protection rules. Then a `needs_human` or `block` verdict stops the merge, whatever the author or an agent decides.
|
|
217
|
+
|
|
218
|
+
### Alerts in Slack and Teams
|
|
219
|
+
|
|
220
|
+
When the verdict is `needs_human` or worse, bricksentry can post a short alert: the verdict, the rules that fired, who should review, and a link to the PR.
|
|
221
|
+
|
|
222
|
+
```yaml
|
|
223
|
+
# bricksentry.yml
|
|
224
|
+
notify:
|
|
225
|
+
on: needs_human # alert at this verdict or worse
|
|
226
|
+
slack_webhook: env:SLACK_WEBHOOK_URL # Slack incoming webhook
|
|
227
|
+
teams_webhook: env:TEAMS_WEBHOOK_URL # Teams Workflows "webhook request" URL
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
Keep webhook URLs in secrets or environment variables, never in the file. `BRICKSENTRY_SLACK_WEBHOOK` and `BRICKSENTRY_TEAMS_WEBHOOK` work too. `assess` and `preview` send alerts automatically when a webhook is set (`--no-notify` turns them off), and in Python call `sentry.notify(assessment)`. A failed webhook is reported but never changes the verdict or fails the run.
|
|
231
|
+
|
|
180
232
|
## Python API
|
|
181
233
|
|
|
182
234
|
```python
|
|
@@ -204,7 +256,7 @@ tables:
|
|
|
204
256
|
keys: [order_id]
|
|
205
257
|
segment_by: [region]
|
|
206
258
|
paths: ["src/pipelines/orders/**", "resources/orders_job.yml"]
|
|
207
|
-
policy: policy.yml
|
|
259
|
+
policy: policy.yml # or builtin:<template>, see "Policy templates" below
|
|
208
260
|
```
|
|
209
261
|
|
|
210
262
|
### Policy example
|
|
@@ -238,6 +290,20 @@ rules:
|
|
|
238
290
|
|
|
239
291
|
If several rules match, the most severe one wins. The full starter policy is in [`examples/databricks/policy.yml`](examples/databricks/policy.yml), and `bricksentry init` writes one for you.
|
|
240
292
|
|
|
293
|
+
### Policy templates
|
|
294
|
+
|
|
295
|
+
Start from a ready-made policy instead of writing one:
|
|
296
|
+
|
|
297
|
+
| Template | For |
|
|
298
|
+
|---|---|
|
|
299
|
+
| `default` | Balanced: block duplicate keys, a human for row loss, dropped columns, PII and certified downstream |
|
|
300
|
+
| `strict` | Production-critical pipelines: small changes need a human, failed checks block |
|
|
301
|
+
| `pii` | Tables with personal data: any change to a `pii`-tagged table, or one feeding it, needs a human |
|
|
302
|
+
| `certified` | Certified or gold tables that dashboards and AI rely on |
|
|
303
|
+
| `finance` | Revenue and money tables: totals can't move quietly, double counting is blocked |
|
|
304
|
+
|
|
305
|
+
Use one directly with `policy: builtin:finance`, or write an editable copy with `bricksentry init --policy finance`. `bricksentry policies finance` prints it. Tags come from Unity Catalog, so tag your tables `pii` or `certified` for those templates to apply.
|
|
306
|
+
|
|
241
307
|
### Policy conditions
|
|
242
308
|
|
|
243
309
|
`table` (glob) · `tag` · `downstream_tag` · `downstream_kind` · `downstream_count_gt` · `removed_pct_gt` · `added_pct_gt` · `changed_pct_gt` · `row_count_change_pct_gt` · `row_count_drop_pct_gt` · `column_removed` · `column_added` · `column_type_changed` · `duplicate_keys` · `null_keys` · `sum_change_pct_gt` / `null_increase_gt` (optionally with `column`) · `any_change` · `diff_error`
|
|
@@ -262,7 +328,7 @@ All conditions in a `when` must hold. The most severe matching rule sets the ver
|
|
|
262
328
|
|
|
263
329
|
**Top priority: validation across more workspaces.** Classic and serverless compute, AWS, Azure and GCP, and workspaces with restricted system-table access. If you run the quickstart notebook, please [share what you see](https://github.com/bricksentry/bricksentry/issues), whether it works or not.
|
|
264
330
|
|
|
265
|
-
Next: Asset Bundle parsing for automatic table detection · column-level blast radius from `system.access.column_lineage` · an aggregate diff for keyless tables · Lakeflow expectations in the verdict · `bricksentry watch` for scheduled drift checks · a Databricks App UI.
|
|
331
|
+
Next: dbt support, so dbt models on Databricks get the same diff, blast radius and verdict (planned for 0.2) · Asset Bundle parsing for automatic table detection · column-level blast radius from `system.access.column_lineage` · an aggregate diff for keyless tables · Lakeflow expectations in the verdict · `bricksentry watch` for scheduled drift checks · a Databricks App UI.
|
|
266
332
|
|
|
267
333
|
## Contributing
|
|
268
334
|
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
# Welcome to bricksentry
|
|
2
2
|
|
|
3
|
+
<!-- mcp-name: io.github.bricksentry/bricksentry -->
|
|
4
|
+
|
|
3
5
|
[](https://pypi.org/project/bricksentry/) [](https://pypi.org/project/bricksentry/) [](https://github.com/bricksentry/bricksentry/actions/workflows/ci.yml) [](https://github.com/bricksentry/bricksentry/actions/workflows/lint.yml) [](https://github.com/bricksentry/bricksentry/actions/workflows/ci.yml) [](LICENSE)
|
|
4
6
|
|
|
5
7
|
***The safety check for data changes in the AI era.***
|
|
@@ -88,6 +90,8 @@ To watch the whole loop, run `bricksentry demo` (see the top of this page). `bri
|
|
|
88
90
|
|
|
89
91
|
```bash
|
|
90
92
|
bricksentry init # starter bricksentry.yml + policy.yml
|
|
93
|
+
bricksentry init --policy finance # ...or start from a policy template
|
|
94
|
+
bricksentry policies # list the policy templates
|
|
91
95
|
bricksentry impact main.sales.orders # blast radius
|
|
92
96
|
bricksentry diff main.sales.orders main.sales_pr_42.orders
|
|
93
97
|
bricksentry preview main.sales.orders --sql "MERGE INTO {{target}} t USING updates u ON t.order_id = u.order_id WHEN MATCHED THEN UPDATE SET *"
|
|
@@ -124,12 +128,60 @@ Check out with `fetch-depth: 0` and give the job `pull-requests: write` permissi
|
|
|
124
128
|
Or use the bundled GitHub Action, which also writes the report to the job summary:
|
|
125
129
|
|
|
126
130
|
```yaml
|
|
127
|
-
- uses: bricksentry/bricksentry@v0.1.
|
|
131
|
+
- uses: bricksentry/bricksentry@v0.1.6
|
|
128
132
|
with:
|
|
129
133
|
config: bricksentry.yml
|
|
130
134
|
fail-on: needs_human
|
|
131
135
|
```
|
|
132
136
|
|
|
137
|
+
A complete workflow you can copy to `.github/workflows/bricksentry.yml`:
|
|
138
|
+
|
|
139
|
+
```yaml
|
|
140
|
+
name: bricksentry
|
|
141
|
+
on: pull_request
|
|
142
|
+
|
|
143
|
+
permissions:
|
|
144
|
+
contents: read
|
|
145
|
+
pull-requests: write
|
|
146
|
+
|
|
147
|
+
jobs:
|
|
148
|
+
check-data:
|
|
149
|
+
runs-on: ubuntu-latest
|
|
150
|
+
steps:
|
|
151
|
+
- uses: actions/checkout@v4
|
|
152
|
+
with:
|
|
153
|
+
fetch-depth: 0
|
|
154
|
+
# Build this PR's version of your pipeline into a per-PR schema first,
|
|
155
|
+
# for example: databricks bundle deploy -t ci && databricks bundle run -t ci
|
|
156
|
+
- uses: bricksentry/bricksentry@v0.1.6
|
|
157
|
+
with:
|
|
158
|
+
config: bricksentry.yml
|
|
159
|
+
fail-on: needs_human
|
|
160
|
+
slack-webhook: ${{ secrets.SLACK_WEBHOOK_URL }} # optional
|
|
161
|
+
teams-webhook: ${{ secrets.TEAMS_WEBHOOK_URL }} # optional
|
|
162
|
+
env:
|
|
163
|
+
DATABRICKS_HOST: ${{ secrets.DATABRICKS_HOST }}
|
|
164
|
+
DATABRICKS_CLIENT_ID: ${{ secrets.DATABRICKS_CLIENT_ID }}
|
|
165
|
+
DATABRICKS_CLIENT_SECRET: ${{ secrets.DATABRICKS_CLIENT_SECRET }}
|
|
166
|
+
DATABRICKS_WAREHOUSE_ID: ${{ secrets.DATABRICKS_WAREHOUSE_ID }}
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
To make the check binding, mark this job as a required status check in your branch protection rules. Then a `needs_human` or `block` verdict stops the merge, whatever the author or an agent decides.
|
|
170
|
+
|
|
171
|
+
### Alerts in Slack and Teams
|
|
172
|
+
|
|
173
|
+
When the verdict is `needs_human` or worse, bricksentry can post a short alert: the verdict, the rules that fired, who should review, and a link to the PR.
|
|
174
|
+
|
|
175
|
+
```yaml
|
|
176
|
+
# bricksentry.yml
|
|
177
|
+
notify:
|
|
178
|
+
on: needs_human # alert at this verdict or worse
|
|
179
|
+
slack_webhook: env:SLACK_WEBHOOK_URL # Slack incoming webhook
|
|
180
|
+
teams_webhook: env:TEAMS_WEBHOOK_URL # Teams Workflows "webhook request" URL
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
Keep webhook URLs in secrets or environment variables, never in the file. `BRICKSENTRY_SLACK_WEBHOOK` and `BRICKSENTRY_TEAMS_WEBHOOK` work too. `assess` and `preview` send alerts automatically when a webhook is set (`--no-notify` turns them off), and in Python call `sentry.notify(assessment)`. A failed webhook is reported but never changes the verdict or fails the run.
|
|
184
|
+
|
|
133
185
|
## Python API
|
|
134
186
|
|
|
135
187
|
```python
|
|
@@ -157,7 +209,7 @@ tables:
|
|
|
157
209
|
keys: [order_id]
|
|
158
210
|
segment_by: [region]
|
|
159
211
|
paths: ["src/pipelines/orders/**", "resources/orders_job.yml"]
|
|
160
|
-
policy: policy.yml
|
|
212
|
+
policy: policy.yml # or builtin:<template>, see "Policy templates" below
|
|
161
213
|
```
|
|
162
214
|
|
|
163
215
|
### Policy example
|
|
@@ -191,6 +243,20 @@ rules:
|
|
|
191
243
|
|
|
192
244
|
If several rules match, the most severe one wins. The full starter policy is in [`examples/databricks/policy.yml`](examples/databricks/policy.yml), and `bricksentry init` writes one for you.
|
|
193
245
|
|
|
246
|
+
### Policy templates
|
|
247
|
+
|
|
248
|
+
Start from a ready-made policy instead of writing one:
|
|
249
|
+
|
|
250
|
+
| Template | For |
|
|
251
|
+
|---|---|
|
|
252
|
+
| `default` | Balanced: block duplicate keys, a human for row loss, dropped columns, PII and certified downstream |
|
|
253
|
+
| `strict` | Production-critical pipelines: small changes need a human, failed checks block |
|
|
254
|
+
| `pii` | Tables with personal data: any change to a `pii`-tagged table, or one feeding it, needs a human |
|
|
255
|
+
| `certified` | Certified or gold tables that dashboards and AI rely on |
|
|
256
|
+
| `finance` | Revenue and money tables: totals can't move quietly, double counting is blocked |
|
|
257
|
+
|
|
258
|
+
Use one directly with `policy: builtin:finance`, or write an editable copy with `bricksentry init --policy finance`. `bricksentry policies finance` prints it. Tags come from Unity Catalog, so tag your tables `pii` or `certified` for those templates to apply.
|
|
259
|
+
|
|
194
260
|
### Policy conditions
|
|
195
261
|
|
|
196
262
|
`table` (glob) · `tag` · `downstream_tag` · `downstream_kind` · `downstream_count_gt` · `removed_pct_gt` · `added_pct_gt` · `changed_pct_gt` · `row_count_change_pct_gt` · `row_count_drop_pct_gt` · `column_removed` · `column_added` · `column_type_changed` · `duplicate_keys` · `null_keys` · `sum_change_pct_gt` / `null_increase_gt` (optionally with `column`) · `any_change` · `diff_error`
|
|
@@ -215,7 +281,7 @@ All conditions in a `when` must hold. The most severe matching rule sets the ver
|
|
|
215
281
|
|
|
216
282
|
**Top priority: validation across more workspaces.** Classic and serverless compute, AWS, Azure and GCP, and workspaces with restricted system-table access. If you run the quickstart notebook, please [share what you see](https://github.com/bricksentry/bricksentry/issues), whether it works or not.
|
|
217
283
|
|
|
218
|
-
Next: Asset Bundle parsing for automatic table detection · column-level blast radius from `system.access.column_lineage` · an aggregate diff for keyless tables · Lakeflow expectations in the verdict · `bricksentry watch` for scheduled drift checks · a Databricks App UI.
|
|
284
|
+
Next: dbt support, so dbt models on Databricks get the same diff, blast radius and verdict (planned for 0.2) · Asset Bundle parsing for automatic table detection · column-level blast radius from `system.access.column_lineage` · an aggregate diff for keyless tables · Lakeflow expectations in the verdict · `bricksentry watch` for scheduled drift checks · a Databricks App UI.
|
|
219
285
|
|
|
220
286
|
## Contributing
|
|
221
287
|
|
|
@@ -20,6 +20,15 @@ inputs:
|
|
|
20
20
|
comment:
|
|
21
21
|
description: Post or update a PR comment with the report
|
|
22
22
|
default: "true"
|
|
23
|
+
slack-webhook:
|
|
24
|
+
description: Slack incoming webhook URL for verdict alerts. Pass it from a secret, e.g. secrets.SLACK_WEBHOOK_URL
|
|
25
|
+
default: ""
|
|
26
|
+
teams-webhook:
|
|
27
|
+
description: Microsoft Teams Workflows webhook URL for verdict alerts. Pass it from a secret
|
|
28
|
+
default: ""
|
|
29
|
+
notify-on:
|
|
30
|
+
description: Send an alert at this verdict or worse (pass, warn, needs_human, block)
|
|
31
|
+
default: needs_human
|
|
23
32
|
version:
|
|
24
33
|
description: bricksentry version spec to install (e.g. "==0.1.0"); empty = latest
|
|
25
34
|
default: ""
|
|
@@ -44,6 +53,9 @@ runs:
|
|
|
44
53
|
env:
|
|
45
54
|
BRICKSENTRY_PR: ${{ github.event.pull_request.number }}
|
|
46
55
|
GITHUB_TOKEN: ${{ github.token }}
|
|
56
|
+
BRICKSENTRY_SLACK_WEBHOOK: ${{ inputs.slack-webhook }}
|
|
57
|
+
BRICKSENTRY_TEAMS_WEBHOOK: ${{ inputs.teams-webhook }}
|
|
58
|
+
BRICKSENTRY_NOTIFY_ON: ${{ inputs.notify-on }}
|
|
47
59
|
run: |
|
|
48
60
|
set +e
|
|
49
61
|
BASE="${{ inputs.base-ref }}"
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "bricksentry"
|
|
7
|
-
version = "0.1.
|
|
7
|
+
version = "0.1.6"
|
|
8
8
|
description = "Change-safety for Databricks pipelines and the AI agents that edit them: data diffs, Unity Catalog blast radius, policy verdicts and rollback plans."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.10"
|
|
@@ -186,6 +186,17 @@ class Sentry:
|
|
|
186
186
|
out["preview"] = {"sandbox_table": clone if keep else None, "executed_sql": rewritten}
|
|
187
187
|
return out
|
|
188
188
|
|
|
189
|
+
# --- alerts ---------------------------------------------------------------
|
|
190
|
+
def notify(self, assessment: Assessment, pr: str | None = None, force: bool = False) -> list[str]:
|
|
191
|
+
"""Send a Slack / Teams alert for ``assessment`` if configured. Never raises."""
|
|
192
|
+
from bricksentry.notify import NotifySettings, send
|
|
193
|
+
|
|
194
|
+
try:
|
|
195
|
+
settings = NotifySettings.from_config(self.config.notify)
|
|
196
|
+
except ValueError as e:
|
|
197
|
+
return [f"notify: bad config ({e})"]
|
|
198
|
+
return send(assessment, settings, pr=pr, force=force)
|
|
199
|
+
|
|
189
200
|
# --- lookups for agents -------------------------------------------------
|
|
190
201
|
def get_assessment(self, assessment_id: str) -> Assessment | None:
|
|
191
202
|
return self._assessments.get(assessment_id) or self._load(assessment_id)
|
|
@@ -40,6 +40,8 @@ def _exit_for(verdict: Verdict, fail_on: str) -> None:
|
|
|
40
40
|
|
|
41
41
|
config_opt = click.option("--config", "-c", "config_path", type=click.Path(), default=None,
|
|
42
42
|
help="Path to bricksentry.yml (default: ./bricksentry.yml or $BRICKSENTRY_CONFIG)")
|
|
43
|
+
notify_opt = click.option("--notify/--no-notify", "notify", default=True, show_default=True,
|
|
44
|
+
help="Send a Slack/Teams alert if webhooks are configured (see notify: in bricksentry.yml)")
|
|
43
45
|
fail_opt = click.option("--fail-on", type=click.Choice([v.value for v in Verdict]), default="block",
|
|
44
46
|
show_default=True, help="Exit 1 when the verdict is at least this severe")
|
|
45
47
|
|
|
@@ -94,9 +96,10 @@ def impact(table, depth, fmt, config_path):
|
|
|
94
96
|
@click.option("--format", "fmt", type=click.Choice(["text", "json", "markdown"]), default="text")
|
|
95
97
|
@click.option("--output", "-o", type=click.Path(), default=None, help="Also write the markdown report here.")
|
|
96
98
|
@click.option("--comment", is_flag=True, help="Post/update the report as a GitHub PR comment.")
|
|
99
|
+
@notify_opt
|
|
97
100
|
@fail_opt
|
|
98
101
|
@config_opt
|
|
99
|
-
def assess(tables, git_base, cand_pairs, pr, fmt, output, comment, fail_on, config_path):
|
|
102
|
+
def assess(tables, git_base, cand_pairs, pr, fmt, output, comment, notify, fail_on, config_path):
|
|
100
103
|
"""Assess a change: data diff + blast radius + policy verdict + rollback plan."""
|
|
101
104
|
from bricksentry.changes import changed_files, tables_for_files
|
|
102
105
|
from bricksentry.report import to_markdown
|
|
@@ -122,6 +125,9 @@ def assess(tables, git_base, cand_pairs, pr, fmt, output, comment, fail_on, conf
|
|
|
122
125
|
|
|
123
126
|
url = upsert_pr_comment(md, pr=pr)
|
|
124
127
|
click.echo(f"PR comment: {url}", err=True)
|
|
128
|
+
if notify:
|
|
129
|
+
for line in s.notify(a, pr=pr):
|
|
130
|
+
click.echo(f"notify {line}", err=True)
|
|
125
131
|
if fmt == "text":
|
|
126
132
|
click.echo(f"{a.verdict.value.upper()} (risk {a.verdict.risk_tier})")
|
|
127
133
|
for t in a.tables:
|
|
@@ -141,15 +147,21 @@ def assess(tables, git_base, cand_pairs, pr, fmt, output, comment, fail_on, conf
|
|
|
141
147
|
@click.option("--file", "sql_file", type=click.Path(exists=True), default=None)
|
|
142
148
|
@click.option("--key", "-k", "keys", multiple=True)
|
|
143
149
|
@click.option("--format", "fmt", type=click.Choice(["text", "json"]), default="text")
|
|
150
|
+
@notify_opt
|
|
144
151
|
@fail_opt
|
|
145
152
|
@config_opt
|
|
146
|
-
def preview(target, sql_text, sql_file, keys, fmt, fail_on, config_path):
|
|
153
|
+
def preview(target, sql_text, sql_file, keys, fmt, notify, fail_on, config_path):
|
|
147
154
|
"""Run a write against a sandbox clone of TARGET and show what it would change."""
|
|
148
155
|
if not (sql_text or sql_file):
|
|
149
156
|
raise click.UsageError("pass --sql or --file")
|
|
150
157
|
sql = sql_text or Path(sql_file).read_text()
|
|
151
158
|
s = _sentry(config_path)
|
|
152
159
|
out = s.preview_write(sql, target, keys=list(keys) or None)
|
|
160
|
+
if notify:
|
|
161
|
+
a = s.get_assessment(out["id"])
|
|
162
|
+
if a is not None:
|
|
163
|
+
for line in s.notify(a):
|
|
164
|
+
click.echo(f"notify {line}", err=True)
|
|
153
165
|
if fmt == "json":
|
|
154
166
|
_emit(out, fmt)
|
|
155
167
|
else:
|
|
@@ -204,6 +216,12 @@ candidate_pattern: "{catalog}.{schema}_pr_{pr}.{table}"
|
|
|
204
216
|
|
|
205
217
|
# sample_pct: 10 # diff a deterministic 10% key sample on big tables
|
|
206
218
|
|
|
219
|
+
# Optional Slack / Teams alerts. Keep webhook URLs in environment variables or CI secrets.
|
|
220
|
+
# notify:
|
|
221
|
+
# on: needs_human
|
|
222
|
+
# slack_webhook: env:SLACK_WEBHOOK_URL
|
|
223
|
+
# teams_webhook: env:TEAMS_WEBHOOK_URL
|
|
224
|
+
|
|
207
225
|
lineage:
|
|
208
226
|
depth: 3
|
|
209
227
|
lookback_days: 90
|
|
@@ -236,9 +254,16 @@ rules:
|
|
|
236
254
|
|
|
237
255
|
@main.command()
|
|
238
256
|
@click.option("--force", is_flag=True)
|
|
239
|
-
|
|
257
|
+
@click.option("--policy", "template", default="default", show_default=True,
|
|
258
|
+
help="Policy template for policy.yml (see `bricksentry policies`)")
|
|
259
|
+
def init(force, template):
|
|
240
260
|
"""Write a starter bricksentry.yml and policy.yml."""
|
|
241
|
-
|
|
261
|
+
from bricksentry.policy_templates import TEMPLATES, to_yaml
|
|
262
|
+
|
|
263
|
+
if template.lower() not in TEMPLATES:
|
|
264
|
+
raise click.UsageError(f"unknown template {template!r}; choose from {', '.join(sorted(TEMPLATES))}")
|
|
265
|
+
policy_body = _INIT_POLICY if template.lower() == "default" else to_yaml(template)
|
|
266
|
+
for name, body in (("bricksentry.yml", _INIT_CONFIG), ("policy.yml", policy_body)):
|
|
242
267
|
p = Path(name)
|
|
243
268
|
if p.exists() and not force:
|
|
244
269
|
click.echo(f"skip {name} (exists; use --force)")
|
|
@@ -247,6 +272,21 @@ def init(force):
|
|
|
247
272
|
click.echo(f"wrote {name}")
|
|
248
273
|
|
|
249
274
|
|
|
275
|
+
@main.command()
|
|
276
|
+
@click.argument("name", required=False)
|
|
277
|
+
def policies(name):
|
|
278
|
+
"""List the built-in policy templates, or print one as policy.yml."""
|
|
279
|
+
from bricksentry.policy_templates import TEMPLATES, to_yaml
|
|
280
|
+
|
|
281
|
+
if name:
|
|
282
|
+
if name.lower() not in TEMPLATES:
|
|
283
|
+
raise click.UsageError(f"unknown template {name!r}; choose from {', '.join(sorted(TEMPLATES))}")
|
|
284
|
+
click.echo(to_yaml(name), nl=False)
|
|
285
|
+
return
|
|
286
|
+
width = max(len(n) for n in TEMPLATES)
|
|
287
|
+
for n, t in TEMPLATES.items():
|
|
288
|
+
click.echo(f"{n.ljust(width)} {t['description']}")
|
|
289
|
+
click.echo("\nUse one with `policy: builtin:<name>` in bricksentry.yml, or `bricksentry init --policy <name>`.")
|
|
250
290
|
|
|
251
291
|
|
|
252
292
|
def entry() -> None:
|
|
@@ -18,7 +18,11 @@ Example::
|
|
|
18
18
|
keys: [order_id]
|
|
19
19
|
segment_by: [region]
|
|
20
20
|
paths: ["pipelines/orders/**", "resources/orders_job.yml"]
|
|
21
|
-
policy: policy.yml #
|
|
21
|
+
policy: policy.yml # a file, an inline mapping, or builtin:<name> (see `bricksentry policies`)
|
|
22
|
+
notify: # optional Slack / Teams alerts
|
|
23
|
+
on: needs_human
|
|
24
|
+
slack_webhook: env:SLACK_WEBHOOK_URL
|
|
25
|
+
teams_webhook: env:TEAMS_WEBHOOK_URL
|
|
22
26
|
"""
|
|
23
27
|
|
|
24
28
|
from __future__ import annotations
|
|
@@ -54,6 +58,7 @@ class Config:
|
|
|
54
58
|
lineage: dict[str, Any] = field(default_factory=dict)
|
|
55
59
|
tables: dict[str, TableSpec] = field(default_factory=dict)
|
|
56
60
|
policy: dict[str, Any] | None = None
|
|
61
|
+
notify: dict[str, Any] = field(default_factory=dict)
|
|
57
62
|
root: Path = field(default_factory=Path.cwd)
|
|
58
63
|
|
|
59
64
|
@classmethod
|
|
@@ -77,7 +82,12 @@ class Config:
|
|
|
77
82
|
)
|
|
78
83
|
policy = data.get("policy")
|
|
79
84
|
if isinstance(policy, str):
|
|
80
|
-
policy
|
|
85
|
+
if policy.strip().lower().startswith("builtin:"):
|
|
86
|
+
from bricksentry.policy_templates import get_template
|
|
87
|
+
|
|
88
|
+
policy = get_template(policy.split(":", 1)[1])
|
|
89
|
+
else:
|
|
90
|
+
policy = yaml.safe_load((root / policy).read_text()) or {}
|
|
81
91
|
return cls(
|
|
82
92
|
backend=data.get("backend") or {"type": "duckdb"},
|
|
83
93
|
sandbox_schema=data.get("sandbox_schema", "bricksentry_sandbox"),
|
|
@@ -89,6 +99,7 @@ class Config:
|
|
|
89
99
|
lineage=data.get("lineage") or {},
|
|
90
100
|
tables=tables,
|
|
91
101
|
policy=policy,
|
|
102
|
+
notify=data.get("notify") or {},
|
|
92
103
|
root=root,
|
|
93
104
|
)
|
|
94
105
|
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""Send a short verdict alert to Slack or Microsoft Teams (stdlib only).
|
|
2
|
+
|
|
3
|
+
Configure in ``bricksentry.yml``::
|
|
4
|
+
|
|
5
|
+
notify:
|
|
6
|
+
on: needs_human # alert at this verdict or worse (default)
|
|
7
|
+
slack_webhook: env:SLACK_WEBHOOK_URL # read the URL from an environment variable
|
|
8
|
+
teams_webhook: env:TEAMS_WEBHOOK_URL
|
|
9
|
+
|
|
10
|
+
or just set ``BRICKSENTRY_SLACK_WEBHOOK`` / ``BRICKSENTRY_TEAMS_WEBHOOK``
|
|
11
|
+
(and optionally ``BRICKSENTRY_NOTIFY_ON``).
|
|
12
|
+
Webhook URLs are secrets: keep them in environment variables or CI secrets,
|
|
13
|
+
not in the YAML file itself.
|
|
14
|
+
|
|
15
|
+
Slack uses an incoming webhook. Teams uses a Workflows ("Post to a channel when a
|
|
16
|
+
webhook request is received") URL, which accepts an Adaptive Card.
|
|
17
|
+
|
|
18
|
+
Alerts never fail a run: a webhook error is reported and the verdict stands.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import json
|
|
24
|
+
import os
|
|
25
|
+
import urllib.request
|
|
26
|
+
from dataclasses import dataclass
|
|
27
|
+
from typing import Any
|
|
28
|
+
|
|
29
|
+
from bricksentry.models import Assessment, Verdict
|
|
30
|
+
|
|
31
|
+
_EMOJI = {"pass": ":large_green_circle:", "warn": ":large_yellow_circle:",
|
|
32
|
+
"needs_human": ":large_orange_circle:", "block": ":red_circle:"}
|
|
33
|
+
_TITLE = {"pass": "Safe to ship", "warn": "Safe to ship, with warnings",
|
|
34
|
+
"needs_human": "Needs human review", "block": "Blocked"}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass
|
|
38
|
+
class NotifySettings:
|
|
39
|
+
on: Verdict = Verdict.NEEDS_HUMAN
|
|
40
|
+
slack_webhook: str | None = None
|
|
41
|
+
teams_webhook: str | None = None
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def enabled(self) -> bool:
|
|
45
|
+
return bool(self.slack_webhook or self.teams_webhook)
|
|
46
|
+
|
|
47
|
+
@classmethod
|
|
48
|
+
def from_config(cls, data: dict[str, Any] | None) -> NotifySettings:
|
|
49
|
+
data = data or {}
|
|
50
|
+
return cls(
|
|
51
|
+
on=Verdict(str(data.get("on") or os.environ.get("BRICKSENTRY_NOTIFY_ON") or "needs_human")),
|
|
52
|
+
slack_webhook=_resolve(data.get("slack_webhook")) or os.environ.get("BRICKSENTRY_SLACK_WEBHOOK") or None,
|
|
53
|
+
teams_webhook=_resolve(data.get("teams_webhook")) or os.environ.get("BRICKSENTRY_TEAMS_WEBHOOK") or None,
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _resolve(value: Any) -> str | None:
|
|
58
|
+
"""``env:NAME`` or ``${NAME}`` reads an environment variable; anything else is used as given."""
|
|
59
|
+
if not value:
|
|
60
|
+
return None
|
|
61
|
+
v = str(value).strip()
|
|
62
|
+
if v.startswith("env:"):
|
|
63
|
+
return os.environ.get(v[4:].strip()) or None
|
|
64
|
+
if v.startswith("${") and v.endswith("}"):
|
|
65
|
+
return os.environ.get(v[2:-1].strip()) or None
|
|
66
|
+
return v
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _pr_link(pr: str | None) -> str | None:
|
|
70
|
+
repo = os.environ.get("GITHUB_REPOSITORY")
|
|
71
|
+
server = (os.environ.get("GITHUB_SERVER_URL") or "https://github.com").rstrip("/")
|
|
72
|
+
if repo and pr:
|
|
73
|
+
return f"{server}/{repo}/pull/{pr}"
|
|
74
|
+
run = os.environ.get("GITHUB_RUN_ID")
|
|
75
|
+
if repo and run:
|
|
76
|
+
return f"{server}/{repo}/actions/runs/{run}"
|
|
77
|
+
return None
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _lines(a: Assessment, pr: str | None, max_reasons: int = 5) -> tuple[str, list[str], str | None]:
|
|
81
|
+
v = a.verdict.value
|
|
82
|
+
title = f"bricksentry: {_TITLE[v]} (risk {a.verdict.risk_tier})"
|
|
83
|
+
lines = [f"Tables: {', '.join(t.table for t in a.tables)}"]
|
|
84
|
+
hits = sorted(a.hits, key=lambda h: -h.verdict.rank)
|
|
85
|
+
for h in hits[:max_reasons]:
|
|
86
|
+
lines.append(f"[{h.verdict.value}] {h.rule} on {h.table}: {h.reason}")
|
|
87
|
+
if len(hits) > max_reasons:
|
|
88
|
+
lines.append(f"...and {len(hits) - max_reasons} more")
|
|
89
|
+
if a.notify:
|
|
90
|
+
lines.append(f"Review requested from: {', '.join(a.notify)}")
|
|
91
|
+
lines.append(f"Assessment: {a.id}")
|
|
92
|
+
return title, lines, _pr_link(pr)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def slack_payload(a: Assessment, pr: str | None = None) -> dict[str, Any]:
|
|
96
|
+
title, lines, link = _lines(a, pr)
|
|
97
|
+
head = f"{_EMOJI[a.verdict.value]} *{title}*"
|
|
98
|
+
body = "\n".join(lines) + (f"\n<{link}|Open in GitHub>" if link else "")
|
|
99
|
+
return {
|
|
100
|
+
"text": f"{title}", # notification fallback
|
|
101
|
+
"blocks": [
|
|
102
|
+
{"type": "section", "text": {"type": "mrkdwn", "text": head}},
|
|
103
|
+
{"type": "section", "text": {"type": "mrkdwn", "text": body[:2900]}},
|
|
104
|
+
],
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def teams_payload(a: Assessment, pr: str | None = None) -> dict[str, Any]:
|
|
109
|
+
title, lines, link = _lines(a, pr)
|
|
110
|
+
color = {"pass": "Good", "warn": "Warning", "needs_human": "Warning", "block": "Attention"}[a.verdict.value]
|
|
111
|
+
body: list[dict[str, Any]] = [
|
|
112
|
+
{"type": "TextBlock", "text": title, "weight": "Bolder", "size": "Medium", "color": color, "wrap": True},
|
|
113
|
+
] + [{"type": "TextBlock", "text": line, "wrap": True, "spacing": "Small"} for line in lines]
|
|
114
|
+
card: dict[str, Any] = {
|
|
115
|
+
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
|
|
116
|
+
"type": "AdaptiveCard",
|
|
117
|
+
"version": "1.4",
|
|
118
|
+
"body": body,
|
|
119
|
+
}
|
|
120
|
+
if link:
|
|
121
|
+
card["actions"] = [{"type": "Action.OpenUrl", "title": "Open in GitHub", "url": link}]
|
|
122
|
+
return {
|
|
123
|
+
"type": "message",
|
|
124
|
+
"attachments": [{"contentType": "application/vnd.microsoft.card.adaptive", "content": card}],
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _post(url: str, payload: dict[str, Any], timeout: int = 15) -> None:
|
|
129
|
+
req = urllib.request.Request(url, data=json.dumps(payload).encode(), method="POST")
|
|
130
|
+
req.add_header("Content-Type", "application/json")
|
|
131
|
+
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
132
|
+
r.read()
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def send(a: Assessment, settings: NotifySettings, pr: str | None = None, force: bool = False) -> list[str]:
|
|
136
|
+
"""Send alerts for ``a``. Returns one status line per channel; never raises."""
|
|
137
|
+
out: list[str] = []
|
|
138
|
+
if not settings.enabled:
|
|
139
|
+
return out
|
|
140
|
+
if not force and a.verdict.rank < settings.on.rank:
|
|
141
|
+
return [f"no alert: verdict {a.verdict.value} is below notify.on={settings.on.value}"]
|
|
142
|
+
for name, url, build in (
|
|
143
|
+
("slack", settings.slack_webhook, slack_payload),
|
|
144
|
+
("teams", settings.teams_webhook, teams_payload),
|
|
145
|
+
):
|
|
146
|
+
if not url:
|
|
147
|
+
continue
|
|
148
|
+
if not url.startswith("https://"):
|
|
149
|
+
out.append(f"{name}: skipped, webhook URL must start with https://")
|
|
150
|
+
continue
|
|
151
|
+
try:
|
|
152
|
+
_post(url, build(a, pr))
|
|
153
|
+
out.append(f"{name}: sent")
|
|
154
|
+
except Exception as e: # an alert must never change the verdict or crash CI
|
|
155
|
+
out.append(f"{name}: failed ({type(e).__name__}: {e})")
|
|
156
|
+
return out
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""Ready-made policies for common patterns.
|
|
2
|
+
|
|
3
|
+
Use one in ``bricksentry.yml``::
|
|
4
|
+
|
|
5
|
+
policy: builtin:pii
|
|
6
|
+
|
|
7
|
+
or write it to a file you can edit: ``bricksentry init --policy pii``.
|
|
8
|
+
List them with ``bricksentry policies``.
|
|
9
|
+
|
|
10
|
+
Every template keeps the core safety rules (failed diffs, duplicate keys,
|
|
11
|
+
NULL keys, dropped columns) and adds rules for its pattern.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import copy
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from bricksentry.policy import DEFAULT_POLICY
|
|
20
|
+
|
|
21
|
+
_CORE = [
|
|
22
|
+
{"name": "diff-failed", "when": {"diff_error": True}, "then": "needs_human"},
|
|
23
|
+
{"name": "duplicate-keys", "when": {"duplicate_keys": True}, "then": "block"},
|
|
24
|
+
{"name": "null-keys", "when": {"null_keys": True}, "then": "warn"},
|
|
25
|
+
{"name": "dropped-column", "when": {"column_removed": True}, "then": "needs_human"},
|
|
26
|
+
{"name": "type-change", "when": {"column_type_changed": True}, "then": "warn"},
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
TEMPLATES: dict[str, dict[str, Any]] = {
|
|
30
|
+
"default": {
|
|
31
|
+
"description": "Balanced defaults: block duplicate keys, ask a human for row loss, dropped columns, PII and certified downstream.",
|
|
32
|
+
"policy": DEFAULT_POLICY,
|
|
33
|
+
},
|
|
34
|
+
"strict": {
|
|
35
|
+
"description": "Production-critical pipelines: small changes need a human, failed checks block.",
|
|
36
|
+
"policy": {
|
|
37
|
+
"default": "pass",
|
|
38
|
+
"notify_owners_on": "warn",
|
|
39
|
+
"rules": [
|
|
40
|
+
{"name": "diff-failed", "when": {"diff_error": True}, "then": "block"},
|
|
41
|
+
{"name": "duplicate-keys", "when": {"duplicate_keys": True}, "then": "block"},
|
|
42
|
+
{"name": "null-keys", "when": {"null_keys": True}, "then": "needs_human"},
|
|
43
|
+
{"name": "dropped-column", "when": {"column_removed": True}, "then": "block"},
|
|
44
|
+
{"name": "type-change", "when": {"column_type_changed": True}, "then": "needs_human"},
|
|
45
|
+
{"name": "row-loss", "when": {"removed_pct_gt": 0.1}, "then": "needs_human"},
|
|
46
|
+
{"name": "row-count-drop", "when": {"row_count_drop_pct_gt": 0.1}, "then": "needs_human"},
|
|
47
|
+
{"name": "many-rows-changed", "when": {"changed_pct_gt": 2}, "then": "needs_human"},
|
|
48
|
+
{"name": "numeric-total-moved", "when": {"sum_change_pct_gt": 1}, "then": "needs_human"},
|
|
49
|
+
{"name": "certified-downstream", "when": {"downstream_tag": "certified", "any_change": True}, "then": "needs_human"},
|
|
50
|
+
{"name": "wide-blast-radius", "when": {"downstream_count_gt": 10}, "then": "warn"},
|
|
51
|
+
],
|
|
52
|
+
},
|
|
53
|
+
},
|
|
54
|
+
"pii": {
|
|
55
|
+
"description": "Tables holding personal data: any change to a PII table, or feeding one, needs a human.",
|
|
56
|
+
"policy": {
|
|
57
|
+
"default": "pass",
|
|
58
|
+
"notify_owners_on": "needs_human",
|
|
59
|
+
"rules": _CORE + [
|
|
60
|
+
{"name": "pii-table-changed", "when": {"tag": "pii", "any_change": True}, "then": "needs_human"},
|
|
61
|
+
{"name": "pii-new-column", "when": {"tag": "pii", "column_added": True}, "then": "needs_human"},
|
|
62
|
+
{"name": "pii-downstream", "when": {"downstream_tag": "pii", "any_change": True}, "then": "needs_human"},
|
|
63
|
+
{"name": "row-loss", "when": {"removed_pct_gt": 1}, "then": "needs_human"},
|
|
64
|
+
],
|
|
65
|
+
},
|
|
66
|
+
},
|
|
67
|
+
"certified": {
|
|
68
|
+
"description": "Certified or gold tables that dashboards and AI rely on: protect them and everything that feeds them.",
|
|
69
|
+
"policy": {
|
|
70
|
+
"default": "pass",
|
|
71
|
+
"notify_owners_on": "needs_human",
|
|
72
|
+
"rules": _CORE + [
|
|
73
|
+
{"name": "certified-table-changed", "when": {"tag": "certified", "any_change": True}, "then": "needs_human"},
|
|
74
|
+
{"name": "certified-schema-change", "when": {"tag": "certified", "column_type_changed": True}, "then": "block"},
|
|
75
|
+
{"name": "certified-downstream", "when": {"downstream_tag": "certified", "any_change": True}, "then": "needs_human"},
|
|
76
|
+
{"name": "dashboard-downstream", "when": {"downstream_kind": "dashboard", "any_change": True}, "then": "warn"},
|
|
77
|
+
{"name": "row-count-drop", "when": {"row_count_drop_pct_gt": 0.5}, "then": "needs_human"},
|
|
78
|
+
],
|
|
79
|
+
},
|
|
80
|
+
},
|
|
81
|
+
"finance": {
|
|
82
|
+
"description": "Revenue and other money tables: totals must not move quietly, and double counting is blocked.",
|
|
83
|
+
"policy": {
|
|
84
|
+
"default": "pass",
|
|
85
|
+
"notify_owners_on": "needs_human",
|
|
86
|
+
"rules": _CORE + [
|
|
87
|
+
{"name": "numeric-total-moved", "when": {"sum_change_pct_gt": 0.5}, "then": "needs_human"},
|
|
88
|
+
{"name": "row-loss", "when": {"removed_pct_gt": 0.1}, "then": "needs_human"},
|
|
89
|
+
{"name": "row-count-drop", "when": {"row_count_drop_pct_gt": 0.1}, "then": "needs_human"},
|
|
90
|
+
{"name": "new-nulls", "when": {"null_increase_gt": 0}, "then": "warn"},
|
|
91
|
+
{"name": "dashboard-downstream", "when": {"downstream_kind": "dashboard", "any_change": True}, "then": "warn"},
|
|
92
|
+
],
|
|
93
|
+
},
|
|
94
|
+
},
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def get_template(name: str) -> dict[str, Any]:
|
|
99
|
+
"""Return a copy of the named policy, ready for ``Policy(...)``."""
|
|
100
|
+
key = name.strip().lower()
|
|
101
|
+
if key not in TEMPLATES:
|
|
102
|
+
raise KeyError(f"Unknown policy template {name!r}. Available: {', '.join(sorted(TEMPLATES))}")
|
|
103
|
+
return copy.deepcopy(TEMPLATES[key]["policy"])
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def to_yaml(name: str) -> str:
|
|
107
|
+
"""The template as an editable policy.yml, one rule per line."""
|
|
108
|
+
p = get_template(name)
|
|
109
|
+
lines = [
|
|
110
|
+
f"# bricksentry policy template: {name}",
|
|
111
|
+
f"# {TEMPLATES[name.strip().lower()]['description']}",
|
|
112
|
+
f"default: {p.get('default', 'pass')}",
|
|
113
|
+
f"notify_owners_on: {p.get('notify_owners_on', 'needs_human')}",
|
|
114
|
+
"rules:",
|
|
115
|
+
]
|
|
116
|
+
width = max(len(r["name"]) for r in p["rules"]) + 1
|
|
117
|
+
for r in p["rules"]:
|
|
118
|
+
when = ", ".join(f"{k}: {_scalar(v)}" for k, v in r["when"].items())
|
|
119
|
+
lines.append(f" - {{name: {(r['name'] + ',').ljust(width)} when: {{{when}}}, then: {r['then']}}}")
|
|
120
|
+
return "\n".join(lines) + "\n"
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _scalar(v: Any) -> str:
|
|
124
|
+
if isinstance(v, bool):
|
|
125
|
+
return "true" if v else "false"
|
|
126
|
+
return str(v)
|
|
@@ -31,6 +31,29 @@ class PreviewGuardError(ValueError):
|
|
|
31
31
|
pass
|
|
32
32
|
|
|
33
33
|
|
|
34
|
+
# What to do instead when a statement is refused. preview_write only runs data
|
|
35
|
+
# writes on a clone; these commands change the table itself, its permissions or
|
|
36
|
+
# its history, so they belong in a reviewed migration, not an agent's dry run.
|
|
37
|
+
SAFE_ALTERNATIVES = {
|
|
38
|
+
"DROP": "To test removing all rows, preview `DELETE FROM {{target}}`. To retire a table, make it a reviewed "
|
|
39
|
+
"migration and run whats_downstream first to see who still reads it.",
|
|
40
|
+
"TRUNCATE": "Preview `DELETE FROM {{target}}` (optionally with a WHERE clause) to see the same effect on a clone.",
|
|
41
|
+
"ALTER": "To test a schema change, preview `CREATE OR REPLACE TABLE {{target}} AS SELECT ...` with the new "
|
|
42
|
+
"columns or types; the diff shows dropped columns and type changes. Apply the real ALTER in a reviewed migration.",
|
|
43
|
+
"GRANT": "Permissions are not data changes, so there is nothing to diff. Change grants in Unity Catalog through a reviewed process.",
|
|
44
|
+
"REVOKE": "Permissions are not data changes, so there is nothing to diff. Change grants in Unity Catalog through a reviewed process.",
|
|
45
|
+
"VACUUM": "VACUUM removes old versions and limits rollback. Run it as scheduled maintenance, not as part of a change.",
|
|
46
|
+
"RESTORE": "To undo a change, use rollback_plan(table) to get the exact RESTORE statement and run it with a human's approval.",
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _refusal(keyword: str) -> str:
|
|
51
|
+
k = keyword.upper()
|
|
52
|
+
hint = SAFE_ALTERNATIVES.get(k, "")
|
|
53
|
+
msg = f"preview_write refuses {k}: it only runs INSERT / MERGE / UPDATE / DELETE / CREATE OR REPLACE TABLE on a clone."
|
|
54
|
+
return f"{msg} Instead: {hint}" if hint else msg
|
|
55
|
+
|
|
56
|
+
|
|
34
57
|
def sandbox_name(sandbox_schema: str, target: str) -> str:
|
|
35
58
|
short = target.split(".")[-1]
|
|
36
59
|
return f"{sandbox_schema}.{short}__preview_{uuid.uuid4().hex[:8]}"
|
|
@@ -51,9 +74,12 @@ def rewrite_for_preview(sql: str, target: str, clone: str, quote) -> str:
|
|
|
51
74
|
body = sql.strip().rstrip(";").strip()
|
|
52
75
|
code = _strip_sql_comments_and_strings(body)
|
|
53
76
|
if ";" in code:
|
|
54
|
-
raise PreviewGuardError(
|
|
55
|
-
|
|
56
|
-
|
|
77
|
+
raise PreviewGuardError(
|
|
78
|
+
"preview_write accepts exactly one SQL statement. Preview each write separately, in the order they would run."
|
|
79
|
+
)
|
|
80
|
+
forbidden = _FORBIDDEN_RE.search(code)
|
|
81
|
+
if forbidden:
|
|
82
|
+
raise PreviewGuardError(_refusal(forbidden.group(1)))
|
|
57
83
|
|
|
58
84
|
clone_q = ".".join(quote(p) for p in clone.split("."))
|
|
59
85
|
if PLACEHOLDER in body:
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import json
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
from click.testing import CliRunner
|
|
5
|
+
|
|
6
|
+
from bricksentry import Config, Sentry, notify
|
|
7
|
+
from bricksentry.cli import main
|
|
8
|
+
from bricksentry.models import Verdict
|
|
9
|
+
from bricksentry.policy import Policy
|
|
10
|
+
from bricksentry.policy_templates import TEMPLATES, get_template, to_yaml
|
|
11
|
+
from bricksentry.preview import PreviewGuardError, rewrite_for_preview
|
|
12
|
+
|
|
13
|
+
# --- alerts -------------------------------------------------------------------
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@pytest.fixture
|
|
17
|
+
def risky(sentry, backend):
|
|
18
|
+
"""An assessment that needs a human: 10% of rows deleted."""
|
|
19
|
+
backend.execute("CREATE TABLE sales_ci.orders AS SELECT * FROM sales.orders WHERE order_id % 10 <> 0")
|
|
20
|
+
return sentry.assess(["sales.orders"])
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@pytest.fixture
|
|
24
|
+
def posted(monkeypatch):
|
|
25
|
+
calls = []
|
|
26
|
+
monkeypatch.setattr(notify, "_post", lambda url, payload, timeout=15: calls.append((url, payload)))
|
|
27
|
+
return calls
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def test_settings_read_env_references(monkeypatch):
|
|
31
|
+
monkeypatch.setenv("MY_SLACK", "https://hooks.slack.com/services/X")
|
|
32
|
+
s = notify.NotifySettings.from_config({"slack_webhook": "env:MY_SLACK", "on": "warn"})
|
|
33
|
+
assert s.slack_webhook == "https://hooks.slack.com/services/X"
|
|
34
|
+
assert s.on == Verdict.WARN and s.enabled
|
|
35
|
+
assert notify.NotifySettings.from_config({"teams_webhook": "${MISSING_VAR}"}).teams_webhook is None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def test_settings_fall_back_to_bricksentry_env(monkeypatch):
|
|
39
|
+
monkeypatch.setenv("BRICKSENTRY_TEAMS_WEBHOOK", "https://example.webhook.office.com/x")
|
|
40
|
+
assert notify.NotifySettings.from_config(None).teams_webhook.endswith("/x")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def test_send_slack_and_teams(risky, posted, monkeypatch):
|
|
44
|
+
monkeypatch.setenv("GITHUB_REPOSITORY", "acme/pipelines")
|
|
45
|
+
s = notify.NotifySettings(slack_webhook="https://hooks.slack.com/a", teams_webhook="https://teams.example/b")
|
|
46
|
+
out = notify.send(risky, s, pr="42")
|
|
47
|
+
assert out == ["slack: sent", "teams: sent"]
|
|
48
|
+
slack, teams = posted[0][1], posted[1][1]
|
|
49
|
+
text = json.dumps(slack)
|
|
50
|
+
assert "Needs human review" in text and "row-loss" in text and "acme/pipelines/pull/42" in text
|
|
51
|
+
card = teams["attachments"][0]["content"]
|
|
52
|
+
assert card["type"] == "AdaptiveCard"
|
|
53
|
+
assert card["actions"][0]["url"].endswith("/acme/pipelines/pull/42")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def test_send_respects_threshold(risky, posted):
|
|
57
|
+
assert risky.verdict == Verdict.NEEDS_HUMAN
|
|
58
|
+
out = notify.send(risky, notify.NotifySettings(on=Verdict.BLOCK, slack_webhook="https://hooks.slack.com/a"))
|
|
59
|
+
assert out and out[0].startswith("no alert") and posted == []
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def test_send_never_raises(risky, monkeypatch):
|
|
63
|
+
def boom(url, payload, timeout=15):
|
|
64
|
+
raise OSError("network down")
|
|
65
|
+
|
|
66
|
+
monkeypatch.setattr(notify, "_post", boom)
|
|
67
|
+
out = notify.send(risky, notify.NotifySettings(slack_webhook="https://hooks.slack.com/a"))
|
|
68
|
+
assert out == ["slack: failed (OSError: network down)"]
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def test_send_refuses_plain_http(risky, posted):
|
|
72
|
+
out = notify.send(risky, notify.NotifySettings(slack_webhook="http://insecure.example/a"))
|
|
73
|
+
assert "must start with https" in out[0] and posted == []
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def test_sentry_notify_uses_config(backend, posted, monkeypatch):
|
|
77
|
+
monkeypatch.setenv("SLACK_URL", "https://hooks.slack.com/z")
|
|
78
|
+
cfg = Config.from_dict({
|
|
79
|
+
"tables": {"sales.orders": {"keys": ["order_id"]}},
|
|
80
|
+
"notify": {"slack_webhook": "env:SLACK_URL"},
|
|
81
|
+
})
|
|
82
|
+
s = Sentry(cfg, backend=backend)
|
|
83
|
+
backend.execute("CREATE TABLE sales_ci.orders AS SELECT * FROM sales.orders WHERE order_id % 10 <> 0")
|
|
84
|
+
a = s.assess(["sales.orders"])
|
|
85
|
+
assert s.notify(a) == ["slack: sent"]
|
|
86
|
+
assert posted[0][0] == "https://hooks.slack.com/z"
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
# --- policy templates -----------------------------------------------------------
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@pytest.mark.parametrize("name", sorted(TEMPLATES))
|
|
93
|
+
def test_every_template_is_a_valid_policy(name):
|
|
94
|
+
Policy(get_template(name)) # raises on unknown conditions or verdicts
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@pytest.mark.parametrize("name", sorted(TEMPLATES))
|
|
98
|
+
def test_template_yaml_round_trips(name):
|
|
99
|
+
import yaml
|
|
100
|
+
|
|
101
|
+
assert yaml.safe_load(to_yaml(name))["rules"] == get_template(name)["rules"]
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def test_builtin_policy_in_config(backend):
|
|
105
|
+
cfg = Config.from_dict({"tables": {"sales.orders": {"keys": ["order_id"]}}, "policy": "builtin:finance"})
|
|
106
|
+
s = Sentry(cfg, backend=backend)
|
|
107
|
+
backend.execute("CREATE TABLE sales_ci.orders AS SELECT order_id, region, amount * 1.01 AS amount, status FROM sales.orders")
|
|
108
|
+
a = s.assess(["sales.orders"])
|
|
109
|
+
assert "numeric-total-moved" in {h.rule for h in a.hits}
|
|
110
|
+
assert a.verdict == Verdict.NEEDS_HUMAN
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def test_unknown_template_is_a_clear_error():
|
|
114
|
+
with pytest.raises(KeyError, match="Available"):
|
|
115
|
+
get_template("nope")
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def test_cli_policies_and_init(tmp_path, monkeypatch):
|
|
119
|
+
monkeypatch.chdir(tmp_path)
|
|
120
|
+
r = CliRunner().invoke(main, ["policies"])
|
|
121
|
+
assert r.exit_code == 0 and "finance" in r.output and "builtin:" in r.output
|
|
122
|
+
r = CliRunner().invoke(main, ["init", "--policy", "pii"])
|
|
123
|
+
assert r.exit_code == 0
|
|
124
|
+
assert "pii-table-changed" in (tmp_path / "policy.yml").read_text()
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
# --- preview refusals ---------------------------------------------------------
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
@pytest.mark.parametrize(
|
|
131
|
+
"sql,hint",
|
|
132
|
+
[
|
|
133
|
+
("DROP TABLE sales.orders", "DELETE FROM {{target}}"),
|
|
134
|
+
("TRUNCATE TABLE sales.orders", "DELETE FROM {{target}}"),
|
|
135
|
+
("ALTER TABLE sales.orders DROP COLUMN status", "CREATE OR REPLACE TABLE {{target}} AS SELECT"),
|
|
136
|
+
("GRANT SELECT ON TABLE sales.orders TO analysts", "not data changes"),
|
|
137
|
+
],
|
|
138
|
+
)
|
|
139
|
+
def test_refusals_suggest_a_safe_alternative(sql, hint):
|
|
140
|
+
with pytest.raises(PreviewGuardError) as e:
|
|
141
|
+
rewrite_for_preview(sql, "sales.orders", "sandbox.c1", lambda x: x)
|
|
142
|
+
assert hint in str(e.value)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|