Registry-Flag include_global und read-only read_children-Scopes
- include_global=false blendet globale Eintraege (project=None) und fremde for:-Delegationen fuer einen Slug in index, search, get, stats und Hook-Start aus; memory_save(scope="global") wird auch mit Env-Gate und OAuth-Scope abgelehnt. Subscopes erben das Flag. Default true: bestehende Registries und stdio bleiben unveraendert. - _idea_target_clause matcht nie globale Eintraege: eine globale Idee mit for:<slug> konnte aus einem Projekt heraus per forget/supersedes veraendert werden. - read_children auf einen allow_subprojects-Slug macht auch dessen Subscopes lesbar (Label <slug>/<subscope>). - memory_consolidate(project=...) kuratiert nur die Session selbst und Scopes unterhalb ihrer project_id, nie nur lesbare Fremd-Slugs. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
ac0c7a2a51
commit
0f2965d2af
17 changed files with 641 additions and 44 deletions
|
|
@ -208,7 +208,9 @@ Serverprozesses sein. Slugs, Projekt-IDs, Principals, Anzahl und Dateigröße si
|
|||
Felder und doppelte JSON-Schlüssel werden fail-closed abgelehnt. `read_children` ist optional und
|
||||
erlaubt dem Projekt zusätzlich den lesenden Zugriff auf die transitiven Unterprojekte; die
|
||||
Beziehungen müssen auf registrierte Slugs zeigen und dürfen keine Zyklen enthalten. Das Lesen von
|
||||
Kindern ist eine explizite Registry-Freigabe, keine Dateisystemsuche.
|
||||
Kindern ist eine explizite Registry-Freigabe, keine Dateisystemsuche. Das optionale
|
||||
`include_global: false` blendet die kuratierten globalen Einträge für diesen Slug aus (siehe
|
||||
`docs/configuration.de.md`).
|
||||
|
||||
### Server starten
|
||||
|
||||
|
|
@ -246,7 +248,7 @@ HTTPS, ohne Redirects, größenbegrenzt und mit Cache geladen.
|
|||
| `mongomind:transfer` | serverseitiger Datei-Export und -Import |
|
||||
| `mongomind:hooks:read` | `POST /hooks/<slug>/start` |
|
||||
| `mongomind:hooks:write` | `POST /hooks/<slug>/events` |
|
||||
| `mongomind:global:write` | zusätzlicher Gate für `memory_save(scope="global")`; serverseitig muss außerdem `MONGOMIND_ALLOW_GLOBAL_WRITE=1` gelten |
|
||||
| `mongomind:global:write` | zusätzlicher Gate für `memory_save(scope="global")`; serverseitig muss außerdem `MONGOMIND_ALLOW_GLOBAL_WRITE=1` gelten; für Registry-Slugs mit `include_global: false` stets abgelehnt |
|
||||
|
||||
### Remote-Clients
|
||||
|
||||
|
|
|
|||
|
|
@ -208,7 +208,8 @@ exactamente el modo `0600`. Los slugs, los ID de proyecto, los principales, el n
|
|||
campos desconocidos y las claves JSON duplicadas se rechazarán con «fail-closed». `read_children` es opcional y
|
||||
permite además al proyecto el acceso de lectura a los subproyectos transitivos; las
|
||||
relaciones deben apuntar a slugs registrados y no pueden contener ciclos. La lectura de
|
||||
subproyectos es una autorización explícita del registro, no una búsqueda en el sistema de archivos.
|
||||
subproyectos es una autorización explícita del registro, no una búsqueda en el sistema de archivos. El opcional `include_global: false`
|
||||
oculta las entradas globales curadas para ese slug (véase `docs/configuration.es.md`).
|
||||
|
||||
### Iniciar el servidor
|
||||
|
||||
|
|
@ -246,7 +247,7 @@ HTTPS, sin redireccionamientos, con límite de tamaño y con caché.
|
|||
| `mongomind:transfer` | Exportación e importación de archivos desde el servidor |
|
||||
| `mongomind:hooks:read` | `POST /hooks/<slug>/start` |
|
||||
| `mongomind:hooks:write` | `POST /hooks/<slug>/events` |
|
||||
| `mongomind:global:write` | puerta adicional para `memory_save(scope="global")`; además, en el servidor debe estar activo `MONGOMIND_ALLOW_GLOBAL_WRITE=1` |
|
||||
| `mongomind:global:write` | puerta adicional para `memory_save(scope="global")`; además, en el servidor debe estar activo `MONGOMIND_ALLOW_GLOBAL_WRITE=1`; siempre rechazado para slugs del registro con `include_global: false` |
|
||||
|
||||
### Clientes remotos
|
||||
|
||||
|
|
|
|||
|
|
@ -208,7 +208,8 @@ The file must be regular, symlink-free, owned by the server process, and have th
|
|||
fields and duplicate JSON keys are rejected using fail-closed. `read_children` is optional and
|
||||
also grants the project read access to transitive subprojects; the
|
||||
relationships must point to registered slugs and must not contain cycles. Reading
|
||||
children is an explicit registry permission, not a filesystem search.
|
||||
children is an explicit registry permission, not a filesystem search. The optional
|
||||
`include_global: false` hides the curated global entries for that slug (see `docs/configuration.md`).
|
||||
|
||||
### Start the server
|
||||
|
||||
|
|
@ -246,7 +247,7 @@ HTTPS, without redirects, with size limits, and with caching.
|
|||
| `mongomind:transfer` | Server-side file export and import |
|
||||
| `mongomind:hooks:read` | `POST /hooks/<slug>/start` |
|
||||
| `mongomind:hooks:write` | `POST /hooks/<slug>/events` |
|
||||
| `mongomind:global:write` | Additional gate for `memory_save(scope="global")`; `MONGOMIND_ALLOW_GLOBAL_WRITE=1` must also apply on the server side |
|
||||
| `mongomind:global:write` | Additional gate for `memory_save(scope="global")`; `MONGOMIND_ALLOW_GLOBAL_WRITE=1` must also apply on the server side; always refused for registry slugs with `include_global: false` |
|
||||
|
||||
### Remote Clients
|
||||
|
||||
|
|
|
|||
|
|
@ -114,8 +114,8 @@ unter `~/.mongomind/exports/`.
|
|||
- `observations` — zentrale Collection für alle Erinnerungen (aktiv, `pending`, archiviert),
|
||||
Version-Chains und Zähler für Reinforcement/Ablauf. Sämtliche Lese-/Schreibpfade in
|
||||
`store.py` (Dedup, Konsolidierung, Rollup, Forget, Migrationsschritte) operieren auf dieser
|
||||
Collection unter striktem Projekt-Scope; globale Einträge sind aus einem Projektkontext lesbar,
|
||||
aber nicht veränderbar.
|
||||
Collection unter striktem Projekt-Scope; globale Einträge sind aus einem Projektkontext lesbar
|
||||
(außer der Registry-Slug setzt `include_global: false`), aber nicht veränderbar.
|
||||
- `counters` — atomare Zähler (`find_one_and_update`), u. a. für ID-Vergabe.
|
||||
- `locks` — Koordination nebenläufiger Operationen (z. B. Rollup-Lease), verhindert doppelte
|
||||
Verdichtung bei parallelen Hook-/Admin-Läufen.
|
||||
|
|
|
|||
|
|
@ -112,8 +112,8 @@ en `~/.mongomind/exports/`.
|
|||
- `observations`: colección central para todas las memorias (activas, `pending`, archivadas),
|
||||
cadenas de versiones y contadores para refuerzo/caducidad. Todas las rutas de lectura/escritura en
|
||||
`store.py` (deduplicación, consolidación, rollup, olvido, pasos de migración) operan en esta
|
||||
colección dentro del ámbito del proyecto; las entradas globales son legibles desde el contexto del proyecto,
|
||||
pero no modificables.
|
||||
colección dentro del ámbito del proyecto; las entradas globales son legibles desde el contexto del proyecto
|
||||
(salvo que el slug del registro establezca `include_global: false`), pero no modificables.
|
||||
- `counters` — contadores atómicos (`find_one_and_update`), entre otros, para la asignación de ID.
|
||||
- `locks` — coordinación de operaciones concurrentes (p. ej., Rollup-Lease), evita la doble
|
||||
agregación en ejecuciones paralelas de hooks y tareas de administración.
|
||||
|
|
|
|||
|
|
@ -113,8 +113,8 @@ under `~/.mongomind/exports/`.
|
|||
- `observations` — central collection for all memories (active, `pending`, archived),
|
||||
version chains, and counters for reinforcement/expiration. All read/write paths in
|
||||
`store.py` (deduplication, consolidation, rollup, forget, migration steps) operate on this
|
||||
collection within a strictly defined project scope; global entries are readable from a project context,
|
||||
but cannot be modified.
|
||||
collection within a strictly defined project scope; global entries are readable from a project context
|
||||
(unless the registry slug sets `include_global: false`), but cannot be modified.
|
||||
- `counters` — atomic counters (`find_one_and_update`), used, among other things, for ID assignment.
|
||||
- `locks` — coordination of concurrent operations (e.g., rollup lease), prevents duplicate
|
||||
consolidation during parallel hook/admin runs.
|
||||
|
|
|
|||
|
|
@ -118,7 +118,8 @@ zum Startabbruch.
|
|||
{"sub": "provider-subject", "client_id": "registrierter-client"}
|
||||
],
|
||||
"read_children": ["unterprojekt-slug"],
|
||||
"allow_subprojects": true
|
||||
"allow_subprojects": true,
|
||||
"include_global": false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -134,7 +135,10 @@ Principals je Projekt werden akzeptiert. `project_id`, `(sub, client_id)` und Fe
|
|||
sein; doppelte Projekt-IDs, Principals, unbekannte Felder oder doppelte JSON-Schlüssel sind Fehler.
|
||||
`read_children` ist optional und bildet eine explizite, transitive Parent→Kinder-Lesesicht. Alle
|
||||
referenzierten Slugs müssen registriert sein; Selbstreferenzen und Zyklen werden abgelehnt. Die
|
||||
Beziehung erweitert nur Reads des Parent-Endpunkts und ändert keine Schreibberechtigung des Kindes.
|
||||
Beziehung erweitert nur Reads des Parent-Endpunkts und ändert keine Schreibberechtigung des Kindes:
|
||||
`memory_consolidate(project=…)` kuratiert nur den Slug selbst und Scopes *unterhalb* der eigenen
|
||||
`project_id`, nie ein Projekt, das nur über `read_children` lesbar ist. Hat ein Kind-Slug
|
||||
`allow_subprojects: true`, sind auch dessen entdeckte Subscopes lesbar (Label `<kind-slug>/<subscope>`).
|
||||
Die Registry wird beim Serverstart unveränderlich geladen; Änderungen werden erst nach einem
|
||||
kontrollierten Neustart wirksam.
|
||||
|
||||
|
|
@ -161,6 +165,19 @@ getrennter* Kunde/Client braucht weiterhin einen admin-provisionierten Slug mit
|
|||
Berechtigung gedacht (z. B. mehrere Geräte oder Themenbereiche desselben Nutzers), nicht als Ersatz
|
||||
für eine echte Zugriffsgrenze.
|
||||
|
||||
#### Globale Einträge (`include_global`)
|
||||
|
||||
Standardmäßig liest jeder Scope zusätzlich die kuratierten globalen Einträge (`project` = null). Mit
|
||||
`"include_global": false` sieht der Slug **ausschließlich seine eigenen Scopes**: keine globalen
|
||||
Einträge in `memory_index`, `memory_search`, `memory_get`, `memory_stats` und im Hook-Startkontext,
|
||||
und keine `for:<slug>`-Ideen-Delegationen aus anderen Projekten. `memory_save(scope="global")` wird
|
||||
ebenfalls abgelehnt, selbst bei gesetztem `MONGOMIND_ALLOW_GLOBAL_WRITE=1` und `mongomind:global:write`:
|
||||
das Flag gewinnt immer. Subscopes erben das Flag von ihrem Slug. Der Default ist `true`; bestehende
|
||||
Registries und der lokale stdio-Server verhalten sich also unverändert. Das Flag ist der
|
||||
Registry-seitige Weg, einem Client (z. B. einem externen Assistenten) ein eigenes, isoliertes
|
||||
Gedächtnis zu geben; setzt man es später zusammen mit `read_children` wieder auf `true`, öffnet sich
|
||||
die Lesesicht ohne Änderung an Client oder Provider.
|
||||
|
||||
Für `<slug>` wird das JWT gegen genau diese einzelne Audience geprüft:
|
||||
|
||||
```text
|
||||
|
|
@ -182,7 +199,7 @@ und OAuth-Antworten über 256 KiB werden abgelehnt.
|
|||
| `memory_export`, `memory_import` | `mongomind:transfer` |
|
||||
| `POST /hooks/<slug>/start` | `mongomind:hooks:read` |
|
||||
| `POST /hooks/<slug>/events` | `mongomind:hooks:write` |
|
||||
| globaler Save zusätzlich | `mongomind:global:write` plus `MONGOMIND_ALLOW_GLOBAL_WRITE=1` |
|
||||
| globaler Save zusätzlich | `mongomind:global:write` plus `MONGOMIND_ALLOW_GLOBAL_WRITE=1`; für Slugs mit `include_global: false` abgelehnt |
|
||||
|
||||
Der MCP-Endpunkt ist `POST /mcp/<slug>`. Die Protected-Resource-Metadaten stehen unter
|
||||
`GET /.well-known/oauth-protected-resource/mcp/<slug>`. `X-MongoMind-Project` und
|
||||
|
|
|
|||
|
|
@ -117,7 +117,8 @@ la interrupción del inicio.
|
|||
{"sub": "provider-subject", "client_id": "cliente-registrado"}
|
||||
],
|
||||
"read_children": ["slug-de-subproyecto"],
|
||||
"allow_subprojects": true
|
||||
"allow_subprojects": true,
|
||||
"include_global": false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -133,7 +134,10 @@ principales por proyecto. `project_id`, `(sub, client_id)` y los campos deben co
|
|||
los ID de proyecto duplicados, los principales, los campos desconocidos o las claves JSON duplicadas constituyen errores.
|
||||
`read_children` es opcional y constituye una vista de lectura explícita y transitiva de padre a hijos. Todos los
|
||||
slugs a los que se hace referencia deben estar registrados; se rechazan las autorreferencias y los ciclos. La
|
||||
relación solo amplía las lecturas del punto final padre y no modifica los permisos de escritura del punto final hijo.
|
||||
relación solo amplía las lecturas del punto final padre y no modifica los permisos de escritura del punto final hijo:
|
||||
`memory_consolidate(project=…)` solo cura el propio slug y los ámbitos *por debajo* de su `project_id`,
|
||||
nunca un proyecto que solo sea legible mediante `read_children`. Si un slug hijo tiene
|
||||
`allow_subprojects: true`, sus subámbitos descubiertos también son legibles (etiqueta `<slug-hijo>/<subámbito>`).
|
||||
El registro se carga de forma inmutable al iniciar el servidor; los cambios solo surten efecto tras un
|
||||
reinicio controlado.
|
||||
|
||||
|
|
@ -160,6 +164,19 @@ separado* sigue necesitando un slug provisionado por el administrador con su pro
|
|||
(por ejemplo, varios dispositivos o áreas temáticas del mismo usuario), no como sustituto
|
||||
de un límite de acceso real.
|
||||
|
||||
#### Entradas globales (`include_global`)
|
||||
|
||||
De forma predeterminada, cada ámbito lee además las entradas globales curadas (`project` = null). Con
|
||||
`"include_global": false`, el slug ve **únicamente sus propios ámbitos**: sin entradas globales en
|
||||
`memory_index`, `memory_search`, `memory_get`, `memory_stats` ni en el contexto de inicio de los hooks, y sin
|
||||
delegaciones de ideas `for:<slug>` de otros proyectos. `memory_save(scope="global")` también se rechaza,
|
||||
incluso con `MONGOMIND_ALLOW_GLOBAL_WRITE=1` y `mongomind:global:write`: el indicador siempre prevalece.
|
||||
Los subámbitos heredan el indicador de su slug. El valor predeterminado es `true`, por lo que los registros
|
||||
existentes y el servidor stdio local se comportan exactamente igual que antes. El indicador es la vía, del lado
|
||||
del registro, para dar a un cliente (por ejemplo, un asistente externo) una memoria propia y aislada; si más
|
||||
adelante se vuelve a poner en `true` junto con `read_children`, la vista de lectura se abre sin cambios en el
|
||||
cliente ni en el proveedor.
|
||||
|
||||
En el caso de `<slug>`, el JWT se verifica frente a esta audiencia concreta:
|
||||
|
||||
```text
|
||||
|
|
@ -181,7 +198,7 @@ y las respuestas OAuth superiores a 256 KiB.
|
|||
| `memory_export`, `memory_import` | `mongomind:transfer` |
|
||||
| `POST /hooks/<slug>/start` | `mongomind:hooks:read` |
|
||||
| `POST /hooks/<slug>/events` | `mongomind:hooks:write` |
|
||||
| guardado global adicional | `mongomind:global:write` más `MONGOMIND_ALLOW_GLOBAL_WRITE=1` |
|
||||
| guardado global adicional | `mongomind:global:write` más `MONGOMIND_ALLOW_GLOBAL_WRITE=1`; rechazado para slugs con `include_global: false` |
|
||||
|
||||
El punto final MCP es `POST /mcp/<slug>`. Los metadatos de recursos protegidos se encuentran en
|
||||
`GET /.well-known/oauth-protected-resource/mcp/<slug>`. `X-MongoMind-Project` y
|
||||
|
|
|
|||
|
|
@ -117,7 +117,8 @@ in a startup failure.
|
|||
{"sub": "provider-subject", "client_id": "registered-client"}
|
||||
],
|
||||
"read_children": ["subproject-slug"],
|
||||
"allow_subprojects": true
|
||||
"allow_subprojects": true,
|
||||
"include_global": false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -133,7 +134,10 @@ principals per project are accepted. `project_id`, `(sub, client_id)`, and field
|
|||
duplicate project IDs, principals, unknown fields, or duplicate JSON keys are errors.
|
||||
`read_children` is optional and forms an explicit, transitive parent→child read view. All
|
||||
referenced slugs must be registered; self-references and cycles are rejected. The
|
||||
relationship only extends reads of the parent endpoint and does not change the child’s write permissions.
|
||||
relationship only extends reads of the parent endpoint and does not change the child’s write permissions:
|
||||
`memory_consolidate(project=…)` can curate only the slug itself and scopes *below* its own `project_id`,
|
||||
never a project that is merely readable via `read_children`. If a child slug has `allow_subprojects: true`,
|
||||
its discovered subscopes are readable too (label `<child-slug>/<subscope>`).
|
||||
The registry is loaded immutably at server startup; changes take effect only after a
|
||||
controlled restart.
|
||||
|
||||
|
|
@ -160,6 +164,18 @@ separate* customer/client still requires an admin-provisioned slug with its own
|
|||
permission (e.g., multiple devices or subject areas of the same user), not as a substitute
|
||||
for a true access boundary.
|
||||
|
||||
#### Global entries (`include_global`)
|
||||
|
||||
By default every scope also reads the curated global entries (`project` = null). With
|
||||
`"include_global": false`, the slug sees **only its own scopes**: no global entries in
|
||||
`memory_index`, `memory_search`, `memory_get`, `memory_stats`, or the hook start context, and no `for:<slug>`
|
||||
idea delegations from other projects. `memory_save(scope="global")` is refused as well, even if
|
||||
`MONGOMIND_ALLOW_GLOBAL_WRITE=1` and `mongomind:global:write` are present: the flag always wins.
|
||||
Subscopes inherit the flag from their slug. The default is `true`, so existing registries and
|
||||
the local stdio server behave exactly as before. The flag is the registry-side way to give a client
|
||||
(for example an external assistant) its own isolated memory; switching it back to `true`—together
|
||||
with `read_children`—later opens the read view without any client or provider change.
|
||||
|
||||
For `<slug>`, the JWT is validated against this exact single audience:
|
||||
|
||||
```text
|
||||
|
|
@ -181,7 +197,7 @@ and OAuth responses over 256 KiB are rejected.
|
|||
| `memory_export`, `memory_import` | `mongomind:transfer` |
|
||||
| `POST /hooks/<slug>/start` | `mongomind:hooks:read` |
|
||||
| `POST /hooks/<slug>/events` | `mongomind:hooks:write` |
|
||||
| additional global save | `mongomind:global:write` plus `MONGOMIND_ALLOW_GLOBAL_WRITE=1` |
|
||||
| additional global save | `mongomind:global:write` plus `MONGOMIND_ALLOW_GLOBAL_WRITE=1`; refused for slugs with `include_global: false` |
|
||||
|
||||
The MCP endpoint is `POST /mcp/<slug>`. The protected resource metadata is located at
|
||||
`GET /.well-known/oauth-protected-resource/mcp/<slug>`. `X-MongoMind-Project` and
|
||||
|
|
|
|||
|
|
@ -278,6 +278,7 @@ class Project:
|
|||
allowed_principals: frozenset[tuple[str, str]]
|
||||
read_children: tuple[str, ...] = ()
|
||||
allow_subprojects: bool = False
|
||||
include_global: bool = True
|
||||
|
||||
def allows(self, sub: str, client_id: str) -> bool:
|
||||
return (sub, client_id) in self.allowed_principals
|
||||
|
|
@ -333,6 +334,7 @@ class ProjectRegistry:
|
|||
"project_id", "allowed_principals",
|
||||
}.issubset(raw_project) or set(raw_project) - {
|
||||
"project_id", "allowed_principals", "read_children", "allow_subprojects",
|
||||
"include_global",
|
||||
}:
|
||||
raise AuthConfigurationError(f"Projekt {slug} hat ungueltige Felder.")
|
||||
project_id = _clean_identifier(raw_project["project_id"], "project_id")
|
||||
|
|
@ -369,9 +371,13 @@ class ProjectRegistry:
|
|||
raw_allow_subprojects = raw_project.get("allow_subprojects", False)
|
||||
if not isinstance(raw_allow_subprojects, bool):
|
||||
raise AuthConfigurationError(f"allow_subprojects fuer {slug} ist ungueltig.")
|
||||
raw_include_global = raw_project.get("include_global", True)
|
||||
if not isinstance(raw_include_global, bool):
|
||||
raise AuthConfigurationError(f"include_global fuer {slug} ist ungueltig.")
|
||||
project_ids.add(project_id)
|
||||
projects[slug] = Project(
|
||||
slug, project_id, frozenset(principals), tuple(children), raw_allow_subprojects,
|
||||
raw_include_global,
|
||||
)
|
||||
for slug, project in projects.items():
|
||||
for child in project.read_children:
|
||||
|
|
|
|||
|
|
@ -415,21 +415,32 @@ class _Handler(BaseHTTPRequestHandler):
|
|||
)
|
||||
for project in projects
|
||||
]
|
||||
root = registry.project(slug)
|
||||
if getattr(root, "allow_subprojects", False):
|
||||
known_ids = {item.project for item in result}
|
||||
for project_id in _known_subprojects(root.project_id):
|
||||
known_ids = {item.project for item in result}
|
||||
for project in projects:
|
||||
if not getattr(project, "allow_subprojects", False):
|
||||
continue
|
||||
# Der Root-Slug zeigt Subscopes unter ihrem Suffix; ueber read_children
|
||||
# erreichte Slugs behalten ihr Slug-Praefix, damit die Herkunft sichtbar bleibt.
|
||||
is_root = project.slug == slug
|
||||
base_depth = 0 if is_root else depths.get(project.slug, 1)
|
||||
for project_id in _known_subprojects(project.project_id):
|
||||
if project_id in known_ids:
|
||||
continue
|
||||
suffix = project_id[len(root.project_id) + 1:]
|
||||
known_ids.add(project_id)
|
||||
suffix = project_id[len(project.project_id) + 1:]
|
||||
result.append(scope.ReadScope(
|
||||
project=project_id,
|
||||
label=suffix,
|
||||
depth=suffix.count("/") + 1,
|
||||
label=suffix if is_root else f"{project.slug}/{suffix}",
|
||||
depth=base_depth + suffix.count("/") + 1,
|
||||
current=False,
|
||||
))
|
||||
return tuple(result)
|
||||
|
||||
def _include_global(self, slug: str) -> bool:
|
||||
"""Registry-Flag ``include_global``; Subscopes erben es vom Root-Slug."""
|
||||
registry = self.server.project_registry # type: ignore[attr-defined]
|
||||
return getattr(registry.project(slug), "include_global", True) is not False
|
||||
|
||||
def _subscope_root(self, slug: str, segments: tuple[str, ...]) -> str | None:
|
||||
"""Root project id whose subscopes may be addressed via ``project=``.
|
||||
|
||||
|
|
@ -541,6 +552,7 @@ class _Handler(BaseHTTPRequestHandler):
|
|||
context = {
|
||||
"project": principal.project_id,
|
||||
"read_scopes": self._read_scopes(slug, segments),
|
||||
"include_global": self._include_global(slug),
|
||||
"subscope_root": self._subscope_root(slug, segments),
|
||||
"origin_client": _clean_log(principal.client_id, store.MAX_ORIGIN_CLIENT_CHARS).lower(),
|
||||
"rate_key": principal.rate_key,
|
||||
|
|
@ -639,6 +651,7 @@ class _Handler(BaseHTTPRequestHandler):
|
|||
project=principal.project_id,
|
||||
budget=budget,
|
||||
read_scopes=self._read_scopes(slug),
|
||||
include_global=self._include_global(slug),
|
||||
) or ""
|
||||
except OverflowError as exc:
|
||||
self._reject(413, str(exc))
|
||||
|
|
|
|||
|
|
@ -345,6 +345,17 @@ def _read_scopes(project: str | None, context: dict | None) -> tuple[scope.ReadS
|
|||
return scope.resolve_local(project).scopes if project is not None else None
|
||||
|
||||
|
||||
def _include_global(context: dict | None) -> bool:
|
||||
"""Registry-Flag ``include_global`` aus dem vertrauenswuerdigen Request-Kontext.
|
||||
|
||||
Fehlt der Key (stdio, aeltere Aufrufer), gilt der Default ``True``. Ein
|
||||
vorhandener, aber nicht eindeutig ``True``-Wert schliesst fail-closed.
|
||||
"""
|
||||
if not context or "include_global" not in context:
|
||||
return True
|
||||
return context["include_global"] is True
|
||||
|
||||
|
||||
def _derive_subscope(requested: str, subscope_root: str) -> str | None:
|
||||
"""Derive ``<root>/<segments>`` for a not-yet-discovered subscope.
|
||||
|
||||
|
|
@ -395,16 +406,26 @@ def _local_root(project: str | None, context: dict | None) -> str | None:
|
|||
return project
|
||||
|
||||
|
||||
def _is_below(project_id: str, session_project: str | None) -> bool:
|
||||
return bool(session_project) and project_id.startswith(session_project.rstrip("/") + "/")
|
||||
|
||||
|
||||
def _resolve_target_project(
|
||||
requested_project: str | None,
|
||||
session_project: str | None,
|
||||
read_scopes: tuple[scope.ReadScope, ...] | None,
|
||||
subscope_root: str | None = None,
|
||||
local_root: str | None = None,
|
||||
for_mutation: bool = False,
|
||||
) -> str | None:
|
||||
"""Validate an explicit ``project`` override against this session's own
|
||||
server-authorized read_scopes.
|
||||
|
||||
``for_mutation=True`` (``memory_consolidate``) erlaubt aus den read_scopes nur
|
||||
die Session selbst und Scopes *unterhalb* ihrer Projekt-ID. Ueber
|
||||
``read_children`` erreichte fremde Slugs sind damit lesbar, aber nicht
|
||||
kuratierbar.
|
||||
|
||||
Accepts either the opaque ``ReadScope.project`` id or its human-readable
|
||||
``ReadScope.label`` -- callers only ever see labels (``Projekt=child`` in
|
||||
memory_index/memory_get, the pending-rollup line), never the raw id, so
|
||||
|
|
@ -427,6 +448,10 @@ def _resolve_target_project(
|
|||
return session_project
|
||||
for read_scope in read_scopes or ():
|
||||
if requested_project in (read_scope.project, read_scope.label):
|
||||
if for_mutation and not _is_below(read_scope.project, session_project):
|
||||
raise ValueError(
|
||||
f"project {requested_project!r} ist nur lesbar und kann nicht kuratiert werden."
|
||||
)
|
||||
return read_scope.project
|
||||
if subscope_root:
|
||||
derived = _derive_subscope(requested_project, subscope_root)
|
||||
|
|
@ -809,6 +834,7 @@ def _call_tool(name: str, args: dict, context: dict | None = None) -> str:
|
|||
project=project,
|
||||
limit=_clamp_limit(args.get("limit", 30), 1, 100, 30),
|
||||
read_scopes=read_scopes,
|
||||
include_global=_include_global(context),
|
||||
)
|
||||
return "\n".join(lines) if lines else "Gedächtnis leer."
|
||||
if name == "memory_search":
|
||||
|
|
@ -822,6 +848,7 @@ def _call_tool(name: str, args: dict, context: dict | None = None) -> str:
|
|||
since_days=args.get("since_days"),
|
||||
include_pending=args.get("include_pending", False),
|
||||
read_scopes=read_scopes,
|
||||
include_global=_include_global(context),
|
||||
)
|
||||
return "\n".join(hits) if hits else "Keine Treffer."
|
||||
if name == "memory_get":
|
||||
|
|
@ -835,6 +862,7 @@ def _call_tool(name: str, args: dict, context: dict | None = None) -> str:
|
|||
project=target_project,
|
||||
expand=args.get("expand", True),
|
||||
read_scopes=read_scopes,
|
||||
include_global=_include_global(context),
|
||||
reinforce=not _read_only() and (
|
||||
_context_scopes(context) is None or SCOPE_WRITE in _context_scopes(context)
|
||||
),
|
||||
|
|
@ -872,6 +900,7 @@ def _call_tool(name: str, args: dict, context: dict | None = None) -> str:
|
|||
target_project = _resolve_target_project(
|
||||
args.get("project"), project, read_scopes, (context or {}).get("subscope_root"),
|
||||
_local_root(project, context),
|
||||
for_mutation=True,
|
||||
)
|
||||
result = store.consolidate(
|
||||
db,
|
||||
|
|
@ -896,7 +925,7 @@ def _call_tool(name: str, args: dict, context: dict | None = None) -> str:
|
|||
count = store.forget(db, _parse_ids(args["ids"]), project=project)
|
||||
return f"{count} archiviert."
|
||||
if name == "memory_stats":
|
||||
stats = store.stats(db, project=project)
|
||||
stats = store.stats(db, project=project, include_global=_include_global(context))
|
||||
active = stats["active"] if stats["active"] is not None else "unbekannt (Timeout)"
|
||||
pending = stats["pending"] if stats["pending"] is not None else "unbekannt (Timeout)"
|
||||
archived = stats["archived"] if stats["archived"] is not None else "unbekannt (Timeout)"
|
||||
|
|
@ -940,6 +969,8 @@ def _call_tool(name: str, args: dict, context: dict | None = None) -> str:
|
|||
def _project_for_authorized(scope: str, project: str | None, context: dict) -> str | None:
|
||||
if scope != "global":
|
||||
return project
|
||||
if not _include_global(context):
|
||||
raise PermissionError("Globale Einträge sind für dieses Projekt deaktiviert.")
|
||||
if not _allow_global_write():
|
||||
raise PermissionError("Globale Schreibzugriffe sind serverseitig nicht freigeschaltet.")
|
||||
scopes = _context_scopes(context)
|
||||
|
|
|
|||
|
|
@ -430,7 +430,14 @@ def _age_days(doc: dict, now: float) -> float:
|
|||
|
||||
|
||||
def _idea_target_clause(project: str | None) -> dict:
|
||||
return {"type": "idea", "tags": f"{IDEA_TARGET_PREFIX}{project_slug(project)}"}
|
||||
# ``project != None``: Globale Eintraege duerfen nie ueber eine ``for:``-Delegation
|
||||
# aus einem Projekt heraus veraendert werden (AGENTS.md). Lesend matchen sie
|
||||
# weiterhin ueber den ``project: None``-Zweig von ``_project_clause``.
|
||||
return {
|
||||
"type": "idea",
|
||||
"tags": f"{IDEA_TARGET_PREFIX}{project_slug(project)}",
|
||||
"project": {"$ne": None},
|
||||
}
|
||||
|
||||
|
||||
def _read_project_values(
|
||||
|
|
@ -498,6 +505,7 @@ def _project_clause(
|
|||
*,
|
||||
include_idea_targets: bool = False,
|
||||
read_scopes: tuple[ReadScope, ...] | list[ReadScope] | None = None,
|
||||
include_global: bool = True,
|
||||
) -> dict:
|
||||
"""Read current/derived project scopes and global entries.
|
||||
|
||||
|
|
@ -505,13 +513,19 @@ def _project_clause(
|
|||
project but tagged ``for:<this project's slug>`` — an explicit delegation that
|
||||
stays anchored to the exact ``project``, independent of the server-derived
|
||||
read scopes (see docs/plan-idea-type.md).
|
||||
|
||||
``include_global=False`` (Registry-Feld ``include_global``) blendet globale
|
||||
Eintraege (``project: None``) und fremde ``for:``-Delegationen aus: der Slug
|
||||
sieht dann ausschliesslich seine eigenen Scopes.
|
||||
"""
|
||||
projects = _read_project_values(project, read_scopes)
|
||||
if projects is None:
|
||||
return {}
|
||||
clauses = [{"project": {"$in": list(projects)}}, {"project": None}]
|
||||
if include_idea_targets and project is not None:
|
||||
clauses.append(_idea_target_clause(project))
|
||||
return {} if include_global else {"project": {"$ne": None}}
|
||||
clauses: list[dict] = [{"project": {"$in": list(projects)}}]
|
||||
if include_global:
|
||||
clauses.append({"project": None})
|
||||
if include_idea_targets and project is not None:
|
||||
clauses.append(_idea_target_clause(project))
|
||||
return {"$or": clauses}
|
||||
|
||||
|
||||
|
|
@ -553,6 +567,7 @@ def _not_forgotten_filter(
|
|||
include_pending: bool = False,
|
||||
include_idea_targets: bool = False,
|
||||
read_scopes: tuple[ReadScope, ...] | list[ReadScope] | None = None,
|
||||
include_global: bool = True,
|
||||
) -> dict:
|
||||
now = time.time()
|
||||
clauses: list[dict] = [
|
||||
|
|
@ -562,7 +577,10 @@ def _not_forgotten_filter(
|
|||
_review_scope_clause(include_pending, project=project, read_scopes=read_scopes),
|
||||
]
|
||||
proj = _project_clause(
|
||||
project, include_idea_targets=include_idea_targets, read_scopes=read_scopes
|
||||
project,
|
||||
include_idea_targets=include_idea_targets,
|
||||
read_scopes=read_scopes,
|
||||
include_global=include_global,
|
||||
)
|
||||
if proj:
|
||||
clauses.append(proj)
|
||||
|
|
@ -574,9 +592,13 @@ def _base_filter(
|
|||
*,
|
||||
include_idea_targets: bool = False,
|
||||
read_scopes: tuple[ReadScope, ...] | list[ReadScope] | None = None,
|
||||
include_global: bool = True,
|
||||
) -> dict:
|
||||
base = _not_forgotten_filter(
|
||||
project, include_idea_targets=include_idea_targets, read_scopes=read_scopes
|
||||
project,
|
||||
include_idea_targets=include_idea_targets,
|
||||
read_scopes=read_scopes,
|
||||
include_global=include_global,
|
||||
)
|
||||
base["$and"].append(_head_clause())
|
||||
return base
|
||||
|
|
@ -982,6 +1004,7 @@ def index_lines(
|
|||
project: str | None = None,
|
||||
limit: int = 30,
|
||||
read_scopes: tuple[ReadScope, ...] | list[ReadScope] | None = None,
|
||||
include_global: bool = True,
|
||||
) -> list[str]:
|
||||
now = time.time()
|
||||
fields = {
|
||||
|
|
@ -997,7 +1020,7 @@ def index_lines(
|
|||
# `idea`-Einträge haben ihren eigenen Block (siehe idea_lines) und ihr eigenes
|
||||
# festes Limit; sie hier auszuschließen gibt dem Wissensindex sein volles
|
||||
# Budget zurück und verhindert eine doppelte Anzeige.
|
||||
query = _base_filter(project, read_scopes=read_scopes)
|
||||
query = _base_filter(project, read_scopes=read_scopes, include_global=include_global)
|
||||
query["$and"].append({"type": {"$ne": "idea"}})
|
||||
candidates = list(
|
||||
db.observations.find(query, fields)
|
||||
|
|
@ -1238,6 +1261,7 @@ def search(
|
|||
since_days: float | None = None,
|
||||
include_pending: bool = False,
|
||||
read_scopes: tuple[ReadScope, ...] | list[ReadScope] | None = None,
|
||||
include_global: bool = True,
|
||||
) -> list[str]:
|
||||
"""Volltextsuche mit optionalen Filtern und Hybrid-Ranking.
|
||||
|
||||
|
|
@ -1252,11 +1276,15 @@ def search(
|
|||
include_pending=True,
|
||||
include_idea_targets=True,
|
||||
read_scopes=read_scopes,
|
||||
include_global=include_global,
|
||||
)
|
||||
filter_["$and"].append(_head_clause())
|
||||
else:
|
||||
filter_ = _base_filter(
|
||||
project, include_idea_targets=True, read_scopes=read_scopes
|
||||
project,
|
||||
include_idea_targets=True,
|
||||
read_scopes=read_scopes,
|
||||
include_global=include_global,
|
||||
)
|
||||
search_terms = synonyms.expand_query(query) if SEARCH_EXPAND_SYNONYMS else query
|
||||
filter_["$text"] = {"$search": search_terms}
|
||||
|
|
@ -1339,12 +1367,14 @@ def get(
|
|||
expand: bool = True,
|
||||
reinforce: bool = True,
|
||||
read_scopes: tuple[ReadScope, ...] | list[ReadScope] | None = None,
|
||||
include_global: bool = True,
|
||||
) -> list[dict]:
|
||||
query = _not_forgotten_filter(
|
||||
project,
|
||||
include_pending=True,
|
||||
include_idea_targets=True,
|
||||
read_scopes=read_scopes,
|
||||
include_global=include_global,
|
||||
)
|
||||
query["$and"].append({"_id": {"$in": ids}})
|
||||
docs = list(db.observations.find(query).max_time_ms(5000))
|
||||
|
|
@ -1458,6 +1488,7 @@ def idea_lines(
|
|||
project: str,
|
||||
limit: int = IDEA_BLOCK_LIMIT,
|
||||
read_scopes: tuple[ReadScope, ...] | list[ReadScope] | None = None,
|
||||
include_global: bool = True,
|
||||
) -> list[str]:
|
||||
"""Offene `idea`-Einträge für dieses Projekt — eigene, geborene wie über
|
||||
`for:<slug>` zugeordnete aus anderen Projekten (siehe docs/plan-idea-type.md).
|
||||
|
|
@ -1467,7 +1498,10 @@ def idea_lines(
|
|||
ungelesene Idee naturgemäß access_count=0 hat.
|
||||
"""
|
||||
query = _base_filter(
|
||||
project, include_idea_targets=True, read_scopes=read_scopes
|
||||
project,
|
||||
include_idea_targets=True,
|
||||
read_scopes=read_scopes,
|
||||
include_global=include_global,
|
||||
)
|
||||
query["$and"].append({"type": "idea"})
|
||||
docs = list(
|
||||
|
|
@ -1502,6 +1536,7 @@ def start_context(
|
|||
project: str | None,
|
||||
budget: int,
|
||||
read_scopes: tuple[ReadScope, ...] | list[ReadScope] | None = None,
|
||||
include_global: bool = True,
|
||||
) -> str | None:
|
||||
"""Gemeinsamer SessionStart-Aufbau für stdio- und HTTP-Transport.
|
||||
|
||||
|
|
@ -1512,9 +1547,14 @@ def start_context(
|
|||
trotzdem sichtbar, ohne deren Inhalt preiszugeben (siehe
|
||||
``child_pending_reminder_line``).
|
||||
"""
|
||||
lines = index_lines(db, project=project, limit=budget, read_scopes=read_scopes)
|
||||
lines = index_lines(
|
||||
db, project=project, limit=budget, read_scopes=read_scopes,
|
||||
include_global=include_global,
|
||||
)
|
||||
idea_block = (
|
||||
idea_lines(db, project=project, read_scopes=read_scopes)
|
||||
idea_lines(
|
||||
db, project=project, read_scopes=read_scopes, include_global=include_global,
|
||||
)
|
||||
if project is not None else []
|
||||
)
|
||||
pending_reminder = pending_reminder_line(db, project=project) if project is not None else None
|
||||
|
|
@ -2538,10 +2578,10 @@ def _count_with_timeout(db, filter_: dict) -> int | None:
|
|||
return None
|
||||
|
||||
|
||||
def stats(db, *, project: str | None = None) -> dict:
|
||||
def stats(db, *, project: str | None = None, include_global: bool = True) -> dict:
|
||||
now = time.time()
|
||||
scope = _project_clause(project)
|
||||
active_filter = _base_filter(project)
|
||||
scope = _project_clause(project, include_global=include_global)
|
||||
active_filter = _base_filter(project, include_global=include_global)
|
||||
archived_filter = {**scope, "archived": True}
|
||||
pending_filter = {
|
||||
"project": project,
|
||||
|
|
|
|||
|
|
@ -253,6 +253,35 @@ class TestProjectRegistry(RegistryMixin, unittest.TestCase):
|
|||
with self.assertRaises(auth.AuthConfigurationError):
|
||||
auth.ProjectRegistry.load(self.registry_path)
|
||||
|
||||
def test_include_global_defaults_to_true(self):
|
||||
registry = auth.ProjectRegistry.load(self.registry_path)
|
||||
self.assertTrue(registry.project(SLUG).include_global)
|
||||
|
||||
def test_include_global_false_is_parsed(self):
|
||||
data = _registry_data()
|
||||
data["projects"][SLUG]["include_global"] = False
|
||||
self.write_registry(data)
|
||||
registry = auth.ProjectRegistry.load(self.registry_path)
|
||||
self.assertFalse(registry.project(SLUG).include_global)
|
||||
|
||||
def test_rejects_non_boolean_include_global(self):
|
||||
for bad in ("no", 0, 1, None, []):
|
||||
with self.subTest(value=bad):
|
||||
data = _registry_data()
|
||||
data["projects"][SLUG]["include_global"] = bad
|
||||
self.write_registry(data)
|
||||
with self.assertRaises(auth.AuthConfigurationError):
|
||||
auth.ProjectRegistry.load(self.registry_path)
|
||||
|
||||
def test_subproject_inherits_include_global_false(self):
|
||||
data = _registry_data()
|
||||
data["projects"][SLUG]["allow_subprojects"] = True
|
||||
data["projects"][SLUG]["include_global"] = False
|
||||
self.write_registry(data)
|
||||
registry = auth.ProjectRegistry.load(self.registry_path)
|
||||
sub = registry.resolve_subproject(SLUG, ("srv",), SUB, CLIENT_ID)
|
||||
self.assertFalse(sub.include_global)
|
||||
|
||||
def test_requires_exact_0600_permissions(self):
|
||||
self.registry_path.chmod(0o640)
|
||||
with self.assertRaises(auth.AuthConfigurationError):
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ werden vollstaendig durch Fakes beziehungsweise gezielte Store-Mocks ersetzt.
|
|||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import json
|
||||
import sys
|
||||
import tempfile
|
||||
|
|
@ -449,6 +450,14 @@ def _write_registry(path: Path, *, allow_subprojects: bool) -> None:
|
|||
path.chmod(0o600)
|
||||
|
||||
|
||||
def _write_registry_projects(path: Path, projects: dict) -> None:
|
||||
path.write_text(json.dumps({"version": 1, "projects": projects}), encoding="utf-8")
|
||||
path.chmod(0o600)
|
||||
|
||||
|
||||
_PRINCIPALS = [{"sub": "user-123", "client_id": "codex-client"}]
|
||||
|
||||
|
||||
class TestParseMcpPath(unittest.TestCase):
|
||||
"""Direct, network-free tests for the path-splitting helper.
|
||||
|
||||
|
|
@ -621,6 +630,169 @@ class TestSubprojectsDisabled(_ServerTestCase):
|
|||
self.assertEqual(status, 200)
|
||||
|
||||
|
||||
class _RegistryServerCase(_ServerTestCase):
|
||||
"""Basisklasse: startet den Server gegen eine echte, aus ``PROJECTS`` geladene Registry."""
|
||||
|
||||
PROJECTS: dict = {}
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls._tmp = tempfile.TemporaryDirectory()
|
||||
registry_path = Path(cls._tmp.name) / "projects.json"
|
||||
_write_registry_projects(registry_path, cls.PROJECTS)
|
||||
cls.registry = auth.ProjectRegistry.load(registry_path)
|
||||
cls.authenticator = _FakeAuthenticator()
|
||||
cls.config = _auth_config()
|
||||
cls.httpd, cls.base, cls.thread = _serve(
|
||||
authenticator=cls.authenticator,
|
||||
auth_config=cls.config,
|
||||
project_registry=cls.registry,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
super().tearDownClass()
|
||||
cls._tmp.cleanup()
|
||||
|
||||
def setUp(self):
|
||||
self.authenticator.scopes = ALL_TEST_SCOPES
|
||||
http_server.clear_subproject_cache()
|
||||
|
||||
def _context(self, path: str, request_id: int = 1, db=None):
|
||||
captured = {}
|
||||
|
||||
def fake_call_tool(name, args, context=None):
|
||||
captured["context"] = context
|
||||
return "ok"
|
||||
|
||||
patches = [mock.patch.object(server, "_call_tool", side_effect=fake_call_tool)]
|
||||
if db is not None:
|
||||
patches.append(mock.patch.object(server, "_get_db", return_value=db))
|
||||
with contextlib.ExitStack() as stack:
|
||||
for patch in patches:
|
||||
stack.enter_context(patch)
|
||||
status, _, _ = _post(self.base, {
|
||||
"jsonrpc": "2.0", "id": request_id, "method": "tools/call",
|
||||
"params": {"name": "memory_stats", "arguments": {}},
|
||||
}, path=path)
|
||||
self.assertEqual(status, 200)
|
||||
return captured["context"]
|
||||
|
||||
|
||||
class TestIncludeGlobalDisabled(_RegistryServerCase):
|
||||
PROJECTS = {SLUG: {
|
||||
"project_id": PROJECT_ID,
|
||||
"allowed_principals": _PRINCIPALS,
|
||||
"allow_subprojects": True,
|
||||
"include_global": False,
|
||||
}}
|
||||
|
||||
def test_root_context_carries_false(self):
|
||||
self.assertIs(self._context(f"/mcp/{SLUG}")["include_global"], False)
|
||||
|
||||
def test_subscope_inherits_false(self):
|
||||
self.assertIs(self._context(f"/mcp/{SLUG}/srv", 2)["include_global"], False)
|
||||
|
||||
def test_hook_start_forwards_false(self):
|
||||
with mock.patch.object(server, "_get_db", return_value=object()), \
|
||||
mock.patch.object(store, "start_context", return_value="") as start:
|
||||
status, _, _ = _post(
|
||||
self.base, {"context_remaining_pct": 42},
|
||||
path=f"/hooks/{SLUG}/start", token=OAUTH_TOKEN,
|
||||
)
|
||||
self.assertEqual(status, 200)
|
||||
self.assertIs(start.call_args.kwargs["include_global"], False)
|
||||
|
||||
|
||||
class TestIncludeGlobalDefault(_RegistryServerCase):
|
||||
PROJECTS = {SLUG: {"project_id": PROJECT_ID, "allowed_principals": _PRINCIPALS}}
|
||||
|
||||
def test_context_defaults_to_true(self):
|
||||
self.assertIs(self._context(f"/mcp/{SLUG}")["include_global"], True)
|
||||
|
||||
def test_hook_start_defaults_to_true(self):
|
||||
with mock.patch.object(server, "_get_db", return_value=object()), \
|
||||
mock.patch.object(store, "start_context", return_value="") as start:
|
||||
_post(
|
||||
self.base, {"context_remaining_pct": 42},
|
||||
path=f"/hooks/{SLUG}/start", token=OAUTH_TOKEN,
|
||||
)
|
||||
self.assertIs(start.call_args.kwargs["include_global"], True)
|
||||
|
||||
|
||||
class TestReadChildrenSubscopes(_RegistryServerCase):
|
||||
"""``read_children`` auf einen ``allow_subprojects``-Slug macht auch dessen Subscopes lesbar."""
|
||||
|
||||
PROJECTS = {
|
||||
SLUG: {
|
||||
"project_id": PROJECT_ID,
|
||||
"allowed_principals": _PRINCIPALS,
|
||||
"read_children": ["parent"],
|
||||
},
|
||||
"parent": {
|
||||
"project_id": "repo:parent",
|
||||
"allowed_principals": [{"sub": "other", "client_id": "other-client"}],
|
||||
"allow_subprojects": True,
|
||||
},
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _db(*project_ids):
|
||||
return SimpleNamespace(observations=SimpleNamespace(
|
||||
distinct=lambda field, query: list(project_ids),
|
||||
))
|
||||
|
||||
def test_child_slug_subscopes_are_readable_with_prefixed_labels(self):
|
||||
db = self._db("repo:parent/srv", "repo:parent/git/tool")
|
||||
context = self._context(f"/mcp/{SLUG}", 1, db=db)
|
||||
by_project = {item.project: item for item in context["read_scopes"]}
|
||||
self.assertEqual(
|
||||
set(by_project),
|
||||
{PROJECT_ID, "repo:parent", "repo:parent/srv", "repo:parent/git/tool"},
|
||||
)
|
||||
self.assertEqual(by_project["repo:parent/srv"].label, "parent/srv")
|
||||
self.assertEqual(by_project["repo:parent/git/tool"].label, "parent/git/tool")
|
||||
self.assertFalse(by_project["repo:parent/srv"].current)
|
||||
self.assertTrue(by_project[PROJECT_ID].current)
|
||||
|
||||
def test_child_subscopes_do_not_grant_subscope_root_or_write_target(self):
|
||||
context = self._context(f"/mcp/{SLUG}", 2, db=self._db("repo:parent/srv"))
|
||||
# Der eigene Slug hat kein allow_subprojects -> keine frei waehlbaren Subscopes.
|
||||
self.assertIsNone(context["subscope_root"])
|
||||
self.assertEqual(context["project"], PROJECT_ID)
|
||||
|
||||
def test_subscope_connection_still_sees_only_itself(self):
|
||||
# /mcp/<slug>/<sub> verlangt allow_subprojects am eigenen Slug -> 403 ohne.
|
||||
status, _, _ = _post(
|
||||
self.base, {"jsonrpc": "2.0", "id": 3, "method": "ping"}, path=f"/mcp/{SLUG}/srv",
|
||||
)
|
||||
self.assertEqual(status, 403)
|
||||
|
||||
|
||||
class TestReadChildrenWithoutSubprojects(_RegistryServerCase):
|
||||
PROJECTS = {
|
||||
SLUG: {
|
||||
"project_id": PROJECT_ID,
|
||||
"allowed_principals": _PRINCIPALS,
|
||||
"read_children": ["parent"],
|
||||
},
|
||||
"parent": {
|
||||
"project_id": "repo:parent",
|
||||
"allowed_principals": [{"sub": "other", "client_id": "other-client"}],
|
||||
},
|
||||
}
|
||||
|
||||
def test_no_discovery_for_child_without_allow_subprojects(self):
|
||||
def boom(field, query):
|
||||
raise AssertionError("Subscope-Discovery darf nicht laufen")
|
||||
|
||||
db = SimpleNamespace(observations=SimpleNamespace(distinct=boom))
|
||||
context = self._context(f"/mcp/{SLUG}", 1, db=db)
|
||||
self.assertEqual(
|
||||
{item.project for item in context["read_scopes"]}, {PROJECT_ID, "repo:parent"},
|
||||
)
|
||||
|
||||
|
||||
class TestRemoteHookRoutes(_ServerTestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
|
|
|
|||
|
|
@ -211,6 +211,49 @@ class TestResolveTargetProject(unittest.TestCase):
|
|||
server._resolve_target_project(
|
||||
requested, str(root), (), None, str(root))
|
||||
|
||||
def test_mutation_allows_session_and_scopes_below_it(self):
|
||||
scopes = (
|
||||
server.scope.ReadScope("/proj/a", ".", 0, True),
|
||||
server.scope.ReadScope("/proj/a/child", "child", 1),
|
||||
)
|
||||
self.assertEqual(
|
||||
server._resolve_target_project(
|
||||
"child", "/proj/a", scopes, for_mutation=True),
|
||||
"/proj/a/child",
|
||||
)
|
||||
self.assertEqual(
|
||||
server._resolve_target_project(
|
||||
"/proj/a", "/proj/a", scopes, for_mutation=True),
|
||||
"/proj/a",
|
||||
)
|
||||
|
||||
def test_mutation_rejects_read_only_foreign_scope(self):
|
||||
# read_children: fremder Slug ist lesbar, aber nicht kuratierbar.
|
||||
scopes = (
|
||||
server.scope.ReadScope("/proj/chatgpt", ".", 0, True),
|
||||
server.scope.ReadScope("/proj/web", "mongomind", 1),
|
||||
server.scope.ReadScope("/proj/web/git", "mongomind/git", 2),
|
||||
)
|
||||
for requested in ("mongomind", "/proj/web", "mongomind/git", "/proj/web/git"):
|
||||
with self.subTest(requested=requested):
|
||||
# Lesen bleibt erlaubt ...
|
||||
self.assertIn(
|
||||
server._resolve_target_project(requested, "/proj/chatgpt", scopes),
|
||||
{"/proj/web", "/proj/web/git"},
|
||||
)
|
||||
# ... Kuratieren nicht.
|
||||
with self.assertRaises(ValueError):
|
||||
server._resolve_target_project(
|
||||
requested, "/proj/chatgpt", scopes, for_mutation=True)
|
||||
|
||||
def test_mutation_prefix_match_is_path_segment_exact(self):
|
||||
scopes = (
|
||||
server.scope.ReadScope("/proj/a", ".", 0, True),
|
||||
server.scope.ReadScope("/proj/abc", "abc", 1),
|
||||
)
|
||||
with self.assertRaises(ValueError):
|
||||
server._resolve_target_project("abc", "/proj/a", scopes, for_mutation=True)
|
||||
|
||||
def test_local_root_only_for_stdio_sessions(self):
|
||||
self.assertEqual(server._local_root("/proj/a", None), "/proj/a")
|
||||
self.assertIsNone(server._local_root("/proj/a", {"read_scopes": ()}))
|
||||
|
|
@ -396,6 +439,105 @@ class TestValidation(unittest.TestCase):
|
|||
})
|
||||
|
||||
|
||||
class TestIncludeGlobalDispatch(unittest.TestCase):
|
||||
"""Registry-Flag ``include_global`` -- reine Dispatch-Verdrahtung, keine DB."""
|
||||
|
||||
CONTEXT = {"project": "/proj/chatgpt", "read_scopes": (), "origin_client": "chatgpt-client"}
|
||||
ABSENT = object()
|
||||
|
||||
def _patched(self):
|
||||
return mock.patch.multiple(
|
||||
server,
|
||||
_get_db=mock.Mock(return_value=object()),
|
||||
)
|
||||
|
||||
def _call(self, tool, args, store_name, include_global, return_value):
|
||||
context = dict(self.CONTEXT)
|
||||
if include_global is not self.ABSENT:
|
||||
context["include_global"] = include_global
|
||||
with self._patched(), \
|
||||
mock.patch.object(server.store, store_name, return_value=return_value) as mocked:
|
||||
try:
|
||||
server._call_tool(tool, args, context)
|
||||
except Exception: # Antwortformatierung ist hier nicht Gegenstand
|
||||
pass
|
||||
return mocked.call_args.kwargs.get("include_global")
|
||||
|
||||
def test_flag_is_forwarded_to_every_read_tool(self):
|
||||
cases = (
|
||||
("memory_index", {}, "index_lines", []),
|
||||
("memory_search", {"query": "x"}, "search", []),
|
||||
("memory_get", {"ids": [1]}, "get", []),
|
||||
("memory_stats", {}, "stats", {
|
||||
"active": 0, "pending": 0, "archived": 0, "most_used": [],
|
||||
}),
|
||||
)
|
||||
for tool, args, store_name, ret in cases:
|
||||
with self.subTest(tool=tool):
|
||||
self.assertIs(self._call(tool, args, store_name, False, ret), False)
|
||||
self.assertIs(self._call(tool, args, store_name, True, ret), True)
|
||||
|
||||
def test_missing_key_defaults_to_true(self):
|
||||
self.assertIs(self._call("memory_index", {}, "index_lines", self.ABSENT, []), True)
|
||||
|
||||
def test_non_boolean_value_fails_closed(self):
|
||||
for bad in ("false", 0, 1, None, "yes"):
|
||||
with self.subTest(value=bad):
|
||||
self.assertIs(self._call("memory_index", {}, "index_lines", bad, []), False)
|
||||
|
||||
def test_stdio_context_without_flag_is_unchanged(self):
|
||||
self.assertTrue(server._include_global(None))
|
||||
self.assertTrue(server._include_global({}))
|
||||
|
||||
def test_global_write_is_refused_even_with_env_and_scope(self):
|
||||
context = {
|
||||
"include_global": False,
|
||||
"scopes": {server.SCOPE_WRITE, server.SCOPE_GLOBAL_WRITE},
|
||||
}
|
||||
with mock.patch.dict(os.environ, {"MONGOMIND_ALLOW_GLOBAL_WRITE": "1"}):
|
||||
with self.assertRaisesRegex(PermissionError, "deaktiviert"):
|
||||
server._project_for_authorized("global", "/proj/chatgpt", context)
|
||||
|
||||
def test_global_write_still_works_with_default_flag(self):
|
||||
context = {"scopes": {server.SCOPE_WRITE, server.SCOPE_GLOBAL_WRITE}}
|
||||
with mock.patch.dict(os.environ, {"MONGOMIND_ALLOW_GLOBAL_WRITE": "1"}):
|
||||
self.assertIsNone(server._project_for_authorized("global", "/proj/a", context))
|
||||
|
||||
def test_project_scope_save_is_unaffected_by_flag(self):
|
||||
self.assertEqual(
|
||||
server._project_for_authorized(
|
||||
"project", "/proj/chatgpt", {"include_global": False}),
|
||||
"/proj/chatgpt",
|
||||
)
|
||||
|
||||
def test_consolidate_refuses_read_only_foreign_scope(self):
|
||||
scopes = (
|
||||
server.scope.ReadScope("/proj/chatgpt", ".", 0, True),
|
||||
server.scope.ReadScope("/proj/web", "mongomind", 1),
|
||||
)
|
||||
context = dict(self.CONTEXT, read_scopes=scopes)
|
||||
with self._patched(), \
|
||||
mock.patch.object(server.store, "consolidate") as consolidate:
|
||||
with self.assertRaisesRegex(ValueError, "nicht kuratiert"):
|
||||
server._call_tool(
|
||||
"memory_consolidate",
|
||||
{"source_ids": [1], "title": "t", "content": "c", "project": "mongomind"},
|
||||
context,
|
||||
)
|
||||
consolidate.assert_not_called()
|
||||
|
||||
def test_memory_pending_may_still_read_foreign_scope(self):
|
||||
scopes = (
|
||||
server.scope.ReadScope("/proj/chatgpt", ".", 0, True),
|
||||
server.scope.ReadScope("/proj/web", "mongomind", 1),
|
||||
)
|
||||
context = dict(self.CONTEXT, read_scopes=scopes)
|
||||
with self._patched(), \
|
||||
mock.patch.object(server.store, "pending_lines", return_value=[]) as pending:
|
||||
server._call_tool("memory_pending", {"project": "mongomind"}, context)
|
||||
self.assertEqual(pending.call_args.kwargs["project"], "/proj/web")
|
||||
|
||||
|
||||
class TestOAuthScopes(unittest.TestCase):
|
||||
def test_visible_tools_are_filtered_by_scope(self):
|
||||
names = {
|
||||
|
|
|
|||
|
|
@ -1920,5 +1920,115 @@ class TestE2ETestCaseUsage(unittest.TestCase):
|
|||
)
|
||||
|
||||
|
||||
class TestIncludeGlobal(E2ETestCase):
|
||||
"""Registry-Flag ``include_global=False``: kein Lese-/Schreibpfad erreicht ``project: None``."""
|
||||
|
||||
PROJECT = "/proj/chatgpt"
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.own = store.save(
|
||||
self.db, title="Eigener quokka Eintrag", content="quokka gehoert chatgpt.",
|
||||
project=self.PROJECT,
|
||||
)["id"]
|
||||
self.global_note = store.save(
|
||||
self.db, title="Globaler quokka Eintrag", content="quokka gilt ueberall.",
|
||||
project=None,
|
||||
)["id"]
|
||||
self.global_idea = store.save(
|
||||
self.db, title="Globale quokka Idee", content="quokka Idee fuer chatgpt.",
|
||||
type="idea", project=None, tags=["for:chatgpt"],
|
||||
)["id"]
|
||||
self.foreign_idea = store.save(
|
||||
self.db, title="Fremde quokka Idee", content="quokka Idee aus anderem Projekt.",
|
||||
type="idea", project="/proj/other", tags=["for:chatgpt"],
|
||||
)["id"]
|
||||
|
||||
@staticmethod
|
||||
def _ids(lines):
|
||||
return {int(line.split()[0].lstrip("#")) for line in lines if line.startswith("#")}
|
||||
|
||||
def test_index_hides_global_only_when_disabled(self):
|
||||
hidden = self._ids(store.index_lines(
|
||||
self.db, project=self.PROJECT, include_global=False))
|
||||
self.assertEqual(hidden, {self.own})
|
||||
shown = self._ids(store.index_lines(self.db, project=self.PROJECT))
|
||||
self.assertIn(self.global_note, shown)
|
||||
|
||||
def test_search_hides_global_only_when_disabled(self):
|
||||
for include_pending in (False, True):
|
||||
with self.subTest(include_pending=include_pending):
|
||||
hidden = self._ids(store.search(
|
||||
self.db, "quokka", project=self.PROJECT,
|
||||
include_pending=include_pending, include_global=False))
|
||||
self.assertEqual(hidden, {self.own})
|
||||
shown = self._ids(store.search(
|
||||
self.db, "quokka", project=self.PROJECT, include_pending=include_pending))
|
||||
self.assertTrue({self.own, self.global_note} <= shown)
|
||||
|
||||
def test_ideas_hide_global_and_foreign_delegations_when_disabled(self):
|
||||
hidden = self._ids(store.idea_lines(
|
||||
self.db, project=self.PROJECT, include_global=False))
|
||||
self.assertEqual(hidden, set())
|
||||
shown = self._ids(store.idea_lines(self.db, project=self.PROJECT))
|
||||
self.assertTrue({self.global_idea, self.foreign_idea} <= shown)
|
||||
|
||||
def test_get_by_id_cannot_reach_global_entries_when_disabled(self):
|
||||
ids = [self.own, self.global_note, self.global_idea, self.foreign_idea]
|
||||
hidden = store.get(
|
||||
self.db, ids, project=self.PROJECT, reinforce=False, include_global=False)
|
||||
self.assertEqual({doc["id"] for doc in hidden}, {self.own})
|
||||
shown = store.get(self.db, ids, project=self.PROJECT, reinforce=False)
|
||||
self.assertTrue({self.global_note, self.global_idea} <= {doc["id"] for doc in shown})
|
||||
|
||||
def test_start_context_hides_global_when_disabled(self):
|
||||
hidden = store.start_context(
|
||||
self.db, project=self.PROJECT, budget=2000, include_global=False) or ""
|
||||
self.assertIn("Eigener quokka", hidden)
|
||||
self.assertNotIn("Globaler quokka", hidden)
|
||||
self.assertNotIn("Globale quokka Idee", hidden)
|
||||
self.assertNotIn("Fremde quokka Idee", hidden)
|
||||
shown = store.start_context(self.db, project=self.PROJECT, budget=2000) or ""
|
||||
self.assertIn("Globaler quokka", shown)
|
||||
|
||||
def test_stats_count_only_own_entries_when_disabled(self):
|
||||
# most_used listet nur Eintraege mit access_count > 0.
|
||||
self.db.observations.update_one({"_id": self.own}, {"$set": {"access_count": 2}})
|
||||
self.db.observations.update_one({"_id": self.global_note}, {"$set": {"access_count": 9}})
|
||||
hidden = store.stats(self.db, project=self.PROJECT, include_global=False)
|
||||
self.assertEqual(hidden["active"], 1)
|
||||
self.assertEqual(
|
||||
[entry.split()[0] for entry in hidden["most_used"]], [f"#{self.own}"])
|
||||
shown = store.stats(self.db, project=self.PROJECT)
|
||||
self.assertGreaterEqual(shown["active"], 3)
|
||||
self.assertEqual(shown["most_used"][0].split()[0], f"#{self.global_note}")
|
||||
|
||||
def test_scope_without_projects_still_excludes_global_when_disabled(self):
|
||||
# Verteidigung in der Tiefe: kein Projekt -> frueher "alles", jetzt nie project=None.
|
||||
self.assertEqual(
|
||||
store._project_clause(None, include_global=False), {"project": {"$ne": None}})
|
||||
self.assertEqual(store._project_clause(None), {})
|
||||
|
||||
def test_global_idea_with_for_tag_cannot_be_forgotten_or_superseded_from_project(self):
|
||||
self.assertEqual(store.forget(self.db, [self.global_idea], project=self.PROJECT), 0)
|
||||
self.assertFalse(self.db.observations.find_one({"_id": self.global_idea})["archived"])
|
||||
with self.assertRaises(ValueError):
|
||||
store.save(
|
||||
self.db, title="Ersatz", content="Soll scheitern.", type="idea",
|
||||
project=self.PROJECT, supersedes=self.global_idea)
|
||||
|
||||
def test_foreign_delegated_idea_can_still_be_closed_by_default(self):
|
||||
# Regression: die bestehende for:-Delegation (docs/plan-idea-type.md) bleibt erhalten.
|
||||
self.assertEqual(store.forget(self.db, [self.foreign_idea], project=self.PROJECT), 1)
|
||||
|
||||
def test_export_contains_no_global_records(self):
|
||||
with tempfile.TemporaryDirectory() as tmp, \
|
||||
mock.patch.object(store, "EXPORT_DIR", Path(tmp)):
|
||||
result = store.export(self.db, project=self.PROJECT)
|
||||
payload = Path(result["path"]).read_text(encoding="utf-8")
|
||||
self.assertIn("Eigener quokka", payload)
|
||||
self.assertNotIn("Globaler quokka", payload)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
|
|||
Loading…
Reference in a new issue