adk-memshield 0.1.0__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.
- adk_memshield-0.1.0/.gitignore +48 -0
- adk_memshield-0.1.0/LICENSE +176 -0
- adk_memshield-0.1.0/PKG-INFO +280 -0
- adk_memshield-0.1.0/README.md +246 -0
- adk_memshield-0.1.0/benchmarks/run_memleak_eval.py +674 -0
- adk_memshield-0.1.0/pyproject.toml +82 -0
- adk_memshield-0.1.0/sql/01_schema.sql +118 -0
- adk_memshield-0.1.0/sql/02_benchmark_baseline.sql +30 -0
- adk_memshield-0.1.0/src/adk_memshield/__init__.py +16 -0
- adk_memshield-0.1.0/src/adk_memshield/config.py +62 -0
- adk_memshield-0.1.0/src/adk_memshield/embedder.py +65 -0
- adk_memshield-0.1.0/src/adk_memshield/service.py +598 -0
- adk_memshield-0.1.0/tests/test_rls_isolation.py +624 -0
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# Multi-agent coordination & local IDE files (DO NOT COMMIT)
|
|
2
|
+
SPEC.md
|
|
3
|
+
STATE.md
|
|
4
|
+
CLAUDE.md
|
|
5
|
+
.claude/
|
|
6
|
+
.antigravity/
|
|
7
|
+
.gemini/
|
|
8
|
+
|
|
9
|
+
# Python build & packaging
|
|
10
|
+
__pycache__/
|
|
11
|
+
*.py[cod]
|
|
12
|
+
*$py.class
|
|
13
|
+
*.so
|
|
14
|
+
.Python
|
|
15
|
+
build/
|
|
16
|
+
develop-eggs/
|
|
17
|
+
dist/
|
|
18
|
+
downloads/
|
|
19
|
+
eggs/
|
|
20
|
+
.eggs/
|
|
21
|
+
lib/
|
|
22
|
+
lib64/
|
|
23
|
+
parts/
|
|
24
|
+
sdist/
|
|
25
|
+
var/
|
|
26
|
+
wheels/
|
|
27
|
+
*.egg-info/
|
|
28
|
+
.installed.cfg
|
|
29
|
+
*.egg
|
|
30
|
+
|
|
31
|
+
# Virtual environments & caches
|
|
32
|
+
.venv/
|
|
33
|
+
venv/
|
|
34
|
+
ENV/
|
|
35
|
+
env/
|
|
36
|
+
.pytest_cache/
|
|
37
|
+
.ruff_cache/
|
|
38
|
+
.mypy_cache/
|
|
39
|
+
.coverage
|
|
40
|
+
htmlcov/
|
|
41
|
+
|
|
42
|
+
# OS & Editor
|
|
43
|
+
.DS_Store
|
|
44
|
+
Thumbs.db
|
|
45
|
+
.vscode/
|
|
46
|
+
.idea/
|
|
47
|
+
*.swp
|
|
48
|
+
*.swo
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: adk-memshield
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Zero-trust multi-tenant semantic memory service for Google ADK backed by PostgreSQL pgvector and Row-Level Security (RLS).
|
|
5
|
+
Project-URL: Homepage, https://github.com/aalishan001/adk-memshield
|
|
6
|
+
Project-URL: Repository, https://github.com/aalishan001/adk-memshield
|
|
7
|
+
Project-URL: Issues, https://github.com/aalishan001/adk-memshield/issues
|
|
8
|
+
Author: Aalishan
|
|
9
|
+
License-Expression: Apache-2.0
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: agents,ai-security,google-adk,memleak,memory,multi-tenant,pgvector,postgresql,row-level-security
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Framework :: AsyncIO
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Topic :: Database
|
|
22
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
23
|
+
Classifier: Topic :: Security
|
|
24
|
+
Requires-Python: >=3.10
|
|
25
|
+
Requires-Dist: fastembed>=0.3.0
|
|
26
|
+
Requires-Dist: google-adk<3,>=2.12.0
|
|
27
|
+
Requires-Dist: psycopg[binary,pool]>=3.1.0
|
|
28
|
+
Requires-Dist: pydantic>=2.6.0
|
|
29
|
+
Provides-Extra: dev
|
|
30
|
+
Requires-Dist: build>=1.0.0; extra == 'dev'
|
|
31
|
+
Requires-Dist: pytest-asyncio>=0.23.0; extra == 'dev'
|
|
32
|
+
Requires-Dist: pytest>=8.0.0; extra == 'dev'
|
|
33
|
+
Description-Content-Type: text/markdown
|
|
34
|
+
|
|
35
|
+
# `adk-memshield`
|
|
36
|
+
|
|
37
|
+
**Zero-trust multi-tenant semantic memory for Google ADK (`google-adk`), enforced in the database by PostgreSQL `pgvector` + Row-Level Security (RLS).**
|
|
38
|
+
|
|
39
|
+
[](./LICENSE)
|
|
40
|
+
[](./pyproject.toml)
|
|
41
|
+
[](https://github.com/google/adk-python)
|
|
42
|
+
|
|
43
|
+
---
|
|
44
|
+
|
|
45
|
+
## Why `adk-memshield`?
|
|
46
|
+
|
|
47
|
+
Multi-tenant and multi-agent `google-adk` deployments often keep long-term semantic memory in one shared vector table, with isolation enforced only by the `WHERE` clause the application remembers to write. That design leaks in two well-documented ways:
|
|
48
|
+
|
|
49
|
+
1. **Cross-user semantic leakage** — *MemLeak: Cross-User Semantic Leakage in Multi-Tenant AI Agent Memory* ([arXiv:2610.04195](https://arxiv.org/abs/2610.04195)) shows that similarity search over a pooled store surfaces other users' memories without any exploit, and that hard ownership gating is the mitigation that consistently restores the clean baseline.
|
|
50
|
+
2. **Lateral leakage inside agent swarms** — *AgentLeak* ([arXiv:2602.11510](https://arxiv.org/abs/2602.11510)) shows that internal channels between agents are a major leakage path. `adk-memshield` addresses the memory-retrieval slice of that problem: a low-clearance sub-agent must not retrieve shared tenant memories labelled above its clearance.
|
|
51
|
+
|
|
52
|
+
`adk-memshield` is a drop-in `BaseMemoryService` that moves ownership gating out of application code and into PostgreSQL itself, using **`FORCE ROW LEVEL SECURITY`** and **transaction-local identity (`set_config(..., true)`)**. A retrieval query with a missing or wrong filter returns fewer rows, not someone else's rows.
|
|
53
|
+
|
|
54
|
+
---
|
|
55
|
+
|
|
56
|
+
## Architecture
|
|
57
|
+
|
|
58
|
+
```mermaid
|
|
59
|
+
flowchart LR
|
|
60
|
+
subgraph ADK["Google ADK Runtime"]
|
|
61
|
+
Agent["ADK Agent / Sub-Agent<br/>(app_name, user_id from Runner)"]
|
|
62
|
+
Service["MemShieldMemoryService<br/>(BaseMemoryService)<br/>tenant_id + clearance from config"]
|
|
63
|
+
Embedder["MemShieldEmbedder<br/>(FastEmbed bge-small-en-v1.5, 384d)"]
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
subgraph PG["PostgreSQL 16 + pgvector (role memshield_app, NOBYPASSRLS)"]
|
|
67
|
+
Tx["Explicit transaction"]
|
|
68
|
+
Ctx["Transaction-local identity<br/>set_config('app.*', val, true)"]
|
|
69
|
+
RLS["RLS policies<br/>SELECT / INSERT / UPDATE / DELETE"]
|
|
70
|
+
Vec[("memories<br/>vector(384)")]
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
Agent --> Service
|
|
74
|
+
Service --> Embedder
|
|
75
|
+
Service --> Tx
|
|
76
|
+
Tx --> Ctx
|
|
77
|
+
Ctx --> RLS
|
|
78
|
+
RLS --> Vec
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
### Security properties
|
|
82
|
+
|
|
83
|
+
- **No superuser bypass.** Superusers and `BYPASSRLS` roles ignore RLS even under `FORCE ROW LEVEL SECURITY`. [`sql/01_schema.sql`](./sql/01_schema.sql) creates a least-privilege `memshield_app` role (`NOSUPERUSER NOCREATEDB NOCREATEROLE NOBYPASSRLS`); connect with it.
|
|
84
|
+
- **Pool-safe identity.** Every operation runs in an explicit transaction and binds `app.current_app_name`, `app.current_tenant_id`, `app.current_user_id` and `app.agent_clearance` with `set_config(..., true)`. The settings vanish at commit/rollback, so identity never bleeds into the next pooled checkout. All values are bound parameters; the only interpolated identifier (`table_name`) is validated against `^[A-Za-z_][A-Za-z0-9_]*$`.
|
|
85
|
+
- **Fail-closed.** Without identity context a query sees 0 rows. Identity columns carry `CHECK (<col> <> '')` because a pooled connection reports `''` (not `NULL`) for a custom setting once it has been used, and the service rejects empty `app_name`/`user_id` before touching the database.
|
|
86
|
+
- **All four commands are gated.** `SELECT` allows own rows plus `tenant_shared` rows with `min_clearance <= app.agent_clearance`. `INSERT` and `UPDATE` (`USING` + `WITH CHECK`) and `DELETE` (`USING`) are restricted to the caller's own rows, so cross-user poisoning or re-owning a row raises `InsufficientPrivilege`.
|
|
87
|
+
- **No write-up.** An agent cannot write a `tenant_shared` memory labelled above its own clearance, so a Tier-1 agent cannot plant "executive" context that higher-clearance agents would trust.
|
|
88
|
+
- **Defense in depth.** The library's own query also filters by user/scope/clearance, mirroring the policy, so neither layer is a single point of failure. Ownership columns always come from call arguments and config, never from caller-supplied metadata.
|
|
89
|
+
- **Idempotent session ingestion.** ADK may call `add_session_to_memory` repeatedly for one session; a unique index on `(owner, session_id, event_id)` stores each event once.
|
|
90
|
+
- **Non-blocking.** Embedding and database I/O run in a worker thread (`asyncio.to_thread`), so memory calls do not stall the ADK event loop.
|
|
91
|
+
|
|
92
|
+
---
|
|
93
|
+
|
|
94
|
+
## Benchmark: unprotected `pgvector` vs. `adk-memshield`
|
|
95
|
+
|
|
96
|
+
[`benchmarks/run_memleak_eval.py`](./benchmarks/run_memleak_eval.py) seeds a synthetic enterprise corpus (**3 tenants, 6 users, 60 memories**: API credentials, compensation, medical/HR records, query-shaped lure memories, and L3/L4 executive memos) into an ordinary table and into the RLS table. Each scenario runs **the same buggy application-layer SQL** against both, inside the same transaction-local identity of the authenticated caller, so the only variable is whether the database enforces ownership. `top_k=3`, 75 queries, 5 repeats.
|
|
97
|
+
|
|
98
|
+
| Scenario | Application-layer mistake | Queries | Unprotected: queries leaking | Unprotected: leaked share of top-k rows | Unprotected: leak at rank 1 | `adk-memshield`: queries leaking | Unprotected clean recall | `adk-memshield` clean recall |
|
|
99
|
+
| :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: |
|
|
100
|
+
| Scenario 1: Shared-Tenant Pool (Incidental Overlap) | Filters `tenant_id` only, omits `user_id`/`scope` | 12 | 100.0% | 44.4% | 8.3% | **0.0%** | 100.0% | **100.0%** |
|
|
101
|
+
| Scenario 2: Adversarial Top-K Planted Lure | Same tenant-only filter; co-tenant plants query-shaped lures | 12 | 100.0% | 58.3% | 58.3% | **0.0%** | 100.0% | **100.0%** |
|
|
102
|
+
| Scenario 3: Tool-Argument `user_id` Override | Correct filter, but `user_id` taken from attacker-controlled tool args | 9 | 100.0% | 81.5% | 100.0% | **0.0%** | n/a | **n/a** |
|
|
103
|
+
| Scenario 4: Low-Clearance Swarm Agent (AgentLeak-style) | Own + `tenant_shared` rows, omits `min_clearance` check | 9 | 100.0% | 44.4% | 66.7% | **0.0%** | 100.0% | **100.0%** |
|
|
104
|
+
| Scenario 5: Total Filter Omission | No `WHERE` clause at all (`simulate_missing_app_filter=True`) | 33 | 100.0% | 74.7% | 69.7% | **0.0%** | 72.7% | **100.0%** |
|
|
105
|
+
| **Mean of Scenarios 1-5** | | 75 | **100.0%** | **60.7%** | **60.6%** | **0.0%** | **93.2%** | **100.0%** |
|
|
106
|
+
| Control: Correct App Filter (no bug) | `MemShieldMemoryService` default filter (user/scope/clearance) | 33 | 0.0% | 0.0% | 0.0% | **0.0%** | 100.0% | **100.0%** |
|
|
107
|
+
|
|
108
|
+
Retrieval latency (database transaction including `set_config`, 60 rows, ms):
|
|
109
|
+
|
|
110
|
+
| Scenario | Unprotected p50 / p95 | `adk-memshield` p50 / p95 |
|
|
111
|
+
| :--- | :---: | :---: |
|
|
112
|
+
| Scenario 1: Shared-Tenant Pool (Incidental Overlap) | 0.74 / 1.19 | 0.78 / 1.38 |
|
|
113
|
+
| Scenario 2: Adversarial Top-K Planted Lure | 0.79 / 1.27 | 0.72 / 1.45 |
|
|
114
|
+
| Scenario 3: Tool-Argument `user_id` Override | 0.83 / 1.35 | 0.84 / 1.42 |
|
|
115
|
+
| Scenario 4: Low-Clearance Swarm Agent (AgentLeak-style) | 0.80 / 1.24 | 0.91 / 1.60 |
|
|
116
|
+
| Scenario 5: Total Filter Omission | 0.72 / 1.22 | 0.73 / 1.22 |
|
|
117
|
+
| Control: Correct App Filter (no bug) | 0.76 / 1.53 | 0.78 / 1.39 |
|
|
118
|
+
|
|
119
|
+
**How to read this**
|
|
120
|
+
|
|
121
|
+
- **Leak rate is saturated by design of fixed top-k.** With no similarity floor, `LIMIT 3` always fills its slots. When a caller has fewer than three relevant rows of their own, a buggy filter fills the remainder with other people's rows, so every buggy query leaked at least one row. The *leaked share* and *rank-1* columns show how much of the retrieved context was unauthorized.
|
|
122
|
+
- **RLS removed every unauthorized row in every scenario**, while the identical buggy SQL leaked on the plain table. The control row confirms the leak classifier reports 0% when the application filter is correct.
|
|
123
|
+
- **Planted lures hijack rank 1, not recall.** Each Scenario 2 lure restates the target question followed by a short malicious payload (a white-box, PoisonedRAG-style attacker who knows the query wording). On the plain table a lure took rank 1 in 58.3% of queries: every roadmap/SLA query, but only 1 of 3 vendor queries and none of the API/KMS queries, where the victim's own note already restates the question almost verbatim. With RLS the lures are never retrieved.
|
|
124
|
+
- **Recall gains are modest and specific.** In Scenarios 1, 2 and 4 the caller's own answer still made the top 3 on the plain table, so RLS changed *what else* was in context (and what ranked first) rather than recall. The recall gain appears under total filter omission (72.7% → 100%), where cross-tenant near-duplicates and lures crowd out the caller's own memories.
|
|
125
|
+
- **Scenario 3 has no authorized answer.** The queries are pure exfiltration attempts, so recall is n/a. RLS turns the attack into an empty or own-rows-only result; it cannot repair the application's wrong `user_id` argument.
|
|
126
|
+
- **Latency.** At 60 rows the RLS overhead is within run-to-run noise. This benchmark does not measure ANN index behaviour at scale (see Limitations).
|
|
127
|
+
- The corpus and queries are synthetic and hand-written. Treat the numbers as a reproducible illustration of failure modes, not as an estimate of real-world leak rates.
|
|
128
|
+
|
|
129
|
+
---
|
|
130
|
+
|
|
131
|
+
## Threat model & limitations
|
|
132
|
+
|
|
133
|
+
- **What RLS protects against:** bugs and omissions in application retrieval SQL, prompt-injected tool arguments, and cross-user writes, all *while the service binds the correct identity*.
|
|
134
|
+
- **What it does not protect against:** a compromised application process. `memshield_app` can call `set_config` itself, so code holding the database credentials can claim any identity. Keep identity binding inside this service and keep credentials out of agent-reachable code paths.
|
|
135
|
+
- **Tenant and clearance come from service config, not from the ADK session.** `search_memory` receives only `app_name`/`user_id` from ADK, so run one service instance per tenant/clearance tier (or per Runner).
|
|
136
|
+
- **`tenant_shared` content is trusted by design.** A user may publish a `tenant_shared` memory at or below their own clearance, and every agent in the tenant with sufficient clearance can retrieve it. RLS enforces *who may read*, not whether the content is benign.
|
|
137
|
+
- **ANN indexes and RLS.** The schema ships without a vector index. If you add HNSW/IVFFlat, RLS filters rows *after* the index scan and can return fewer than `top_k` rows. Use pgvector ≥ 0.8 iterative index scans (`SET hnsw.iterative_scan = relaxed_order`) and benchmark recall at your scale.
|
|
138
|
+
- `sql/02_benchmark_baseline.sql` creates an intentionally unprotected table for tests and benchmarks. **Do not apply it in production.**
|
|
139
|
+
|
|
140
|
+
---
|
|
141
|
+
|
|
142
|
+
## Installation
|
|
143
|
+
|
|
144
|
+
```bash
|
|
145
|
+
pip install adk-memshield
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
From source, for development:
|
|
149
|
+
|
|
150
|
+
```bash
|
|
151
|
+
pip install -e ".[dev]"
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
---
|
|
155
|
+
|
|
156
|
+
## Quickstart
|
|
157
|
+
|
|
158
|
+
### 1. Apply the schema
|
|
159
|
+
|
|
160
|
+
Apply [`sql/01_schema.sql`](./sql/01_schema.sql) as a superuser/owner, then rotate the `memshield_app` password. The file also ships inside the wheel:
|
|
161
|
+
|
|
162
|
+
```python
|
|
163
|
+
from importlib.resources import files
|
|
164
|
+
|
|
165
|
+
schema_sql = (files("adk_memshield") / "sql" / "01_schema.sql").read_text()
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
For local development, start the bundled Postgres on port `54329`:
|
|
169
|
+
|
|
170
|
+
```bash
|
|
171
|
+
docker compose -p adk-memshield up -d db
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
### 2. Wire it into an ADK `Runner`
|
|
175
|
+
|
|
176
|
+
```python
|
|
177
|
+
from google.adk.agents.llm_agent import LlmAgent
|
|
178
|
+
from google.adk.runners import Runner
|
|
179
|
+
from google.adk.sessions.in_memory_session_service import InMemorySessionService
|
|
180
|
+
from google.adk.tools.load_memory_tool import load_memory_tool
|
|
181
|
+
from google.adk.tools.preload_memory_tool import preload_memory_tool
|
|
182
|
+
|
|
183
|
+
from adk_memshield import MemShieldConfig, MemShieldMemoryService
|
|
184
|
+
|
|
185
|
+
memory_service = MemShieldMemoryService(
|
|
186
|
+
MemShieldConfig(
|
|
187
|
+
dsn="postgresql://memshield_app:memshield_pass@localhost:54329/memshield",
|
|
188
|
+
tenant_id="tenant_alpha",
|
|
189
|
+
agent_clearance=2,
|
|
190
|
+
)
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
runner = Runner(
|
|
194
|
+
app_name="finance_copilot",
|
|
195
|
+
agent=LlmAgent(
|
|
196
|
+
name="assistant",
|
|
197
|
+
model="gemini-2.5-flash",
|
|
198
|
+
tools=[preload_memory_tool, load_memory_tool],
|
|
199
|
+
),
|
|
200
|
+
session_service=InMemorySessionService(),
|
|
201
|
+
memory_service=memory_service,
|
|
202
|
+
)
|
|
203
|
+
# ADK's memory tools call memory_service.search_memory(app_name=..., user_id=...) with the
|
|
204
|
+
# Runner's authenticated identity; persist a finished session with:
|
|
205
|
+
# await memory_service.add_session_to_memory(session)
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
### 3. Write and search memories directly
|
|
209
|
+
|
|
210
|
+
```python
|
|
211
|
+
from google.adk.memory.memory_entry import MemoryEntry
|
|
212
|
+
from google.genai import types
|
|
213
|
+
|
|
214
|
+
await memory_service.add_memory(
|
|
215
|
+
app_name="finance_copilot",
|
|
216
|
+
user_id="alice",
|
|
217
|
+
memories=[
|
|
218
|
+
MemoryEntry(
|
|
219
|
+
content=types.Content(parts=[types.Part(text="Wire routing code is SWIFT-ALPHA-99.")]),
|
|
220
|
+
custom_metadata={"scope": "private"},
|
|
221
|
+
),
|
|
222
|
+
# Visible to tenant agents with clearance >= 2 (the writer's clearance must be >= 2).
|
|
223
|
+
MemoryEntry(
|
|
224
|
+
content=types.Content(parts=[types.Part(text="Treasury approval threshold is $250k.")]),
|
|
225
|
+
custom_metadata={"scope": "tenant_shared", "min_clearance": 2},
|
|
226
|
+
),
|
|
227
|
+
],
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
response = await memory_service.search_memory(
|
|
231
|
+
app_name="finance_copilot", user_id="alice", query="What is my wire routing code?"
|
|
232
|
+
)
|
|
233
|
+
for entry in response.memories:
|
|
234
|
+
print(entry.content.parts[0].text, entry.custom_metadata["similarity"])
|
|
235
|
+
|
|
236
|
+
print(memory_service.last_query_telemetry.to_dict()) # SQL, identity context, latency, rows
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
### 4. Run custom SQL under the caller's RLS identity
|
|
240
|
+
|
|
241
|
+
```python
|
|
242
|
+
with memory_service.rls_transaction(app_name="finance_copilot", user_id="alice") as cur:
|
|
243
|
+
cur.execute("SELECT content FROM memories ORDER BY created_at DESC LIMIT 10")
|
|
244
|
+
rows = cur.fetchall() # only rows alice may read, even though the SQL has no WHERE clause
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
### 5. `memshield://` URI for the ADK service registry
|
|
248
|
+
|
|
249
|
+
```python
|
|
250
|
+
from adk_memshield import register_adk_uri
|
|
251
|
+
from google.adk.cli.service_registry import get_service_registry
|
|
252
|
+
|
|
253
|
+
register_adk_uri("memshield")
|
|
254
|
+
memory_service = get_service_registry().create_memory_service(
|
|
255
|
+
"memshield://memshield_app:memshield_pass@localhost:54329/memshield?tenant_id=tenant_alpha&agent_clearance=2"
|
|
256
|
+
)
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
---
|
|
260
|
+
|
|
261
|
+
## Reproducing tests & benchmarks
|
|
262
|
+
|
|
263
|
+
All containers use compose project `adk-memshield` and host port `54329`:
|
|
264
|
+
|
|
265
|
+
```bash
|
|
266
|
+
# 1. Start pgvector:pg16 (applies sql/01_schema.sql and sql/02_benchmark_baseline.sql on first start)
|
|
267
|
+
docker compose -p adk-memshield up -d db
|
|
268
|
+
|
|
269
|
+
# 2. Run the 8 integration tests, including a real ADK Runner + preload_memory/load_memory test
|
|
270
|
+
docker compose -p adk-memshield run --rm test pytest -v
|
|
271
|
+
|
|
272
|
+
# 3. Run the benchmark
|
|
273
|
+
docker compose -p adk-memshield run --rm test python benchmarks/run_memleak_eval.py
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
---
|
|
277
|
+
|
|
278
|
+
## License
|
|
279
|
+
|
|
280
|
+
Apache License 2.0 — see [`LICENSE`](./LICENSE).
|