adk-memshield 0.1.0__py3-none-any.whl
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/__init__.py +16 -0
- adk_memshield/config.py +62 -0
- adk_memshield/embedder.py +65 -0
- adk_memshield/service.py +598 -0
- adk_memshield/sql/01_schema.sql +118 -0
- adk_memshield-0.1.0.dist-info/METADATA +280 -0
- adk_memshield-0.1.0.dist-info/RECORD +9 -0
- adk_memshield-0.1.0.dist-info/WHEEL +4 -0
- adk_memshield-0.1.0.dist-info/licenses/LICENSE +176 -0
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""adk-memshield: Zero-trust multi-tenant semantic memory service for Google ADK."""
|
|
2
|
+
|
|
3
|
+
from .config import MemShieldConfig
|
|
4
|
+
from .embedder import EmbedFn, MemShieldEmbedder
|
|
5
|
+
from .service import MemShieldMemoryService, QueryTelemetry, register_adk_uri
|
|
6
|
+
|
|
7
|
+
__version__ = "0.1.0"
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"EmbedFn",
|
|
11
|
+
"MemShieldConfig",
|
|
12
|
+
"MemShieldEmbedder",
|
|
13
|
+
"MemShieldMemoryService",
|
|
14
|
+
"QueryTelemetry",
|
|
15
|
+
"register_adk_uri",
|
|
16
|
+
]
|
adk_memshield/config.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Configuration models for adk-memshield."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
from typing import Literal
|
|
8
|
+
|
|
9
|
+
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
|
10
|
+
|
|
11
|
+
_SAFE_IDENTIFIER_RE = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class MemShieldConfig(BaseModel):
|
|
15
|
+
"""Configuration for MemShieldMemoryService.
|
|
16
|
+
|
|
17
|
+
Attributes:
|
|
18
|
+
dsn: PostgreSQL connection URI using a non-superuser role (e.g. memshield_app)
|
|
19
|
+
so PostgreSQL Row-Level Security (RLS) policies are strictly enforced.
|
|
20
|
+
tenant_id: Active tenant identifier bound to transaction-local context
|
|
21
|
+
(`app.current_tenant_id`).
|
|
22
|
+
agent_clearance: Clearance level (1..5) of the active agent/caller bound to
|
|
23
|
+
transaction-local context (`app.agent_clearance`).
|
|
24
|
+
default_scope: Default visibility scope for newly stored memories
|
|
25
|
+
(`'private'` or `'tenant_shared'`).
|
|
26
|
+
default_min_clearance: Default minimum clearance level (1..5) required to
|
|
27
|
+
read `'tenant_shared'` memories.
|
|
28
|
+
top_k: Maximum number of memories returned by `search_memory`.
|
|
29
|
+
min_similarity: Optional minimum cosine similarity threshold for retrieval.
|
|
30
|
+
embedding_model: FastEmbed ONNX model identifier.
|
|
31
|
+
embedding_dim: Expected embedding vector dimensionality.
|
|
32
|
+
table_name: Target PostgreSQL table name (`'memories'` by default).
|
|
33
|
+
simulate_missing_app_filter: Chaos/testing flag. When True, omits application-layer
|
|
34
|
+
SQL `WHERE` clauses during `search_memory` to verify that PostgreSQL RLS
|
|
35
|
+
independently prevents cross-tenant and cross-user leakage.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
model_config = ConfigDict(validate_assignment=True, extra="forbid")
|
|
39
|
+
|
|
40
|
+
dsn: str = Field(
|
|
41
|
+
default_factory=lambda: os.environ.get(
|
|
42
|
+
"MEMSHIELD_DB_DSN",
|
|
43
|
+
"postgresql://memshield_app:memshield_pass@localhost:54329/memshield",
|
|
44
|
+
)
|
|
45
|
+
)
|
|
46
|
+
tenant_id: str = Field(default="default", min_length=1)
|
|
47
|
+
agent_clearance: int = Field(default=1, ge=1, le=5)
|
|
48
|
+
default_scope: Literal["private", "tenant_shared"] = Field(default="private")
|
|
49
|
+
default_min_clearance: int = Field(default=1, ge=1, le=5)
|
|
50
|
+
top_k: int = Field(default=5, ge=1, le=100)
|
|
51
|
+
min_similarity: float | None = Field(default=None, ge=-1.0, le=1.0)
|
|
52
|
+
embedding_model: str = Field(default="BAAI/bge-small-en-v1.5")
|
|
53
|
+
embedding_dim: int = Field(default=384, ge=1)
|
|
54
|
+
table_name: str = Field(default="memories")
|
|
55
|
+
simulate_missing_app_filter: bool = Field(default=False)
|
|
56
|
+
|
|
57
|
+
@field_validator("table_name")
|
|
58
|
+
@classmethod
|
|
59
|
+
def _validate_table_name(cls, value: str) -> str:
|
|
60
|
+
if not _SAFE_IDENTIFIER_RE.match(value):
|
|
61
|
+
raise ValueError(f"Unsafe SQL table identifier: {value!r}")
|
|
62
|
+
return value
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""FastEmbed ONNX embedding wrapper with custom callable override support."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import threading
|
|
6
|
+
from collections.abc import Callable, Sequence
|
|
7
|
+
from typing import TYPE_CHECKING
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from fastembed import TextEmbedding
|
|
11
|
+
|
|
12
|
+
EmbedFn = Callable[[Sequence[str]], list[list[float]]]
|
|
13
|
+
|
|
14
|
+
_MODEL_CACHE: dict[str, TextEmbedding] = {}
|
|
15
|
+
_MODEL_CACHE_LOCK = threading.Lock()
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _get_fastembed_model(model_name: str) -> TextEmbedding:
|
|
19
|
+
"""Return a process-cached FastEmbed TextEmbedding instance."""
|
|
20
|
+
with _MODEL_CACHE_LOCK:
|
|
21
|
+
if model_name not in _MODEL_CACHE:
|
|
22
|
+
from fastembed import TextEmbedding
|
|
23
|
+
|
|
24
|
+
_MODEL_CACHE[model_name] = TextEmbedding(model_name=model_name)
|
|
25
|
+
return _MODEL_CACHE[model_name]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class MemShieldEmbedder:
|
|
29
|
+
"""Embeds text strings into normalized float vectors for pgvector storage and search.
|
|
30
|
+
|
|
31
|
+
Defaults to `fastembed` (`BAAI/bge-small-en-v1.5`, 384 dimensions) via ONNX Runtime,
|
|
32
|
+
or delegates to a user-supplied `embed_fn`.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
def __init__(
|
|
36
|
+
self,
|
|
37
|
+
model_name: str = "BAAI/bge-small-en-v1.5",
|
|
38
|
+
expected_dim: int = 384,
|
|
39
|
+
embed_fn: EmbedFn | None = None,
|
|
40
|
+
) -> None:
|
|
41
|
+
self.model_name = model_name
|
|
42
|
+
self.expected_dim = expected_dim
|
|
43
|
+
self._embed_fn = embed_fn
|
|
44
|
+
|
|
45
|
+
def embed_documents(self, texts: Sequence[str]) -> list[list[float]]:
|
|
46
|
+
"""Embed a batch of document/memory strings into float lists."""
|
|
47
|
+
if not texts:
|
|
48
|
+
return []
|
|
49
|
+
if self._embed_fn is not None:
|
|
50
|
+
vectors = [list(map(float, vec)) for vec in self._embed_fn(texts)]
|
|
51
|
+
else:
|
|
52
|
+
model = _get_fastembed_model(self.model_name)
|
|
53
|
+
vectors = [[float(x) for x in vec.tolist()] for vec in model.embed(list(texts))]
|
|
54
|
+
|
|
55
|
+
for vec in vectors:
|
|
56
|
+
if len(vec) != self.expected_dim:
|
|
57
|
+
raise ValueError(
|
|
58
|
+
f"Embedding dimension mismatch: expected {self.expected_dim}, got {len(vec)}"
|
|
59
|
+
)
|
|
60
|
+
return vectors
|
|
61
|
+
|
|
62
|
+
def embed_query(self, query: str) -> list[float]:
|
|
63
|
+
"""Embed a single search query string into a float list."""
|
|
64
|
+
vectors = self.embed_documents([query])
|
|
65
|
+
return vectors[0]
|
adk_memshield/service.py
ADDED
|
@@ -0,0 +1,598 @@
|
|
|
1
|
+
"""Google ADK BaseMemoryService implementation backed by PostgreSQL pgvector + RLS."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
import time
|
|
8
|
+
from collections.abc import Iterator, Mapping, Sequence
|
|
9
|
+
from contextlib import contextmanager
|
|
10
|
+
from dataclasses import asdict, dataclass
|
|
11
|
+
from typing import Any, Literal
|
|
12
|
+
from urllib.parse import parse_qs, urlencode, urlparse, urlunparse
|
|
13
|
+
|
|
14
|
+
import psycopg
|
|
15
|
+
from google.adk.events.event import Event
|
|
16
|
+
from google.adk.memory.base_memory_service import BaseMemoryService, SearchMemoryResponse
|
|
17
|
+
from google.adk.memory.memory_entry import MemoryEntry
|
|
18
|
+
from google.adk.sessions.session import Session
|
|
19
|
+
from google.genai import types
|
|
20
|
+
from psycopg_pool import ConnectionPool
|
|
21
|
+
|
|
22
|
+
from .config import MemShieldConfig
|
|
23
|
+
from .embedder import EmbedFn, MemShieldEmbedder
|
|
24
|
+
|
|
25
|
+
_SHARED_POOLS: dict[str, ConnectionPool] = {}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _get_shared_pool(dsn: str) -> ConnectionPool:
|
|
29
|
+
"""Return a process-shared ConnectionPool keyed by PostgreSQL DSN."""
|
|
30
|
+
pool = _SHARED_POOLS.get(dsn)
|
|
31
|
+
if pool is None or pool.closed:
|
|
32
|
+
pool = ConnectionPool(conninfo=dsn, min_size=1, max_size=8, open=True)
|
|
33
|
+
_SHARED_POOLS[dsn] = pool
|
|
34
|
+
return pool
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _format_vector(vec: Sequence[float]) -> str:
|
|
38
|
+
"""Serialize a float sequence as a pgvector literal string."""
|
|
39
|
+
return "[" + ",".join(f"{float(x):.8f}" for x in vec) + "]"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _extract_text_from_content(content: types.Content | None) -> str:
|
|
43
|
+
"""Extract concatenated non-empty text parts from a google.genai Content object."""
|
|
44
|
+
if content is None or not content.parts:
|
|
45
|
+
return ""
|
|
46
|
+
texts: list[str] = []
|
|
47
|
+
for part in content.parts:
|
|
48
|
+
if getattr(part, "text", None):
|
|
49
|
+
stripped = part.text.strip()
|
|
50
|
+
if stripped:
|
|
51
|
+
texts.append(stripped)
|
|
52
|
+
return "\n".join(texts)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _require_identity(app_name: str, user_id: str) -> None:
|
|
56
|
+
"""Reject empty identities before they reach the database (fail closed)."""
|
|
57
|
+
if not app_name or not str(app_name).strip():
|
|
58
|
+
raise ValueError("app_name must be a non-empty string")
|
|
59
|
+
if not user_id or not str(user_id).strip():
|
|
60
|
+
raise ValueError("user_id must be a non-empty string")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _parse_memshield_uri(uri: str) -> tuple[str, dict[str, Any]]:
|
|
64
|
+
"""Parse a memshield:// or postgresql:// URI into (postgres_dsn, config_overrides)."""
|
|
65
|
+
parsed = urlparse(uri)
|
|
66
|
+
query_params = parse_qs(parsed.query)
|
|
67
|
+
overrides: dict[str, Any] = {}
|
|
68
|
+
|
|
69
|
+
if "tenant_id" in query_params:
|
|
70
|
+
overrides["tenant_id"] = query_params.pop("tenant_id")[0]
|
|
71
|
+
if "agent_clearance" in query_params:
|
|
72
|
+
overrides["agent_clearance"] = int(query_params.pop("agent_clearance")[0])
|
|
73
|
+
if "default_scope" in query_params:
|
|
74
|
+
overrides["default_scope"] = query_params.pop("default_scope")[0]
|
|
75
|
+
if "default_min_clearance" in query_params:
|
|
76
|
+
overrides["default_min_clearance"] = int(query_params.pop("default_min_clearance")[0])
|
|
77
|
+
if "top_k" in query_params:
|
|
78
|
+
overrides["top_k"] = int(query_params.pop("top_k")[0])
|
|
79
|
+
if "table_name" in query_params:
|
|
80
|
+
overrides["table_name"] = query_params.pop("table_name")[0]
|
|
81
|
+
if "simulate_missing_app_filter" in query_params:
|
|
82
|
+
val = query_params.pop("simulate_missing_app_filter")[0].lower()
|
|
83
|
+
overrides["simulate_missing_app_filter"] = val in ("1", "true", "yes")
|
|
84
|
+
|
|
85
|
+
remaining_query = urlencode(query_params, doseq=True)
|
|
86
|
+
dsn = urlunparse(
|
|
87
|
+
(
|
|
88
|
+
"postgresql",
|
|
89
|
+
parsed.netloc,
|
|
90
|
+
parsed.path,
|
|
91
|
+
parsed.params,
|
|
92
|
+
remaining_query,
|
|
93
|
+
parsed.fragment,
|
|
94
|
+
)
|
|
95
|
+
)
|
|
96
|
+
return dsn, overrides
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@dataclass
|
|
100
|
+
class QueryTelemetry(Mapping[str, Any]):
|
|
101
|
+
"""Telemetry snapshot recorded on `MemShieldMemoryService.last_query_telemetry`.
|
|
102
|
+
|
|
103
|
+
Supports both attribute access (`telemetry.latency_ms`) and dictionary access
|
|
104
|
+
(`telemetry["latency_ms"]`).
|
|
105
|
+
"""
|
|
106
|
+
|
|
107
|
+
operation: str
|
|
108
|
+
sql: str
|
|
109
|
+
session_context: dict[str, str]
|
|
110
|
+
latency_ms: float
|
|
111
|
+
row_count: int
|
|
112
|
+
simulate_missing_app_filter: bool
|
|
113
|
+
table_name: str
|
|
114
|
+
|
|
115
|
+
def to_dict(self) -> dict[str, Any]:
|
|
116
|
+
return asdict(self)
|
|
117
|
+
|
|
118
|
+
def __getitem__(self, key: str) -> Any:
|
|
119
|
+
return asdict(self)[key]
|
|
120
|
+
|
|
121
|
+
def __iter__(self) -> Iterator[str]:
|
|
122
|
+
return iter(asdict(self))
|
|
123
|
+
|
|
124
|
+
def __len__(self) -> int:
|
|
125
|
+
return len(asdict(self))
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class MemShieldMemoryService(BaseMemoryService):
|
|
129
|
+
"""Zero-trust multi-tenant semantic memory service for Google ADK.
|
|
130
|
+
|
|
131
|
+
Enforces tenant, user, and multi-agent clearance boundaries at the PostgreSQL
|
|
132
|
+
kernel level using Row-Level Security (RLS) and transaction-local `set_config`.
|
|
133
|
+
|
|
134
|
+
Blocking work (ONNX embedding and psycopg I/O) runs in a worker thread via
|
|
135
|
+
`asyncio.to_thread`, so the ADK event loop is never stalled by memory calls.
|
|
136
|
+
"""
|
|
137
|
+
|
|
138
|
+
def __init__(
|
|
139
|
+
self,
|
|
140
|
+
config: MemShieldConfig | None = None,
|
|
141
|
+
*,
|
|
142
|
+
dsn: str | None = None,
|
|
143
|
+
uri: str | None = None,
|
|
144
|
+
tenant_id: str | None = None,
|
|
145
|
+
agent_clearance: int | None = None,
|
|
146
|
+
default_scope: Literal["private", "tenant_shared"] | None = None,
|
|
147
|
+
default_min_clearance: int | None = None,
|
|
148
|
+
top_k: int | None = None,
|
|
149
|
+
min_similarity: float | None = None,
|
|
150
|
+
embedding_model: str | None = None,
|
|
151
|
+
embedding_dim: int | None = None,
|
|
152
|
+
table_name: str | None = None,
|
|
153
|
+
simulate_missing_app_filter: bool | None = None,
|
|
154
|
+
embed_fn: EmbedFn | None = None,
|
|
155
|
+
pool: ConnectionPool | None = None,
|
|
156
|
+
) -> None:
|
|
157
|
+
cfg_data: dict[str, Any] = config.model_dump() if config is not None else {}
|
|
158
|
+
|
|
159
|
+
if uri is not None:
|
|
160
|
+
parsed_dsn, uri_overrides = _parse_memshield_uri(uri)
|
|
161
|
+
cfg_data["dsn"] = parsed_dsn
|
|
162
|
+
cfg_data.update(uri_overrides)
|
|
163
|
+
|
|
164
|
+
explicit_overrides = {
|
|
165
|
+
"dsn": dsn,
|
|
166
|
+
"tenant_id": tenant_id,
|
|
167
|
+
"agent_clearance": agent_clearance,
|
|
168
|
+
"default_scope": default_scope,
|
|
169
|
+
"default_min_clearance": default_min_clearance,
|
|
170
|
+
"top_k": top_k,
|
|
171
|
+
"min_similarity": min_similarity,
|
|
172
|
+
"embedding_model": embedding_model,
|
|
173
|
+
"embedding_dim": embedding_dim,
|
|
174
|
+
"table_name": table_name,
|
|
175
|
+
"simulate_missing_app_filter": simulate_missing_app_filter,
|
|
176
|
+
}
|
|
177
|
+
for key, value in explicit_overrides.items():
|
|
178
|
+
if value is not None:
|
|
179
|
+
cfg_data[key] = value
|
|
180
|
+
|
|
181
|
+
self.config = MemShieldConfig(**cfg_data)
|
|
182
|
+
self.embedder = MemShieldEmbedder(
|
|
183
|
+
model_name=self.config.embedding_model,
|
|
184
|
+
expected_dim=self.config.embedding_dim,
|
|
185
|
+
embed_fn=embed_fn,
|
|
186
|
+
)
|
|
187
|
+
self._pool = pool if pool is not None else _get_shared_pool(self.config.dsn)
|
|
188
|
+
self.last_query_telemetry: QueryTelemetry | None = None
|
|
189
|
+
|
|
190
|
+
def _rls_context(self, *, app_name: str, user_id: str) -> dict[str, str]:
|
|
191
|
+
return {
|
|
192
|
+
"app.current_app_name": str(app_name),
|
|
193
|
+
"app.current_tenant_id": str(self.config.tenant_id),
|
|
194
|
+
"app.current_user_id": str(user_id),
|
|
195
|
+
"app.agent_clearance": str(self.config.agent_clearance),
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
@contextmanager
|
|
199
|
+
def rls_transaction(
|
|
200
|
+
self,
|
|
201
|
+
*,
|
|
202
|
+
app_name: str,
|
|
203
|
+
user_id: str,
|
|
204
|
+
) -> Iterator[psycopg.Cursor[Any]]:
|
|
205
|
+
"""Yield a cursor inside an explicit transaction bound to the caller's RLS identity.
|
|
206
|
+
|
|
207
|
+
Identity is bound with `set_config(..., is_local => true)`, so it is discarded when
|
|
208
|
+
the transaction commits or rolls back and never bleeds into the next pooled
|
|
209
|
+
checkout. Any custom SQL executed on the yielded cursor is subject to the RLS
|
|
210
|
+
policies on `memories`, even if that SQL omits its own ownership filters.
|
|
211
|
+
"""
|
|
212
|
+
_require_identity(app_name, user_id)
|
|
213
|
+
context = self._rls_context(app_name=app_name, user_id=user_id)
|
|
214
|
+
with self._pool.connection() as conn:
|
|
215
|
+
with conn.transaction():
|
|
216
|
+
with conn.cursor() as cur:
|
|
217
|
+
cur.execute(
|
|
218
|
+
"""
|
|
219
|
+
SELECT
|
|
220
|
+
set_config('app.current_app_name', %s, true),
|
|
221
|
+
set_config('app.current_tenant_id', %s, true),
|
|
222
|
+
set_config('app.current_user_id', %s, true),
|
|
223
|
+
set_config('app.agent_clearance', %s, true);
|
|
224
|
+
""",
|
|
225
|
+
(
|
|
226
|
+
context["app.current_app_name"],
|
|
227
|
+
context["app.current_tenant_id"],
|
|
228
|
+
context["app.current_user_id"],
|
|
229
|
+
context["app.agent_clearance"],
|
|
230
|
+
),
|
|
231
|
+
)
|
|
232
|
+
yield cur
|
|
233
|
+
|
|
234
|
+
async def add_session_to_memory(self, session: Session) -> None:
|
|
235
|
+
"""Extract non-empty text parts from `session.events`, embed, and insert with RLS.
|
|
236
|
+
|
|
237
|
+
Idempotent per event: ADK may add the same session several times during its
|
|
238
|
+
lifetime, and previously stored `(session_id, event_id)` pairs are skipped.
|
|
239
|
+
"""
|
|
240
|
+
session_meta: dict[str, Any] = {}
|
|
241
|
+
if session.state:
|
|
242
|
+
if "scope" in session.state:
|
|
243
|
+
session_meta["scope"] = session.state["scope"]
|
|
244
|
+
if "min_clearance" in session.state:
|
|
245
|
+
session_meta["min_clearance"] = session.state["min_clearance"]
|
|
246
|
+
|
|
247
|
+
await self.add_events_to_memory(
|
|
248
|
+
app_name=session.app_name,
|
|
249
|
+
user_id=session.user_id,
|
|
250
|
+
events=session.events,
|
|
251
|
+
session_id=session.id,
|
|
252
|
+
custom_metadata=session_meta or None,
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
async def add_events_to_memory(
|
|
256
|
+
self,
|
|
257
|
+
*,
|
|
258
|
+
app_name: str,
|
|
259
|
+
user_id: str,
|
|
260
|
+
events: Sequence[Event],
|
|
261
|
+
session_id: str | None = None,
|
|
262
|
+
custom_metadata: Mapping[str, object] | None = None,
|
|
263
|
+
) -> None:
|
|
264
|
+
"""Append incremental ADK events into RLS-protected semantic memory."""
|
|
265
|
+
base_meta = dict(custom_metadata) if custom_metadata else {}
|
|
266
|
+
entries: list[MemoryEntry] = []
|
|
267
|
+
|
|
268
|
+
for event in events:
|
|
269
|
+
text = _extract_text_from_content(event.content)
|
|
270
|
+
if not text:
|
|
271
|
+
continue
|
|
272
|
+
author = event.author or (
|
|
273
|
+
event.content.role if event.content and event.content.role else "user"
|
|
274
|
+
)
|
|
275
|
+
ev_meta = dict(base_meta)
|
|
276
|
+
if session_id is not None:
|
|
277
|
+
ev_meta.setdefault("session_id", session_id)
|
|
278
|
+
if event.id:
|
|
279
|
+
ev_meta.setdefault("event_id", event.id)
|
|
280
|
+
|
|
281
|
+
entries.append(
|
|
282
|
+
MemoryEntry(
|
|
283
|
+
content=types.Content(
|
|
284
|
+
parts=[types.Part(text=text)],
|
|
285
|
+
role=author,
|
|
286
|
+
),
|
|
287
|
+
author=author,
|
|
288
|
+
custom_metadata=ev_meta,
|
|
289
|
+
)
|
|
290
|
+
)
|
|
291
|
+
|
|
292
|
+
if not entries:
|
|
293
|
+
return
|
|
294
|
+
|
|
295
|
+
await self.add_memory(
|
|
296
|
+
app_name=app_name,
|
|
297
|
+
user_id=user_id,
|
|
298
|
+
memories=entries,
|
|
299
|
+
custom_metadata=base_meta,
|
|
300
|
+
)
|
|
301
|
+
|
|
302
|
+
async def add_memory(
|
|
303
|
+
self,
|
|
304
|
+
*,
|
|
305
|
+
app_name: str,
|
|
306
|
+
user_id: str,
|
|
307
|
+
memories: Sequence[MemoryEntry],
|
|
308
|
+
custom_metadata: Mapping[str, object] | None = None,
|
|
309
|
+
) -> None:
|
|
310
|
+
"""Directly ingest `MemoryEntry` items into RLS-protected PostgreSQL storage."""
|
|
311
|
+
_require_identity(app_name, user_id)
|
|
312
|
+
await asyncio.to_thread(
|
|
313
|
+
self._add_memory_sync,
|
|
314
|
+
app_name=app_name,
|
|
315
|
+
user_id=user_id,
|
|
316
|
+
memories=memories,
|
|
317
|
+
custom_metadata=custom_metadata,
|
|
318
|
+
)
|
|
319
|
+
|
|
320
|
+
def _add_memory_sync(
|
|
321
|
+
self,
|
|
322
|
+
*,
|
|
323
|
+
app_name: str,
|
|
324
|
+
user_id: str,
|
|
325
|
+
memories: Sequence[MemoryEntry],
|
|
326
|
+
custom_metadata: Mapping[str, object] | None,
|
|
327
|
+
) -> None:
|
|
328
|
+
base_meta = dict(custom_metadata) if custom_metadata else {}
|
|
329
|
+
prepared: list[tuple[MemoryEntry, str, str, str, int, str | None, dict[str, Any]]] = []
|
|
330
|
+
|
|
331
|
+
for entry in memories:
|
|
332
|
+
text = _extract_text_from_content(entry.content)
|
|
333
|
+
if not text:
|
|
334
|
+
continue
|
|
335
|
+
merged_meta = {**base_meta, **(entry.custom_metadata or {})}
|
|
336
|
+
scope = str(merged_meta.pop("scope", self.config.default_scope))
|
|
337
|
+
min_clearance = int(
|
|
338
|
+
merged_meta.pop("min_clearance", self.config.default_min_clearance)
|
|
339
|
+
)
|
|
340
|
+
session_id = merged_meta.pop("session_id", None)
|
|
341
|
+
author = entry.author or (
|
|
342
|
+
entry.content.role if entry.content and entry.content.role else "user"
|
|
343
|
+
)
|
|
344
|
+
prepared.append(
|
|
345
|
+
(entry, text, author, scope, min_clearance, session_id, merged_meta)
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
if not prepared:
|
|
349
|
+
return
|
|
350
|
+
|
|
351
|
+
texts = [item[1] for item in prepared]
|
|
352
|
+
embeddings = self.embedder.embed_documents(texts)
|
|
353
|
+
|
|
354
|
+
# Ownership columns always come from the authenticated call arguments and the
|
|
355
|
+
# service config, never from caller-supplied metadata.
|
|
356
|
+
table = self.config.table_name
|
|
357
|
+
insert_sql = f"""
|
|
358
|
+
INSERT INTO {table} (
|
|
359
|
+
app_name, tenant_id, user_id, session_id, author,
|
|
360
|
+
scope, min_clearance, content, custom_metadata, embedding
|
|
361
|
+
)
|
|
362
|
+
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s::jsonb, %s::vector)
|
|
363
|
+
ON CONFLICT (app_name, tenant_id, user_id, session_id, (custom_metadata->>'event_id'))
|
|
364
|
+
WHERE custom_metadata ? 'event_id'
|
|
365
|
+
DO NOTHING
|
|
366
|
+
RETURNING id
|
|
367
|
+
"""
|
|
368
|
+
|
|
369
|
+
t0 = time.perf_counter()
|
|
370
|
+
inserted_count = 0
|
|
371
|
+
with self.rls_transaction(app_name=app_name, user_id=user_id) as cur:
|
|
372
|
+
for (
|
|
373
|
+
entry,
|
|
374
|
+
text,
|
|
375
|
+
author,
|
|
376
|
+
scope,
|
|
377
|
+
min_clearance,
|
|
378
|
+
session_id,
|
|
379
|
+
meta,
|
|
380
|
+
), vec in zip(prepared, embeddings, strict=True):
|
|
381
|
+
cur.execute(
|
|
382
|
+
insert_sql,
|
|
383
|
+
(
|
|
384
|
+
app_name,
|
|
385
|
+
self.config.tenant_id,
|
|
386
|
+
user_id,
|
|
387
|
+
session_id,
|
|
388
|
+
author,
|
|
389
|
+
scope,
|
|
390
|
+
min_clearance,
|
|
391
|
+
text,
|
|
392
|
+
json.dumps(meta),
|
|
393
|
+
_format_vector(vec),
|
|
394
|
+
),
|
|
395
|
+
)
|
|
396
|
+
row = cur.fetchone()
|
|
397
|
+
if row is None:
|
|
398
|
+
continue # duplicate (session_id, event_id) already stored
|
|
399
|
+
if entry.id is None:
|
|
400
|
+
entry.id = str(row[0])
|
|
401
|
+
inserted_count += 1
|
|
402
|
+
|
|
403
|
+
latency_ms = (time.perf_counter() - t0) * 1000.0
|
|
404
|
+
self.last_query_telemetry = QueryTelemetry(
|
|
405
|
+
operation="add_memory",
|
|
406
|
+
sql=insert_sql.strip(),
|
|
407
|
+
session_context=self._rls_context(app_name=app_name, user_id=user_id),
|
|
408
|
+
latency_ms=latency_ms,
|
|
409
|
+
row_count=inserted_count,
|
|
410
|
+
simulate_missing_app_filter=self.config.simulate_missing_app_filter,
|
|
411
|
+
table_name=table,
|
|
412
|
+
)
|
|
413
|
+
|
|
414
|
+
async def search_memory(
|
|
415
|
+
self,
|
|
416
|
+
*,
|
|
417
|
+
app_name: str,
|
|
418
|
+
user_id: str,
|
|
419
|
+
query: str,
|
|
420
|
+
) -> SearchMemoryResponse:
|
|
421
|
+
"""Search semantic memories with transaction-local PostgreSQL RLS enforcement."""
|
|
422
|
+
_require_identity(app_name, user_id)
|
|
423
|
+
return await asyncio.to_thread(
|
|
424
|
+
self._search_memory_sync, app_name=app_name, user_id=user_id, query=query
|
|
425
|
+
)
|
|
426
|
+
|
|
427
|
+
def _search_memory_sync(
|
|
428
|
+
self,
|
|
429
|
+
*,
|
|
430
|
+
app_name: str,
|
|
431
|
+
user_id: str,
|
|
432
|
+
query: str,
|
|
433
|
+
) -> SearchMemoryResponse:
|
|
434
|
+
query_vec = self.embedder.embed_query(query)
|
|
435
|
+
vec_literal = _format_vector(query_vec)
|
|
436
|
+
table = self.config.table_name
|
|
437
|
+
|
|
438
|
+
if self.config.simulate_missing_app_filter:
|
|
439
|
+
sql = f"""
|
|
440
|
+
SELECT
|
|
441
|
+
id, app_name, tenant_id, user_id, session_id, author,
|
|
442
|
+
scope, min_clearance, content, custom_metadata, created_at,
|
|
443
|
+
1 - (embedding <=> %s::vector) AS similarity
|
|
444
|
+
FROM {table}
|
|
445
|
+
ORDER BY embedding <=> %s::vector
|
|
446
|
+
LIMIT %s
|
|
447
|
+
"""
|
|
448
|
+
params: tuple[Any, ...] = (vec_literal, vec_literal, self.config.top_k)
|
|
449
|
+
else:
|
|
450
|
+
# Defense in depth: the application-layer filter mirrors the RLS SELECT
|
|
451
|
+
# policy, so neither layer alone is a single point of failure.
|
|
452
|
+
sql = f"""
|
|
453
|
+
SELECT
|
|
454
|
+
id, app_name, tenant_id, user_id, session_id, author,
|
|
455
|
+
scope, min_clearance, content, custom_metadata, created_at,
|
|
456
|
+
1 - (embedding <=> %s::vector) AS similarity
|
|
457
|
+
FROM {table}
|
|
458
|
+
WHERE app_name = %s AND tenant_id = %s
|
|
459
|
+
AND (user_id = %s OR (scope = 'tenant_shared' AND min_clearance <= %s))
|
|
460
|
+
ORDER BY embedding <=> %s::vector
|
|
461
|
+
LIMIT %s
|
|
462
|
+
"""
|
|
463
|
+
params = (
|
|
464
|
+
vec_literal,
|
|
465
|
+
app_name,
|
|
466
|
+
self.config.tenant_id,
|
|
467
|
+
user_id,
|
|
468
|
+
self.config.agent_clearance,
|
|
469
|
+
vec_literal,
|
|
470
|
+
self.config.top_k,
|
|
471
|
+
)
|
|
472
|
+
|
|
473
|
+
t0 = time.perf_counter()
|
|
474
|
+
with self.rls_transaction(app_name=app_name, user_id=user_id) as cur:
|
|
475
|
+
cur.execute(sql, params)
|
|
476
|
+
rows = cur.fetchall()
|
|
477
|
+
latency_ms = (time.perf_counter() - t0) * 1000.0
|
|
478
|
+
|
|
479
|
+
results: list[MemoryEntry] = []
|
|
480
|
+
for row in rows:
|
|
481
|
+
(
|
|
482
|
+
row_id,
|
|
483
|
+
row_app_name,
|
|
484
|
+
row_tenant_id,
|
|
485
|
+
row_user_id,
|
|
486
|
+
row_session_id,
|
|
487
|
+
row_author,
|
|
488
|
+
row_scope,
|
|
489
|
+
row_min_clearance,
|
|
490
|
+
row_content,
|
|
491
|
+
row_custom_meta,
|
|
492
|
+
row_created_at,
|
|
493
|
+
row_similarity,
|
|
494
|
+
) = row
|
|
495
|
+
|
|
496
|
+
similarity_val = float(row_similarity)
|
|
497
|
+
if (
|
|
498
|
+
self.config.min_similarity is not None
|
|
499
|
+
and similarity_val < self.config.min_similarity
|
|
500
|
+
):
|
|
501
|
+
continue
|
|
502
|
+
|
|
503
|
+
meta_dict: dict[str, Any] = (
|
|
504
|
+
dict(row_custom_meta) if isinstance(row_custom_meta, Mapping) else {}
|
|
505
|
+
)
|
|
506
|
+
meta_dict.update(
|
|
507
|
+
{
|
|
508
|
+
"app_name": row_app_name,
|
|
509
|
+
"tenant_id": row_tenant_id,
|
|
510
|
+
"user_id": row_user_id,
|
|
511
|
+
"session_id": row_session_id,
|
|
512
|
+
"scope": row_scope,
|
|
513
|
+
"min_clearance": int(row_min_clearance),
|
|
514
|
+
"similarity": similarity_val,
|
|
515
|
+
}
|
|
516
|
+
)
|
|
517
|
+
role = row_author or "user"
|
|
518
|
+
results.append(
|
|
519
|
+
MemoryEntry(
|
|
520
|
+
id=str(row_id),
|
|
521
|
+
content=types.Content(
|
|
522
|
+
parts=[types.Part(text=str(row_content))],
|
|
523
|
+
role=role,
|
|
524
|
+
),
|
|
525
|
+
author=role,
|
|
526
|
+
timestamp=row_created_at.isoformat() if row_created_at else None,
|
|
527
|
+
custom_metadata=meta_dict,
|
|
528
|
+
)
|
|
529
|
+
)
|
|
530
|
+
|
|
531
|
+
self.last_query_telemetry = QueryTelemetry(
|
|
532
|
+
operation="search_memory",
|
|
533
|
+
sql=sql.strip(),
|
|
534
|
+
session_context=self._rls_context(app_name=app_name, user_id=user_id),
|
|
535
|
+
latency_ms=latency_ms,
|
|
536
|
+
row_count=len(results),
|
|
537
|
+
simulate_missing_app_filter=self.config.simulate_missing_app_filter,
|
|
538
|
+
table_name=table,
|
|
539
|
+
)
|
|
540
|
+
return SearchMemoryResponse(memories=results)
|
|
541
|
+
|
|
542
|
+
async def delete_memory(
|
|
543
|
+
self,
|
|
544
|
+
*,
|
|
545
|
+
app_name: str,
|
|
546
|
+
user_id: str,
|
|
547
|
+
memory_id: str | None = None,
|
|
548
|
+
) -> None:
|
|
549
|
+
"""Delete a specific memory ID (or all caller-owned memories) under RLS."""
|
|
550
|
+
_require_identity(app_name, user_id)
|
|
551
|
+
await asyncio.to_thread(
|
|
552
|
+
self._delete_memory_sync, app_name=app_name, user_id=user_id, memory_id=memory_id
|
|
553
|
+
)
|
|
554
|
+
|
|
555
|
+
def _delete_memory_sync(
|
|
556
|
+
self,
|
|
557
|
+
*,
|
|
558
|
+
app_name: str,
|
|
559
|
+
user_id: str,
|
|
560
|
+
memory_id: str | None,
|
|
561
|
+
) -> None:
|
|
562
|
+
table = self.config.table_name
|
|
563
|
+
owner_filter = "app_name = %s AND tenant_id = %s AND user_id = %s"
|
|
564
|
+
owner_params: tuple[Any, ...] = (app_name, self.config.tenant_id, user_id)
|
|
565
|
+
if memory_id is not None:
|
|
566
|
+
sql = f"DELETE FROM {table} WHERE id = %s::uuid AND {owner_filter}"
|
|
567
|
+
params: tuple[Any, ...] = (memory_id, *owner_params)
|
|
568
|
+
else:
|
|
569
|
+
sql = f"DELETE FROM {table} WHERE {owner_filter}"
|
|
570
|
+
params = owner_params
|
|
571
|
+
|
|
572
|
+
t0 = time.perf_counter()
|
|
573
|
+
with self.rls_transaction(app_name=app_name, user_id=user_id) as cur:
|
|
574
|
+
cur.execute(sql, params)
|
|
575
|
+
deleted_count = cur.rowcount if cur.rowcount is not None else 0
|
|
576
|
+
latency_ms = (time.perf_counter() - t0) * 1000.0
|
|
577
|
+
|
|
578
|
+
self.last_query_telemetry = QueryTelemetry(
|
|
579
|
+
operation="delete_memory",
|
|
580
|
+
sql=sql,
|
|
581
|
+
session_context=self._rls_context(app_name=app_name, user_id=user_id),
|
|
582
|
+
latency_ms=latency_ms,
|
|
583
|
+
row_count=deleted_count,
|
|
584
|
+
simulate_missing_app_filter=self.config.simulate_missing_app_filter,
|
|
585
|
+
table_name=table,
|
|
586
|
+
)
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
def register_adk_uri(scheme: str = "memshield") -> None:
|
|
590
|
+
"""Register the `memshield://` URI scheme with Google ADK's ServiceRegistry."""
|
|
591
|
+
from google.adk.cli.service_registry import get_service_registry
|
|
592
|
+
|
|
593
|
+
def _factory(uri: str, **kwargs: Any) -> BaseMemoryService:
|
|
594
|
+
kwargs_copy = dict(kwargs)
|
|
595
|
+
kwargs_copy.pop("agents_dir", None)
|
|
596
|
+
return MemShieldMemoryService(uri=uri, **kwargs_copy)
|
|
597
|
+
|
|
598
|
+
get_service_registry().register_memory_service(scheme, _factory)
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
-- =============================================================================
|
|
2
|
+
-- adk-memshield (v0.1.0) PostgreSQL + pgvector Schema & RLS Policies
|
|
3
|
+
-- =============================================================================
|
|
4
|
+
-- Production schema. Apply this file only; `02_benchmark_baseline.sql` creates an
|
|
5
|
+
-- intentionally unprotected table for benchmarks and must not ship to production.
|
|
6
|
+
|
|
7
|
+
CREATE EXTENSION IF NOT EXISTS vector;
|
|
8
|
+
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
|
9
|
+
|
|
10
|
+
-- 1. Create non-superuser role to enforce Row-Level Security (RLS)
|
|
11
|
+
-- (PostgreSQL superusers bypass RLS even with FORCE ROW LEVEL SECURITY)
|
|
12
|
+
-- 'memshield_pass' is a local development default: rotate it in any real deployment.
|
|
13
|
+
DO $$
|
|
14
|
+
BEGIN
|
|
15
|
+
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'memshield_app') THEN
|
|
16
|
+
CREATE ROLE memshield_app LOGIN PASSWORD 'memshield_pass' NOSUPERUSER NOCREATEDB NOCREATEROLE NOBYPASSRLS;
|
|
17
|
+
END IF;
|
|
18
|
+
END
|
|
19
|
+
$$;
|
|
20
|
+
|
|
21
|
+
GRANT USAGE ON SCHEMA public TO memshield_app;
|
|
22
|
+
|
|
23
|
+
-- 2. RLS-Protected Semantic Memory Table
|
|
24
|
+
-- Identity columns reject empty strings: once a pooled connection has used
|
|
25
|
+
-- set_config(..., true), current_setting(..., true) returns '' (not NULL) after the
|
|
26
|
+
-- transaction ends, so an empty-string owner would otherwise match a context-free query.
|
|
27
|
+
CREATE TABLE IF NOT EXISTS memories (
|
|
28
|
+
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
29
|
+
app_name TEXT NOT NULL CHECK (app_name <> ''),
|
|
30
|
+
tenant_id TEXT NOT NULL CHECK (tenant_id <> ''),
|
|
31
|
+
user_id TEXT NOT NULL CHECK (user_id <> ''),
|
|
32
|
+
session_id TEXT,
|
|
33
|
+
author TEXT DEFAULT 'user',
|
|
34
|
+
scope TEXT NOT NULL DEFAULT 'private' CHECK (scope IN ('private', 'tenant_shared')),
|
|
35
|
+
min_clearance INTEGER NOT NULL DEFAULT 1 CHECK (min_clearance BETWEEN 1 AND 5),
|
|
36
|
+
content TEXT NOT NULL,
|
|
37
|
+
custom_metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
|
|
38
|
+
embedding vector(384) NOT NULL,
|
|
39
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
40
|
+
);
|
|
41
|
+
|
|
42
|
+
CREATE INDEX IF NOT EXISTS idx_memories_scope_lookup
|
|
43
|
+
ON memories (app_name, tenant_id, user_id);
|
|
44
|
+
|
|
45
|
+
-- Idempotent session ingestion: ADK may call add_session_to_memory() repeatedly for
|
|
46
|
+
-- the same session, so each (owner, session, event) is stored at most once.
|
|
47
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_memories_session_event
|
|
48
|
+
ON memories (app_name, tenant_id, user_id, session_id, (custom_metadata->>'event_id'))
|
|
49
|
+
WHERE custom_metadata ? 'event_id';
|
|
50
|
+
|
|
51
|
+
GRANT SELECT, INSERT, UPDATE, DELETE ON memories TO memshield_app;
|
|
52
|
+
|
|
53
|
+
-- 3. Enable & Force Row-Level Security on `memories`
|
|
54
|
+
ALTER TABLE memories ENABLE ROW LEVEL SECURITY;
|
|
55
|
+
ALTER TABLE memories FORCE ROW LEVEL SECURITY;
|
|
56
|
+
|
|
57
|
+
-- Read: own rows, plus tenant-shared rows at or below the agent's clearance.
|
|
58
|
+
DROP POLICY IF EXISTS memories_isolation_select ON memories;
|
|
59
|
+
CREATE POLICY memories_isolation_select ON memories
|
|
60
|
+
FOR SELECT
|
|
61
|
+
TO memshield_app
|
|
62
|
+
USING (
|
|
63
|
+
app_name = current_setting('app.current_app_name', true)
|
|
64
|
+
AND tenant_id = current_setting('app.current_tenant_id', true)
|
|
65
|
+
AND (
|
|
66
|
+
user_id = current_setting('app.current_user_id', true)
|
|
67
|
+
OR (
|
|
68
|
+
scope = 'tenant_shared'
|
|
69
|
+
AND min_clearance <= COALESCE(NULLIF(current_setting('app.agent_clearance', true), '')::int, 1)
|
|
70
|
+
)
|
|
71
|
+
)
|
|
72
|
+
);
|
|
73
|
+
|
|
74
|
+
-- Write: own rows only. A tenant_shared row may not be labelled above the writing
|
|
75
|
+
-- agent's clearance ("no write-up"), so a Tier-1 agent cannot plant content that
|
|
76
|
+
-- higher-clearance agents would trust as executive memory.
|
|
77
|
+
DROP POLICY IF EXISTS memories_isolation_insert ON memories;
|
|
78
|
+
CREATE POLICY memories_isolation_insert ON memories
|
|
79
|
+
FOR INSERT
|
|
80
|
+
TO memshield_app
|
|
81
|
+
WITH CHECK (
|
|
82
|
+
app_name = current_setting('app.current_app_name', true)
|
|
83
|
+
AND tenant_id = current_setting('app.current_tenant_id', true)
|
|
84
|
+
AND user_id = current_setting('app.current_user_id', true)
|
|
85
|
+
AND (
|
|
86
|
+
scope = 'private'
|
|
87
|
+
OR min_clearance <= COALESCE(NULLIF(current_setting('app.agent_clearance', true), '')::int, 1)
|
|
88
|
+
)
|
|
89
|
+
);
|
|
90
|
+
|
|
91
|
+
DROP POLICY IF EXISTS memories_isolation_update ON memories;
|
|
92
|
+
CREATE POLICY memories_isolation_update ON memories
|
|
93
|
+
FOR UPDATE
|
|
94
|
+
TO memshield_app
|
|
95
|
+
USING (
|
|
96
|
+
app_name = current_setting('app.current_app_name', true)
|
|
97
|
+
AND tenant_id = current_setting('app.current_tenant_id', true)
|
|
98
|
+
AND user_id = current_setting('app.current_user_id', true)
|
|
99
|
+
)
|
|
100
|
+
WITH CHECK (
|
|
101
|
+
app_name = current_setting('app.current_app_name', true)
|
|
102
|
+
AND tenant_id = current_setting('app.current_tenant_id', true)
|
|
103
|
+
AND user_id = current_setting('app.current_user_id', true)
|
|
104
|
+
AND (
|
|
105
|
+
scope = 'private'
|
|
106
|
+
OR min_clearance <= COALESCE(NULLIF(current_setting('app.agent_clearance', true), '')::int, 1)
|
|
107
|
+
)
|
|
108
|
+
);
|
|
109
|
+
|
|
110
|
+
DROP POLICY IF EXISTS memories_isolation_delete ON memories;
|
|
111
|
+
CREATE POLICY memories_isolation_delete ON memories
|
|
112
|
+
FOR DELETE
|
|
113
|
+
TO memshield_app
|
|
114
|
+
USING (
|
|
115
|
+
app_name = current_setting('app.current_app_name', true)
|
|
116
|
+
AND tenant_id = current_setting('app.current_tenant_id', true)
|
|
117
|
+
AND user_id = current_setting('app.current_user_id', true)
|
|
118
|
+
);
|
|
@@ -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).
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
adk_memshield/__init__.py,sha256=Plq8LBlAAZWlwX-L9ChANDD9r4aKIudEOTZj_yG0Qlk,426
|
|
2
|
+
adk_memshield/config.py,sha256=FBubNWk0WUJa7w3vwkGRnJOetVpjSP8jz4es_Qvcww4,2788
|
|
3
|
+
adk_memshield/embedder.py,sha256=vitLspPupLGmAoakYHV_OfuNSZm1Fc1Y4nuwyRMFzcg,2244
|
|
4
|
+
adk_memshield/service.py,sha256=yyVFmHl_iM7OS92z12YFjyNU9LNmora965iUPXVp1Qg,22161
|
|
5
|
+
adk_memshield/sql/01_schema.sql,sha256=TLTVxtTqq-SgaQsPMyXaFD4HLzgprQnt2wRdaO3zl_4,5147
|
|
6
|
+
adk_memshield-0.1.0.dist-info/METADATA,sha256=uiSOh56nTHC2BzC3aVHl8cXkuYgCjsk8dv90ceRpMz8,16406
|
|
7
|
+
adk_memshield-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
8
|
+
adk_memshield-0.1.0.dist-info/licenses/LICENSE,sha256=psuoW8kuDP96RQsdhzwOqi6fyWv0ct8CR6Jr7He_P_k,10173
|
|
9
|
+
adk_memshield-0.1.0.dist-info/RECORD,,
|
|
@@ -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
|