Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 44 additions & 3 deletions docs/experiment-packages.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,44 @@ ASAREE records are read under one repeatable-read snapshot. Motoro resources use
a separate snapshot; filesystem captures verify opened files and detect tree
changes. Mutable external knowledge has no cross-file transaction or historical
snapshot. The manifest records this limitation rather than claiming publication
fidelity. Externally registered directories must be authorized through ownership
and isolated from platform storage; broad roots, other owners' knowledge,
symlinks and ambiguous overlaps are reported as unresolved dependencies.
fidelity. Uploaded bundles and documents use the application's per-owner storage
boundary. An external registration or shared browse access alone does not prove
authority to download the registered directory. Broad roots, other owners'
knowledge, symlinks and ambiguous overlaps are unresolved dependencies.

### External knowledge export grants

Operators can authorize a specific external bundle for a user with the
`knowledge_export_grants` setting, supplied as JSON through
`ASAREE_KNOWLEDGE_EXPORT_GRANTS`, for example:

```json
{"00000000-0000-0000-0000-000000000001":["/srv/research/approved-cohort-bundle"]}
```

The key is the application user's UUID. Each absolute path must match the
registered bundle root exactly; there is no implicit grant to descendants or
ancestors. A grant is the operator's assertion that **all content under that
exact root is authorized for that user**. It is not inferred from filesystem
ownership, a registration's owner field, or absence of competing registrations.
Configure only narrow named bundle roots after reviewing their full contents.

Grants support isolated legacy bundles outside today's browse root without
moving or adopting their files. They do not override rejection of the shared
browse root/its ancestors, platform-storage overlaps, or foreign/ownerless
knowledge registrations and other users' grants that overlap in either direction
or exactly. Missing or malformed grants, unreadable registration evidence and
ambiguous knowledge boundaries are reported as unresolved before content capture;
diagnostics do not expose another owner's identifiers, paths, commands or bytes.

Set the same configuration on the API and worker processes, particularly
`asaree-results-worker`, which builds packages. In the supplied Compose setup,
the configured environment file is already forwarded to `asaree-app`,
`asaree-worker`, and `asaree-results-worker`; a host-shell variable alone is not
automatically forwarded. Deployment overrides can set the JSON value in those
services' `environment` mappings. External paths must be mounted consistently
in the exporting worker. No grant is required for authorized uploaded bundles
and documents, and this correction changes no database schema or package format.

Credential/connection fields, including typed fallback and sampling snapshot
fields, and recognized credential files are excluded. Dataset bytes, prompts,
Expand All @@ -78,6 +113,12 @@ without publication attribution are not assigned to historical versions; the
dependency inventory records unavailable or unscoped evidence.
AgentRun IDs in node evidence are source provenance; native Motoro step history
and resume/control snapshots are not bundled.
Workspace scratch is recognized structurally at `.scratch/` under the workspace
root or its `dataset=`/`agent=` slots. User artifacts such as
`outputs/working/prediction.csv`, `outputs/cache/`, `outputs/scratch/`, and
`outputs/.scratch/` remain durable content. Temporary preparation names use the
reserved hidden producer naming pattern; an ordinary `results.preparing/`
output directory is preserved.

Archive generation streams file bytes and SQL evidence slices, spools inventories
to plain files, and discards tar member metadata after writing. Memory does not
Expand Down
6 changes: 6 additions & 0 deletions src/asaree/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from __future__ import annotations

from pathlib import Path
from uuid import UUID

from motoro import CoreSettings
from pydantic import Field, model_validator
Expand Down Expand Up @@ -84,6 +85,11 @@ class AsareeSettings(CoreSettings):
# deliberately so: nothing here tunnels to a client machine.
okf_bundle_root: str = "~"

# Operator-approved exact external bundle roots per application owner.
# Registration/browse access is not authority to download a whole external
# tree. No implicit subtree grants; managed owner uploads need no entry.
knowledge_export_grants: dict[UUID, list[Path]] = Field(default_factory=dict)

# Where UPLOADED single-concept OKF documents are stored (POST
# /okf/documents -- services/okf_documents.py). Deliberately NOT inside
# okf_bundle_root: that root is the jail for paths a user *picks*, and
Expand Down
83 changes: 73 additions & 10 deletions src/asaree/services/experiment_packages.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,11 @@
from motoro.models.skill import Skill, SkillFile
from motoro.services.skill_service import render_skill_md
from sqlalchemy import Text, cast, func, select, update
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import noload

from asaree.config import get_settings
from asaree.models.database import get_session
from asaree.models.dataset import RegisteredDataset
from asaree.models.dataset_split import DatasetArtifact, DatasetSplit
Expand Down Expand Up @@ -547,8 +549,8 @@ async def _server(db: AsyncSession, writer: PackageWriter, config: dict[str, Any
if raw is None:
raise ValueError("Missing knowledge directory")
root = Path(raw)
# Registration ownership grants access, never infer ownership from
# filesystem containment. External bundles also stay inside root.
# An owned registration identifies the requested bundle, but does
# not authorize arbitrary trees in the shared external browse jail.
if server.name.startswith(okf_bundles.BUNDLE_SERVER_NAME_PREFIX):
managed = bool(server.command and "managed://bundles/" in server.command)
allowed = okf_bundles.owner_upload_root(owner) if managed else okf_bundles.bundle_root()
Expand All @@ -562,36 +564,94 @@ async def _server(db: AsyncSession, writer: PackageWriter, config: dict[str, Any
okf_bundles.owner_upload_root(owner), okf_documents.owner_root(owner),
) if root.resolve().is_relative_to(candidate.resolve())), None)
validate_knowledge_root(root, owner_storage or allowed, external=owner_storage is None)
await authorize_knowledge_export(db, root, owner, external=owner_storage is None)
await archive_io(writer, capture_tree, writer, root, directory, server_id)
writer.dependency(server_id, "knowledge", "captured_at_download", directory=directory,
note="Mutable content captured now; no historical snapshot or cross-file transaction.")
except (OSError, ValueError):
except (OSError, ValueError, SQLAlchemyError):
writer.dependency(server_id, "knowledge", "captured_at_download", status="unresolved",
reason="Unavailable, unauthorized, unsafe or concurrently changed knowledge content.")


def validate_knowledge_root(root: Path, allowed: Path, *, external: bool) -> None:
"""Owned registration is necessary, but cannot grant a platform-root dump.
"""Reject unsafe storage geometry; this does not establish authority.

Legacy external bundles outside today's browse root remain exportable when
isolated from platform storage. Never infer external ownership from location.
External authorization also requires an exact operator grant and unambiguous
registration boundaries, checked before capture by the caller.
"""
resolved = root.resolve()
roots = managed_storage.roots()
if root.is_symlink():
raise ValueError("Knowledge root is a symlink")
if not external and not resolved.is_relative_to(allowed.resolve()):
raise ValueError("Knowledge directory outside owner storage")
if external and (resolved == allowed.resolve() or resolved in allowed.resolve().parents):
raise ValueError("Knowledge directory covers the shared browse root")
for namespace, platform_root in roots.items():
platform_root = platform_root.resolve()
if namespace in {"bundles", "documents"} and not external:
if (namespace in {"bundles", "documents"} and not external
and allowed.parent.resolve() == platform_root and resolved.is_relative_to(allowed.resolve())):
continue
if resolved == platform_root or resolved in platform_root.parents or platform_root in resolved.parents:
raise ValueError("Knowledge registration overlaps platform storage")
if resolved == Path(resolved.anchor):
raise ValueError("Knowledge registration points to filesystem root")


def paths_overlap(first: Path, second: Path) -> bool:
return first == second or first in second.parents or second in first.parents


async def authorize_knowledge_export(db: AsyncSession, root: Path, owner: uuid.UUID, *, external: bool) -> None:
"""Prove a boundary before any bytes enter the archive.

Managed ownership comes from the application's UUID-partitioned upload
roots. External ownership requires an operator grant: an owned MCP row and
absence of competing registrations alone do not prove filesystem authority.
All checks use the resource-capture transaction; foreign details stay local.
"""
resolved = root.resolve()
grants = get_settings().knowledge_export_grants
if not isinstance(grants, dict):
raise ValueError("Export grant evidence unavailable")
approved = False
for identity, boundaries in grants.items():
grant_owner = uuid.UUID(str(identity))
if not isinstance(boundaries, list):
raise ValueError("Malformed export grant evidence")
for boundary in boundaries:
if not isinstance(boundary, (str, Path)):
raise ValueError("Malformed export grant boundary")
path = Path(boundary)
if not path.is_absolute():
raise ValueError("Export grants require absolute boundaries")
path = path.resolve()
if grant_owner == owner and path == resolved:
approved = True
elif grant_owner != owner and paths_overlap(path, resolved):
raise ValueError("Ambiguous knowledge export boundary")
if external and not approved:
raise ValueError("External knowledge export requires an exact operator grant")
# Owner-scoped list_bundles cannot reveal a competing registration. Select
# only locators/ownership, never foreign credentials or file contents.
rows = await db.stream(select(
MCPServerConfig.owner_id, MCPServerConfig.command,
).where(
(MCPServerConfig.owner_id != owner) | MCPServerConfig.owner_id.is_(None),
MCPServerConfig.name.startswith(okf_bundles.BUNDLE_SERVER_NAME_PREFIX)
| MCPServerConfig.name.startswith(okf_documents.DOCUMENT_SERVER_NAME_PREFIX),
).execution_options(yield_per=50))
try:
async for registration in rows:
raw = okf_bundles.bundle_path_from_command(registration.command)
if raw is None or not Path(raw).is_absolute():
raise ValueError("Foreign knowledge boundary evidence unavailable")
if paths_overlap(resolved, Path(raw).resolve()):
raise ValueError("Ambiguous knowledge export boundary")
finally:
await rows.close()


async def _resources(writer: PackageWriter, graph: dict[str, Any], settings: dict[str, Any], owner: uuid.UUID) -> None:
async with system_session(reason="owned portable experiment resource capture") as db:
await db.connection(execution_options={"isolation_level": "REPEATABLE READ"})
Expand Down Expand Up @@ -772,10 +832,13 @@ async def _attempt_files(
# Exclude only known platform control/input/scratch identities.
for relative, path, _ in _tree_files(directory):
parts = PurePosixPath(relative).parts
platform_scratch = parts[0] == ".scratch" or (
len(parts) > 1 and parts[0].startswith(("dataset=", "agent=")) and parts[1] == ".scratch"
)
if credential_file(relative) or any(
part in {"scratch", "working", "cache", "__pycache__"}
or part.startswith(".asaree-script-context-") or part.endswith(".preparing") for part in parts
):
part.startswith(".asaree-script-context-")
or re.fullmatch(r"\..+\.[A-Za-z0-9_-]{8,}\.preparing", part) for part in parts
) or platform_scratch:
continue
control_parent = len(parts) == 1 or (
len(parts) == 2 and parts[0].startswith(("dataset=", "agent="))
Expand Down
Loading
Loading