pacioli-guard 0.6.2__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.
Files changed (35) hide show
  1. pacioli_guard-0.6.2/LICENSE +202 -0
  2. pacioli_guard-0.6.2/MANIFEST.in +9 -0
  3. pacioli_guard-0.6.2/PKG-INFO +398 -0
  4. pacioli_guard-0.6.2/README.md +379 -0
  5. pacioli_guard-0.6.2/license.txt +201 -0
  6. pacioli_guard-0.6.2/pacioli_guard/__init__.py +1 -0
  7. pacioli_guard-0.6.2/pacioli_guard/enforce.py +360 -0
  8. pacioli_guard-0.6.2/pacioli_guard/hooks.py +12 -0
  9. pacioli_guard-0.6.2/pacioli_guard/modules.txt +1 -0
  10. pacioli_guard-0.6.2/pacioli_guard/patches/__init__.py +0 -0
  11. pacioli_guard-0.6.2/pacioli_guard/patches/v0_6_0/__init__.py +0 -0
  12. pacioli_guard-0.6.2/pacioli_guard/patches/v0_6_0/warn_unresolved_method_grants.py +122 -0
  13. pacioli_guard-0.6.2/pacioli_guard/patches.txt +2 -0
  14. pacioli_guard-0.6.2/pacioli_guard/scope.py +908 -0
  15. pacioli_guard-0.6.2/pacioli_guard/scoping/__init__.py +0 -0
  16. pacioli_guard-0.6.2/pacioli_guard/scoping/doctype/__init__.py +0 -0
  17. pacioli_guard-0.6.2/pacioli_guard/scoping/doctype/api_key_scope/__init__.py +0 -0
  18. pacioli_guard-0.6.2/pacioli_guard/scoping/doctype/api_key_scope/api_key_scope.json +132 -0
  19. pacioli_guard-0.6.2/pacioli_guard/scoping/doctype/api_key_scope/api_key_scope.py +9 -0
  20. pacioli_guard-0.6.2/pacioli_guard/scoping/doctype/api_key_scope_doctype/__init__.py +0 -0
  21. pacioli_guard-0.6.2/pacioli_guard/scoping/doctype/api_key_scope_doctype/api_key_scope_doctype.json +31 -0
  22. pacioli_guard-0.6.2/pacioli_guard/scoping/doctype/api_key_scope_doctype/api_key_scope_doctype.py +9 -0
  23. pacioli_guard-0.6.2/pacioli_guard/scoping/doctype/api_key_scope_method/__init__.py +0 -0
  24. pacioli_guard-0.6.2/pacioli_guard/scoping/doctype/api_key_scope_method/api_key_scope_method.json +30 -0
  25. pacioli_guard-0.6.2/pacioli_guard/scoping/doctype/api_key_scope_method/api_key_scope_method.py +9 -0
  26. pacioli_guard-0.6.2/pacioli_guard/tests/__init__.py +0 -0
  27. pacioli_guard-0.6.2/pacioli_guard/tests/test_enforce.py +999 -0
  28. pacioli_guard-0.6.2/pacioli_guard/tests/test_patches.py +91 -0
  29. pacioli_guard-0.6.2/pacioli_guard/tests/test_scope.py +1660 -0
  30. pacioli_guard-0.6.2/pacioli_guard.egg-info/PKG-INFO +398 -0
  31. pacioli_guard-0.6.2/pacioli_guard.egg-info/SOURCES.txt +33 -0
  32. pacioli_guard-0.6.2/pacioli_guard.egg-info/dependency_links.txt +1 -0
  33. pacioli_guard-0.6.2/pacioli_guard.egg-info/top_level.txt +1 -0
  34. pacioli_guard-0.6.2/pyproject.toml +35 -0
  35. pacioli_guard-0.6.2/setup.cfg +4 -0
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,9 @@
1
+ # Frappe apps are normally installed via `bench get-app <git-url>` (a raw clone), but if this is
2
+ # ever built into an sdist/wheel the DocType schema, module list, and patches MUST travel with it —
3
+ # otherwise the auth_hook fires against a DocType that was never migrated. Ship the data model.
4
+ recursive-include pacioli_guard *.json
5
+ include pacioli_guard/modules.txt
6
+ include pacioli_guard/patches.txt
7
+ include pacioli_guard/hooks.py
8
+ include license.txt
9
+ include README.md
@@ -0,0 +1,398 @@
1
+ Metadata-Version: 2.4
2
+ Name: pacioli-guard
3
+ Version: 0.6.2
4
+ Summary: Deny-by-default credential governance for Frappe/ERPNext — the counting-house door (credential-layer, no core fork)
5
+ Author: John Broadway
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/john-broadway/pacioli
8
+ Project-URL: Source, https://github.com/john-broadway/pacioli
9
+ Keywords: frappe,erpnext,api-security,least-privilege,credential-scoping
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Security
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ <img src="../assets/marks/device.svg" width="72" align="right" alt="The printer's device"/>
21
+
22
+ *Tractatus de Instrumentis — the guard.* ❧ *Nulla in libro sine contraria — no debit without a credit.*
23
+
24
+ # Pacioli Guard
25
+
26
+ **Least-privilege API governance for ERPNext. Agents included.**
27
+
28
+ Frappe/ERPNext has no native way to scope an API credential. An API key authenticates *as a user*
29
+ and inherits that user's full role permissions across **every** REST endpoint — so a token you
30
+ minted so an integration (or an AI agent) could call one governed `/api/method/…` can equally
31
+ `POST /api/resource/<DocType>` directly, walking around whatever that method wrapped. OAuth2 scopes
32
+ don't close it either (they're consent claims, confirmed by Frappe's own OAuth author).
33
+
34
+ **Pacioli Guard binds a credential to an allowlist** — the methods (and, if you grant it, the
35
+ DocTypes) it may touch — and enforces it **at the credential layer**, deny-by-default. A leaked or
36
+ over-shared key becomes a blast-radius of *what you allowed*, not your whole ERP.
37
+
38
+ It governs **every** API credential on the site — an integration, a Zapier/n8n flow, a script, a
39
+ vendor token, a cron job, an MCP/A2A agent. You don't need to run AI to need this.
40
+
41
+ This is the counting-house door, in Luca Pacioli's terms: **no one writes in the books but the
42
+ appointed hand — and only in the books appointed to them.**
43
+
44
+ ## How it works — no core fork
45
+
46
+ Enforced through Frappe's public `auth_hooks` extension point, which runs **after** the api-key
47
+ authenticates and **before** the request dispatches. A scoped credential that steps outside its
48
+ allowlist gets a `403 PermissionError`; unscoped credentials (browser sessions, normal keys) are
49
+ completely untouched. Nothing in Frappe core is modified — this is a plain `bench install-app`.
50
+
51
+ ```
52
+ POST /api/resource/SI/<name>?run_method=submit → 200 (granted "Sales Invoice.submit" — resolved)
53
+ POST /api/resource/JE/<name>?run_method=submit → 403 (doctype not granted)
54
+ GET /api/method/<any-bare-rpc> → 403 (deny-unknown: bare names denied unless
55
+ granted AND on the 3-entry SAFE_METHODS)
56
+ POST /api/resource/<DocType> → 403 (raw-CRUD bypass closed, unless allow_resource)
57
+ # unscoped credential → unchanged behaviour
58
+ ```
59
+
60
+ ## Install
61
+
62
+ ```bash
63
+ # from your bench directory: wheel into the bench env, then install the app
64
+ env/bin/pip install pacioli-guard
65
+ bench --site <your-site> install-app pacioli_guard
66
+ ```
67
+
68
+ ## Scope a credential
69
+
70
+ Create an **API Key Scope** record (a first-class DocType, with child-table allowlists) for the
71
+ user whose API key you're scoping:
72
+
73
+ - `methods` — exact dotted names or `fnmatch` globs. A document method (item-URL `?run_method=submit`)
74
+ matches as `"<DocType>.submit"`. **As of 0.6.0 (deny-unknown), grant per-doctype
75
+ `"<DocType>.<method>"` patterns** — a bare RPC name only ever fires if it is one of the three
76
+ curated `SAFE_METHODS` (see "Deny-unknown" below); any other bare/unresolved method is denied
77
+ even if a pattern here matches it.
78
+ - `allow_resource` — defaults **false** (method-only; denies raw `/api/resource` CRUD).
79
+ - `resource_doctypes` — when `allow_resource` is true, an optional DocType allowlist (empty = all,
80
+ still bounded by the user's own roles).
81
+ - `Allow Read` / `Allow Create` / `Allow Write` / `Allow Delete` — the **per-credential resource
82
+ verbs** (all default on). A DocType allowlist alone admits *every* verb, so a credential meant to
83
+ *read* invoices also POSTs/PUTs/DELETEs them. Untick the verbs you don't want and the same
84
+ credential is genuinely read-only (or read+create, etc.) across its granted DocTypes. Leaving all
85
+ four ticked is the pre-narrowing behavior (full CRUD); to deny resource access entirely, untick
86
+ `allow_resource`. *Narrowing is per-credential in this version — per-DocType verb granularity is
87
+ a future increment.*
88
+ - `enabled` — the **kill switch** (defaults on). See CONTAIN below.
89
+ - `rate_limit_per_minute` — the **speed limit** (defaults 0 = none). See CONTAIN below.
90
+ - `enforce_workflow` — the **Workflow-bypass gate** (defaults **off**, opt-in per credential). See
91
+ "Workflow enforcement" below.
92
+
93
+ A deprecated one-version fallback still reads a JSON grant from a `api_scope` Long Text field on
94
+ **User** (`{ "methods": [...], "allow_resource": false }`) so pre-DocType setups keep enforcing
95
+ while they migrate. The enforcement seam (`pacioli_guard/scope.py`) is identical either way.
96
+
97
+ ### Body-doctype scoping (submit/cancel) — the generic-RPC residual, closed for every submit/cancel RPC
98
+
99
+ A `methods` entry ordinarily matches by NAME only — it does not by itself constrain the doctype a
100
+ generic RPC touches, since `frappe.client.*`/`run_doc_method` take their real target from the
101
+ request BODY, not the URL. **As of 0.5.0 (extended in 0.5.1)** the guard reads the doctype out of the
102
+ body and enforces the SAME `"<DocType>.submit"`/`"<DocType>.cancel"` pattern the item-URL
103
+ `?run_method=submit` vector already required, for **every frappe RPC that calls `doc.submit()`/
104
+ `doc.cancel()` directly** (the shape that bypasses frappe's own `is_whitelisted` on an override-doctype
105
+ like Journal Entry):
106
+ `frappe.client.submit`, `frappe.client.cancel`, **`frappe.desk.form.save.cancel`** (the Desk UI's own
107
+ cancel endpoint), **`frappe.desk.doctype.bulk_update.bulk_update.submit_cancel_or_update_docs`** (bulk
108
+ submit/cancel of up to 500 docs), `run_doc_method` (v1 `dt`/`dn`/`docs` and v2 `document`/`method`), and
109
+ `frappe.desk.form.save.savedocs` with a Submit/Update/Cancel `action`. So granting a credential
110
+ `"Sales Invoice.submit"` lets it submit a Sales Invoice through *any* of these transports, but **not** a
111
+ Journal Entry or any other doctype through them, even though the credential never named the generic RPC.
112
+ A malformed/missing doctype — or the bulk RPC's non-submit/cancel `action="update"` — fails **closed**
113
+ (denied), never falls back to doctype-blind. The two Desk/bulk names and the fail-closed on bulk-update
114
+ were added in **0.5.1** after a guard-bypass redteam found them missing from 0.5.0 (a CRITICAL bulk
115
+ bypass + the Desk cancel), and the Desk Submit alias (`frappe.desk.form.save.submit`) plus the
116
+ **docstatus-by-body class** were added by a completeness audit against frappe 17 source: because
117
+ `frappe.client.save`/`.insert`/`.insert_many`/`.bulk_update` submit or cancel a doc whenever its
118
+ body carries `docstatus` 1/2 (via `Document.save()`'s transition detection), those are recognised
119
+ too — a docstatus-1/2 body rewrites to `"<DocType>.submit"`/`".cancel"`, a mixed-doctype batch or
120
+ `cancel_all_linked_docs` **deny-closes**, all before 0.5.0 ever left internal.
121
+ As of **0.6.0** nothing "stays doctype-blind — grant with care" anymore: the shapes that used to
122
+ (the draft-create path of `save`/`insert`, `set_value`, `bulk_delete`, bare read/query RPCs) are
123
+ **denied as bare grants** under deny-unknown below — a scoped credential creates drafts via
124
+ `POST /api/resource/<DocType>` (`allow_resource` + `Allow Create`), and `run_doc_method` now
125
+ resolves EVERY inner method (not just submit/cancel/discard) to `"<DocType>.<method>"`.
126
+ **Live-proven on the real Frappe v16 bench** at the Gate 10 close-out (2026-07-07): Journal Entry
127
+ submit/cancel drove through this body-doctype rewrite (`frappe.client.submit`/`.cancel` verbatim in
128
+ the bench request log, 0→1→2), SI/PI/PE stayed clean on the URL-path shape, and the per-doctype
129
+ `apply_workflow` re-grant proved positive — `../SCOPED-TOKEN-PROOF.md` **PHASE M** (PHASE L is the
130
+ pre-fix historical record). See CHANGELOG 0.5.0–0.6.0.
131
+
132
+ ### Deny-unknown (0.6.0) — the posture flip, SHIPPED
133
+
134
+ Three adversarial passes against frappe 17 source drove the body-doctype coverage above — and the
135
+ third proved the honest boundary: a pure, I/O-free request classifier **cannot** be provably
136
+ complete (a *2-hop laundering* vector carries the target doctype **nowhere in the request** — see
137
+ the `Bulk Update` hard-deny below). Whack-a-mole on method names does not converge, so **0.6.0
138
+ inverts the posture**: a `methods` grant on a method call is honored ONLY when the call is
139
+ **doctype-RESOLVED** — the route itself carried the doctype (item-URL `?run_method`, v2
140
+ path-carried doc-method, v2 two-segment controller method, or a body-doctype rewrite above) — OR
141
+ the bare name is one of exactly **three curated `SAFE_METHODS`** (exact names, no globs, each
142
+ read-only with no docstatus/data mutation):
143
+
144
+ - `frappe.auth.get_logged_user` — identity probe (`pacioli doctor`)
145
+ - `frappe.desk.form.linked_with.get_submitted_linked_docs` — linked-doc lookup (the UNDO graph)
146
+ - `erpnext.controllers.stock_controller.show_accounting_ledger_preview` — PLAN preview
147
+
148
+ **Anything else is denied even if a grant pattern fnmatches it** — a new frappe RPC is denied until
149
+ reviewed, instead of open until enumerated. SAFE_METHODS membership is necessary-not-sufficient
150
+ (the grant must still name it), and the **admission criterion** is strict: read-only, no
151
+ docstatus/data mutation, reviewed on entry. **There is NO escape hatch** — no site config, no
152
+ per-credential flag — because an escape hatch is exactly the open-until-enumerated posture this
153
+ flip removes; a new safe method is a reviewed, changelogged, version-bumped act.
154
+
155
+ Consequences worth knowing before you upgrade (full list: CHANGELOG 0.6.0):
156
+
157
+ - `frappe.model.workflow.apply_workflow` is deliberately **not** safe-listed (it submits/cancels
158
+ internally); it resolves per-doctype from its `doc` body param — re-grant it as
159
+ `"<DocType>.apply_workflow"`.
160
+ - `run_doc_method` resolves **every** inner method to `"<DocType>.<method>"` (a missing/non-string
161
+ method deny-closes) — bare it never fires.
162
+ - **`Bulk Update` is hard-denied, ungrantable**: its whitelisted instance method reads the victim
163
+ doctype from the SAVED RECORD (`document_type` + `field=docstatus` on a `Bulk Update` row), so no
164
+ request classifier can resolve it and no grant can express it. Denied before the grant check.
165
+ - The `bench migrate` for 0.6.0 runs a **log-only audit** of existing grants and WARNs per pattern
166
+ the new posture treats differently (best-effort static heuristic; it cannot break the migrate).
167
+
168
+ **Named residuals — the honest boundary of 0.6.0** (stated, not silently claimed closed):
169
+
170
+ - **R3 — safe-listed reads bypass `resource_doctypes`.** The two safe-listed *read* methods carry a
171
+ doctype in their body that is **not** checked against `resource_doctypes` — a disclosure-only
172
+ bypass of the read-narrowing axis (no mutation), pre-existing.
173
+ - **v2 two-segment `/method/<dt>/<method>` grants the whole controller module.** It counts as
174
+ doctype-resolved (the doctype IS in the URL path, so it can't be spoofed), but frappe runs it as a
175
+ **module-level** whitelisted function in that doctype's controller — so a broad `<DocType>.*` grant
176
+ regains *every* whitelisted function in that module, not just document methods. Bounded
177
+ (`load_doctype_module` raises on a non-doctype, so `frappe.client.*` can't be laundered this way;
178
+ most ERPNext controller functions are unsaved mappers) but real: **grant explicit
179
+ `<DocType>.<method>` patterns, not `<DocType>.*`,** for a credential that shouldn't reach a
180
+ controller's whole surface.
181
+ - **v2 collection-mutation routes classify as `create` (NEW — found by the 0.6.0 redteam, staged for
182
+ Gate 10, NOT yet closed).** `POST /api/v2/document/<DocType>/bulk_update` and `…/bulk_delete` are
183
+ classified as a `resource` **create**, but frappe writes/submits (docstatus carried per-item in the
184
+ `docs` list) and *deletes* through them — so a credential narrowed to the `create` verb can write/
185
+ submit/delete existing docs of a granted doctype, and the `enforce_workflow` gate (which reads only
186
+ a top-level `docstatus`) misses the per-item one. Same doctype (not a cross-doctype spoof) and it
187
+ requires `allow_resource`. **Live-checked on the v16 bench (2026-07-06, Gate 10): this route does
188
+ NOT exist on Frappe v16** — `/api/v2/document/<Dt>/bulk_update` resolves to a document-name lookup
189
+ (same `DoesNotExistError` as any garbage trailing segment), so there is no mutating handler behind
190
+ it. The residual reappears only against v17-dev source, so it stays documented (not closed) for
191
+ forward-compat, but it is not a live hole on v16.
192
+ - **Container/tool-DocType 2-hop vectors — four now HARD-DENIED, reconcile a disclosed residual
193
+ (readiness audit + hardening, 2026-07-10).** The same 2-hop shape as `Bulk Update` — a whitelisted
194
+ method on a "container" doctype that reads its *victim* doctype from a **saved record** or a
195
+ **nested child-table row**, not from the request the classifier sees — recurs across ERPNext's
196
+ accounting module. The broker governs a small fixed set of doctypes; every tool-DocType of this
197
+ shape it does **not** use is now added to the same ungrantable hard-deny set (deny-more-only,
198
+ zero-regression):
199
+ - **`Data Import` / `Bank Statement Import` `form_start_import`** (v2 `/method/<DocType>/…`, resolves
200
+ to `("method", "Data Import.form_start_import")`) — a granted import-controller method would drive
201
+ insert+submit of whatever `reference_doctype` the target record names. **HARD-DENIED (ungrantable).**
202
+ - **`Unreconcile Payment` / `Repost Accounting Ledger`** — same child-table-of-references shape
203
+ (plausible, not traced to full depth; a hard-deny is safe regardless since the broker never uses
204
+ them). **HARD-DENIED (ungrantable).**
205
+ - **`Payment Reconciliation.reconcile`** (`run_doc_method`; `document.allocation[*].reference_*`) —
206
+ the allocation child rows name arbitrary Payment Entry / Sales Invoice / Journal Entry docs, and
207
+ ERPNext relinks them with `ignore_permissions=True`, reaching those doctypes with their **own role
208
+ permissions bypassed**. This one **cannot** be classifier-closed: the broker's own F-R2 write
209
+ *needs* `reconcile`, and a malicious call is byte-identical to the legitimate one (same
210
+ `run_doc_method`, same `Payment Reconciliation` doc, same nested refs), so a hard-deny would break
211
+ the broker and any per-credential carve-out is inherited by a stolen broker credential — the exact
212
+ threat. It stays a **disclosed residual**, closed by posture. **Operator rule:** grant
213
+ `Payment Reconciliation.reconcile` ONLY to the broker's own credential (which owns and constructs
214
+ the payload from a pinned plan — an agent cannot inject an allocation list); never to a general
215
+ agent credential, and never grant `<DocType>.*` on a container/tool doctype. Design + the rejected
216
+ shape-deny candidate: `../docs/plans/2026-07-10-container-doctype-2hop-hardening.md`.
217
+
218
+ The deny-unknown enforcement above is **live-proven on a real Frappe v16 bench** (2026-07-06, Gate 10
219
+ — bare-deny, the v2 dt-decoy spoof denied, SAFE_METHODS fire, apply_workflow per-doctype re-grant,
220
+ Bulk Update ungrantable, granted-resolved not over-blocked, migrate audit runs without breaking
221
+ migrate). Document-submit end-to-end (JE/SI/PI/PE) closed 2026-07-07: JE submit/cancel live through
222
+ the body-doctype rewrite (`frappe.client.submit` verbatim in the bench request log, 0→1→2), SI/PI/PE
223
+ regression clean on the URL-path shape, and the per-doctype `apply_workflow` re-grant proven positive
224
+ (a real Draft → Pending Approval transition) — broker-side record `SCOPED-TOKEN-PROOF.md` PHASE M.
225
+
226
+ ## CONTAIN — the kill switch and the speed limit
227
+
228
+ The danger of an agent credential isn't just *what* it can call — it's **velocity under hijack**: a
229
+ compromised or misbehaving agent does allowed things, fast, until someone notices. Guard already
230
+ sits on every request the credential makes, so containment lives here too. Two fields on the same
231
+ **API Key Scope** record:
232
+
233
+ - **`enabled` (kill switch).** Untick it and **every** request from that credential is denied at
234
+ the chokepoint — effective on the *next request*, no restart, no cache to wait out (the grant is
235
+ read per request). It dominates the allowlists: a killed credential can't call anything, not even
236
+ what it was granted. A grant created before this field existed reads as enabled — the field's
237
+ absence is not a kill.
238
+ - **`rate_limit_per_minute` (speed limit).** `0` (default) = no limit. When set, requests are
239
+ counted per fixed one-minute window and the request over the limit gets a `403` naming the limit.
240
+ **Every** request the credential makes burns budget — permitted or denied — because what's being
241
+ contained is the credential's total velocity, not its success rate.
242
+
243
+ What CONTAIN stops: runaway velocity (a hijacked or looping agent gets damped to N calls/minute)
244
+ and gives you an instant, no-deploy revoke (untick one box).
245
+
246
+ What it does **NOT** do — honestly:
247
+
248
+ - The rate counter lives in the site cache (`frappe.cache()`), so it is **best-effort velocity
249
+ damping, not tamper-evident accounting** — a cache flush (or Redis restart) resets the window.
250
+ It is a damper, not a ledger; don't cite its counts as an audit record.
251
+ - Fixed windows have the classic **boundary burst**: a credential can spend a full budget in the
252
+ last second of one window and another in the first second of the next — briefly ~2× the nominal
253
+ rate. Acceptable for damping; set the limit with that in mind.
254
+ - If the cache is unusable while a limit is set, that credential **fails closed** (denied) — whoever
255
+ set a limit opted into containment, and an uncountable window can't honestly be called under it.
256
+ Credentials with no limit never touch the counter.
257
+ - **To revoke, untick `enabled` — do not delete the scope doc.** The kill switch is the sanctioned
258
+ revoke, and it always wins. Deleting the *API Key Scope* row is not the same thing: if a site
259
+ still carries a legacy `User.api_scope` JSON grant from before the DocType existed (the deprecated
260
+ one-version fallback), deleting the row makes the credential fall through to that older grant —
261
+ which predates `enabled` and so reads as *enabled*. During a migration window, delete-to-revoke
262
+ can silently reopen a credential; untick-to-revoke never can. (Once a site has fully migrated off
263
+ the legacy field, this footgun is gone.)
264
+
265
+ Every guard denial — out-of-scope, kill switch, or rate — also writes a row to Frappe's stock
266
+ **Error Log** (`frappe.log_error`, title prefixed `Pacioli Guard denied a request`), so denials are
267
+ visible in the desk without a new DocType. The log write is fail-open by design: a failure to log
268
+ can never suppress the deny.
269
+
270
+ ## Workflow enforcement — the belt-and-suspenders gate
271
+
272
+ Pacioli's **broker** (the MCP tool front door) already refuses to `submit` a workflow-governed
273
+ document on the agent's own path — that's `pacioli/workflow.py`. But Frappe itself does **not**
274
+ enforce Workflow on a direct `docstatus` change (`validate_workflow` only fires when the document's
275
+ `workflow_state` field itself changes on save), so the SAME scoped credential that's denied by the
276
+ broker can submit around a configured approval chain with a raw REST call that never touches the
277
+ broker at all. `enforce_workflow` closes that at the **credential layer** — it turns "governs the
278
+ agent's path" into "governs every api-key path through this credential."
279
+
280
+ Turn it on per credential (**off by default** — like every CONTAIN field before it, a gate that can
281
+ newly deny a previously-passing call must never flip on site-wide by surprise):
282
+
283
+ ```
284
+ enforce_workflow = 1
285
+ ```
286
+
287
+ With it on, `check_scope` refuses — AFTER the existing scope allowlist, on a call the credential
288
+ would otherwise be permitted to make — any of:
289
+
290
+ - A `submit`/`cancel` **method call** on a doctype with an active Workflow (covers the v1 item-URL
291
+ `run_method`, the v2 path-carried doc-method, and the legacy `?cmd=` route alike — they all
292
+ classify to the same shape).
293
+ - A raw `PUT`/`PATCH` to `/api/resource/<DocType>/<name>` (v1) or `/api/v2/document/<DocType>/<name>`
294
+ (v2) whose body carries a `docstatus` key at all, against a workflow-governed doctype — the sneaky
295
+ raw-REST update path. The mere *presence* of the key is the signal; this does not read/compare the
296
+ document's current `docstatus` (a fragile extra DB read).
297
+ - A `POST` **create** carrying a *submitting* `docstatus` (1 or 2) — insert-as-submitted. Here
298
+ presence alone is not the signal (a draft legitimately posts `docstatus: 0`); only a submitting
299
+ value is.
300
+ - The Desk UI's own **`frappe.desk.form.save.savedocs`** endpoint with an `action` other than a
301
+ plain draft `"Save"` — its method name never ends in `submit`/`cancel`, so it is recognised
302
+ specifically (the doctype is read from its `doc` body param); a missing/unknown action is treated
303
+ as docstatus-moving (deny-biased).
304
+
305
+ ...unless the call **is** `frappe.model.workflow.apply_workflow` — the sanctioned transition path,
306
+ exempt from *this* gate (it still clears the kill switch, the rate limit, and the base scope
307
+ allowlist like any other call; "exempt" means never treated as a workflow *bypass*, not "waved
308
+ through the guard entirely").
309
+
310
+ ### What it does **NOT** do — honestly
311
+
312
+ - **Body-doctype submit/cancel ARE covered here now (0.5.1).** This gate judges the SAME
313
+ body-doctype-rewritten target the base scope gate resolves — `frappe.client.submit`/`.cancel`,
314
+ the Desk cancel, bulk submit/cancel, `run_doc_method`(submit/cancel), and `savedocs`
315
+ Submit/Update/Cancel all resolve to `"<DocType>.submit"`/`".cancel"`, so a workflow-governed
316
+ submit/cancel on a doctype named only in the request body is caught, not just the URL-path
317
+ `run_method` shape. This closed a real gap (0.5.0 ran on the un-rewritten target → a body-doctype
318
+ submit yielded doctype `"frappe.client"` → no workflow found → silent no-op); it mattered most for
319
+ **Journal Entry**, which submits/cancels EXCLUSIVELY via `frappe.client.submit`/`.cancel` (its
320
+ overridden submit/cancel aren't whitelisted) and would otherwise have had zero workflow protection.
321
+ Found by the same guard-bypass redteam, before 0.5.0 shipped. The remaining theoretical residual is
322
+ narrow: a *non*-submit/cancel method that flips `docstatus` by raw field write (`frappe.client.set_value`
323
+ on the `docstatus` field) is not rewritten — mitigated because the base scope grants such blind
324
+ methods only with care, and the raw-REST `PUT …?docstatus=` path is caught separately (below).
325
+ - **Credential-layer boundary, same as every other gate in this hook.** Fires only for
326
+ api-key/`Basic` requests. NOT OAuth Bearer, desk/cookie sessions, background jobs, the bench
327
+ console, or script/report calls. This closes the gap for *other scoped api callers bypassing the
328
+ broker* — it is not an ERPNext-wide Workflow patch; only frappe core touching `validate_workflow`
329
+ itself could do that.
330
+ - **Ambiguous/malformed Workflow config is not detected the way the broker detects it.** The
331
+ broker's own pure core explicitly refuses when more than one active Workflow governs a doctype
332
+ (naming every one it found). This gate relies on frappe's internal `get_workflow_name`, which is
333
+ not known to expose that ambiguity at all — if a site somehow carries more than one active
334
+ Workflow for a doctype, this gate silently governs by whichever one frappe's own lookup picked. Do
335
+ not assume this mirrors the broker's ambiguity handling.
336
+ - **Deny-biased on lookup failure, not deny-biased on ambiguity it can't see.** If the internal
337
+ Workflow lookup itself raises for a call that already looks docstatus-changing, that is treated as
338
+ "assume governed" and refused — an unverifiable answer is never read as "no workflow."
339
+ - **Live-verified (Gate 7, 2026-07-03, real ERPNext v16 bench).** Both knowledge-pins held under
340
+ live falsification: `frappe.model.workflow.get_workflow_name` exists at the pinned import path and
341
+ returns the active workflow name (`'SI Approval (Gate5)'`) for a governed doctype and a falsy value
342
+ for an ungoverned one; and a raw JSON `PUT` `docstatus` body **does** surface through
343
+ `frappe.form_dict` (leg refused 403), as does the Desk `savedocs` `doc`/`action` (leg refused 403).
344
+ All four `is_docstatus_changing` detection branches were caught with `enforce_workflow=1` — item-URL
345
+ `run_method=submit` (the governed SI stayed docstatus 0), `savedocs` Submit, raw `PUT {docstatus:1}`,
346
+ and POST-create `docstatus:1` — while the sanctioned `apply_workflow` was not guard-blocked and an
347
+ ungoverned doctype was not over-blocked. Default-off was A/B-proven on the same vector
348
+ (`enforce_workflow=0` → 200, the SI submitted). The generic-RPC residual below was confirmed live as
349
+ documented (see the footgun note): `/api/method/run_doc_method` with the doctype in its body is not
350
+ classified as docstatus-changing, so a credential that is *also* granted that broad method can walk
351
+ around this gate — which is exactly why the default tight scope denies such methods outright.
352
+
353
+ ## Honest scope
354
+
355
+ - Governs **programmatic** REST access (`/api/method` + `/api/resource` v1/v2, incl. item-URL
356
+ `run_method` doc-methods and the legacy `?cmd=` RPC). Frappe's own roles already govern
357
+ desk/browser users, correctly — this doesn't change their experience.
358
+ - **Credential schemes it scopes:** `token <key>:<secret>` and `Basic base64(key:secret)`
359
+ (`curl -u`). **OAuth2 `Bearer` tokens are NOT scoped** — they carry Frappe's own OAuth scopes and
360
+ authenticate as a real user, but this gate deliberately does not touch them (governing OAuth is a
361
+ separate layer, stated not silently skipped). If your agent authenticates via OAuth Bearer, this
362
+ credential floor does not yet constrain it.
363
+ - Internal `frappe.client` RPC and background jobs run in a non-credential context (no `Authorization`
364
+ header) and are not this hook's surface; tracking them is production hardening, tracked separately.
365
+ - A `methods` entry is enforced **deny-unknown as of 0.6.0**: it fires only on a doctype-RESOLVED
366
+ call (item-URL `run_method`, v2 path/two-segment doc-methods, or a body-doctype rewrite — the
367
+ submit/cancel/apply_workflow RPCs and every `run_doc_method` inner method resolve from the
368
+ request body per 0.5.0–0.6.0) or on an exact `SAFE_METHODS` name (three read-only utilities).
369
+ A bare/unresolved generic RPC — a draft `save`/`insert`, `set_value`, `bulk_delete`, any
370
+ unrecognised name — is **denied even if granted** (see "Deny-unknown" above; live-proven
371
+ 2026-07-06: a *granted* bare `frappe.model.workflow.apply_workflow` and a *granted*
372
+ `Bulk Update.bulk_update` both 403'd on the real bench).
373
+ - Scope **narrows** a credential; it never widens one (a scoped user still can't exceed its roles).
374
+ One honest exception: a granted method that ERPNext itself runs with `ignore_permissions=True`
375
+ (notably `Payment Reconciliation.reconcile`) reaches its referenced docs with *their* roles
376
+ bypassed — see the container/tool-DocType 2-hop residual under "Named residuals" and grant such
377
+ methods only to the broker's own credential.
378
+ - Workflow-governed docstatus changes are a SEPARATE opt-in gate (`enforce_workflow`, off by
379
+ default) — see "Workflow enforcement" above for its own honest limits (generic-RPC footgun,
380
+ credential-layer boundary, ambiguity handling, knowledge-pinned shapes).
381
+
382
+ ## Design & proof
383
+
384
+ The security-critical decision logic (`pacioli_guard/scope.py`) is a **pure module** with no Frappe
385
+ import, unit-tested bench-free (`pacioli_guard/tests/test_scope.py`). The live end-to-end proof
386
+ (scoped credential denied on both `/api/method` and `/api/resource` against a real Frappe v16 bench,
387
+ frappe attributing the 403 to this app) is written up in `../SCOPED-TOKEN-PROOF.md`; the market/novelty
388
+ verdict is recorded in the workshop's internal research verdict (a 73-agent adversarial review; not shipped in this tree).
389
+
390
+ Part of **Pacioli** — least-privilege API governance for ERPNext. Pacioli Guard is the foundation;
391
+ the Pacioli MCP broker (planned/consented/proven/reversible tool calls) is the agent front door built on top.
392
+
393
+ License: Apache-2.0.
394
+
395
+
396
+ ---
397
+
398
+ <sub>VENETIIS MCDXCIV · IN THE WORKSHOP OF JOHN BROADWAY · MMXXVI</sub>