Spaces:
Configuration error
refactor: consolidate route auth + service accessors (closes #34)
Browse filesDelete the per-route _check_auth / _get_kv / _get_search_service /
_get_observation_store copies from observations, mcp, search, migration,
memories, graph, and health. Every protected handler now uses the
existing routes/auth.py:require_auth decorator; service accessors move
to a single routes/_deps.py that reads from Flask extensions with an
app-module-globals fallback for test resets.
Also registers kv on flask_app.extensions for symmetry with
observation_store and search_service.
New test tests/test_routes_auth_matrix.py walks every registered HTTP
rule and asserts the auth semantics (401 without token, 2xx with token,
2xx in no-secret mode, 401 on invalid token). Skips WebSocket routes
per the ticket.
Prep for #35 (legacy.py file-split) — removes the auth-plumbing churn
that would otherwise conflict across every route file.
Files changed (10)
- src/agentcache/app.py+1
- src/agentcache/routes/_deps.pyAdded+46
- src/agentcache/routes/graph.py+7-11
- src/agentcache/routes/health.py+5-8
- src/agentcache/routes/mcp.py+11-48
- src/agentcache/routes/memories.py+8-11
- src/agentcache/routes/migration.py+4-27
- src/agentcache/routes/observations.py+11-57
- src/agentcache/routes/search.py+8-46
- tests/test_routes_auth_matrix.pyAdded+151
141 unmodified lines142143144145146147141 unmodified lines# 4. Flask app + blueprintsflask_app = Flask(__name__)flask_app.extensions["observation_store"] = observation_storeflask_app.extensions["search_service"] = search_service141 unmodified lines142143144145146147148141 unmodified lines# 4. Flask app + blueprintsflask_app = Flask(__name__)flask_app.extensions["kv"] = kvflask_app.extensions["observation_store"] = observation_storeflask_app.extensions["search_service"] = search_service
12345678910111213141516171819202122232425262728293031323334353637383940414243444546"""Shared service accessors for route blueprints.
Route handlers call these to reach the process-wide singletons that``app.py:init_services`` populates on the Flask ``extensions`` dict.Kept here so no route file has to re-derive the "extensions → app-moduleglobals → raise" fallback chain that used to live in six copies."""
from __future__ import annotations
from typing import Any
from flask import current_app
def _from_extensions(name: str) -> Any: ext = getattr(current_app, "extensions", {}) or {} value = ext.get(name) if value is not None: return value
from .. import app as app_module
return getattr(app_module, name, None)
def get_kv() -> Any: """Return the process StateKV. Raises RuntimeError if uninitialised.""" kv = _from_extensions("kv") if kv is None: raise RuntimeError("StateKV is not initialized") return kv
def get_search_service() -> Any: """Return the SearchService singleton (or None if search is disabled).""" return _from_extensions("search_service")
def get_observation_store() -> Any: """Return the ObservationStore. Raises RuntimeError if uninitialised.""" store = _from_extensions("observation_store") if store is None: raise RuntimeError("ObservationStore is not initialized") return store10 unmodified lines111213141516171819202122232425262728293 unmodified lines333435363738394 unmodified lines444546474849508 unmodified lines596061626364658 unmodified lines7475767778798010 unmodified linesfrom flask import Blueprint, jsonify, requestfrom .. import legacy as functionsfrom .auth import require_authdef create_graph_bp(kv=None):"""Blueprint factory — receives kv at registration time."""bp = Blueprint("graph", __name__)def _get_kv():if kv is not None:return kvfrom .. import app as app_modulereturn app_module.kv# ------------------------------------------------------------------# GET /agentcache/graph3 unmodified lines@bp.route("/agentmemory/graph", methods=["GET"])@require_authdef api_graph():result = functions.folder_graph_build(_get_kv())return jsonify(result), 200# ------------------------------------------------------------------4 unmodified lines@bp.route("/agentmemory/graph/stats", methods=["GET"])@require_authdef api_graph_stats():g = functions.folder_graph_build(_get_kv())node_count = len(g.get("nodes", []))edge_count = len(g.get("edges", []))return jsonify({"nodes": node_count, "edges": edge_count, "success": True}), 2008 unmodified linesdef api_graph_query():try:request.get_json(force=True) or {}# start_node_id = body.get("startNodeId") # reserved for future usereturn jsonify({"nodes": [], "edges": [], "success": True}), 200except Exception as e:return jsonify({"error": str(e)}), 4008 unmodified linesdef api_graph_build():try:if functions.is_consolidation_enabled():functions.consolidate(_get_kv())return jsonify({"success": True}), 200except Exception as e:return jsonify({"error": str(e)}), 40010 unmodified lines111213141516171819202122232425263 unmodified lines303132333435364 unmodified lines414243444546478 unmodified lines5657585960618 unmodified lines7071727374757610 unmodified linesfrom flask import Blueprint, jsonify, requestfrom .. import legacy as functionsfrom ._deps import get_kvfrom .auth import require_authdef create_graph_bp(kv=None):"""Blueprint factory — receives kv at registration time (falls back to get_kv())."""bp = Blueprint("graph", __name__)def _kv():return kv if kv is not None else get_kv()# ------------------------------------------------------------------# GET /agentcache/graph3 unmodified lines@bp.route("/agentmemory/graph", methods=["GET"])@require_authdef api_graph():result = functions.folder_graph_build(_kv())return jsonify(result), 200# ------------------------------------------------------------------4 unmodified lines@bp.route("/agentmemory/graph/stats", methods=["GET"])@require_authdef api_graph_stats():g = functions.folder_graph_build(_kv())node_count = len(g.get("nodes", []))edge_count = len(g.get("edges", []))return jsonify({"nodes": node_count, "edges": edge_count, "success": True}), 2008 unmodified linesdef api_graph_query():try:request.get_json(force=True) or {}return jsonify({"nodes": [], "edges": [], "success": True}), 200except Exception as e:return jsonify({"error": str(e)}), 4008 unmodified linesdef api_graph_build():try:if functions.is_consolidation_enabled():functions.consolidate(_kv())return jsonify({"success": True}), 200except Exception as e:return jsonify({"error": str(e)}), 400
13 unmodified lines1415161718191 unmodified line21222324252627282930313243 unmodified lines767778798081825 unmodified lines8889909192939413 unmodified linesfrom .. import legacy as functionsfrom ..legacy import query_auditfrom .auth import require_auth1 unmodified line"""Blueprint factory — receives kv and embedding_provider at registration time."""bp = Blueprint("health", __name__)def _get_kv():if kv is not None:return kvfrom .. import app as app_modulereturn app_module.kv# ------------------------------------------------------------------# GET /auth.md (no auth required)43 unmodified lines@bp.route("/agentcache/health", methods=["GET"])@bp.route("/agentmemory/health", methods=["GET"])def health():return jsonify(functions.health_check(_get_kv()))# ------------------------------------------------------------------# GET /agentcache/audit5 unmodified linesdef api_audit():op = request.args.get("operation")limit = int(request.args.get("limit", "50"))res = query_audit(_get_kv(), {"operation": op, "limit": limit})return jsonify({"entries": res, "success": True}), 200# ------------------------------------------------------------------13 unmodified lines141516171819201 unmodified line222324252627282943 unmodified lines737475767778795 unmodified lines8586878889909113 unmodified linesfrom .. import legacy as functionsfrom ..legacy import query_auditfrom ._deps import get_kvfrom .auth import require_auth1 unmodified line"""Blueprint factory — receives kv and embedding_provider at registration time."""bp = Blueprint("health", __name__)def _kv():return kv if kv is not None else get_kv()# ------------------------------------------------------------------# GET /auth.md (no auth required)43 unmodified lines@bp.route("/agentcache/health", methods=["GET"])@bp.route("/agentmemory/health", methods=["GET"])def health():return jsonify(functions.health_check(_kv()))# ------------------------------------------------------------------# GET /agentcache/audit5 unmodified linesdef api_audit():op = request.args.get("operation")limit = int(request.args.get("limit", "50"))res = query_audit(_kv(), {"operation": op, "limit": limit})return jsonify({"entries": res, "success": True}), 200# ------------------------------------------------------------------
13 unmodified lines14151617181920212223242526272829303132333435363738394041424344454647484950515253545556294 unmodified lines3513523533543553563573583593603615 unmodified lines36736836937037137237337437537637737837916 unmodified lines39639739839940040140236 unmodified lines43944044144244344444521 unmodified lines46746846947047147247356 unmodified lines53053153253353453553670 unmodified lines60760860961061161261316 unmodified lines63063163263363463563613 unmodified linesfrom .. import legacyfrom ..core import KVmcp_bp = Blueprint("mcp", __name__)def _check_auth():import hmacsecret = os.getenv("AGENTCACHE_SECRET") or os.getenv("AGENTMEMORY_SECRET")if not secret:return Noneauth = request.headers.get("Authorization") or request.headers.get("authorization")if not auth or not auth.startswith("Bearer "):return jsonify({"error": "unauthorized"}), 401provided_token = auth[7:].strip()if not hmac.compare_digest(provided_token.encode("utf-8"), secret.encode("utf-8")):return jsonify({"error": "unauthorized"}), 401return Nonedef _get_kv():from .. import app as app_modulereturn app_module.kvdef _get_search_service():from .. import app as app_modulereturn app_module.search_servicedef _get_observation_store():from .. import app as app_modulereturn app_module.observation_storedef _datetime_now_iso() -> str:return (datetime.datetime.now(datetime.timezone.utc).isoformat().replace("+00:00", "Z")294 unmodified lines@mcp_bp.route("/agentcache/mcp/tools", methods=["GET"])@mcp_bp.route("/agentmemory/mcp/tools", methods=["GET"])def mcp_tools_list():auth_err = _check_auth()if auth_err:return auth_errtools = get_mcp_tools_schemas()return jsonify({"tools": tools}), 2005 unmodified lines@mcp_bp.route("/agentcache/mcp/tools", methods=["POST"])@mcp_bp.route("/agentmemory/mcp/tools", methods=["POST"])def mcp_tools_call():auth_err = _check_auth()if auth_err:return auth_errtry:kv = _get_kv()body = request.get_json(force=True) or {}name = body.get("name")args = body.get("arguments") or {}16 unmodified lines{"error": "Unauthorized: Agent scope is isolated"}), 403agent_id = current_aidsearch_svc = _get_search_service()if search_svc is not None:res = search_svc.search(query=q,36 unmodified lines{"error": "Unauthorized: Agent scope is isolated"}), 403agent_id = current_aidsearch_svc = _get_search_service()if search_svc is not None:res = search_svc.search(query=q,21 unmodified lines{"error": "Unauthorized: Agent scope is isolated"}), 403request_aid = current_aidobs_store = _get_observation_store()if obs_store is not None:forget_payload = {"memoryId": args.get("memoryId"),56 unmodified lines"files": args.get("files"),"importance": args.get("importance"),}obs_store = _get_observation_store()if obs_store is not None:res = obs_store.ingest(payload)else:70 unmodified lines{"error": "Unauthorized: Agent scope is isolated"}), 403request_aid = current_aidobs_store = _get_observation_store()if obs_store is not None:res = obs_store.timeline(limit=int(args.get("limit", 100)),16 unmodified lines{"error": "Unauthorized: Agent scope is isolated"}), 403request_aid = current_aidobs_store = _get_observation_store()if obs_store is not None:res = obs_store.dedup(args.get("folderPath") or None,13 unmodified lines141516171819202122232425294 unmodified lines3203213223233243253263275 unmodified lines33333433533633733833934034134216 unmodified lines35936036136236336436536 unmodified lines40240340440540640740821 unmodified lines43043143243343443543656 unmodified lines49349449549649749849970 unmodified lines57057157257357457557616 unmodified lines59359459559659759859913 unmodified linesfrom .. import legacyfrom ..core import KVfrom ._deps import get_kv, get_observation_store, get_search_servicefrom .auth import require_authmcp_bp = Blueprint("mcp", __name__)def _datetime_now_iso() -> str:return (datetime.datetime.now(datetime.timezone.utc).isoformat().replace("+00:00", "Z")294 unmodified lines@mcp_bp.route("/agentcache/mcp/tools", methods=["GET"])@mcp_bp.route("/agentmemory/mcp/tools", methods=["GET"])@require_authdef mcp_tools_list():tools = get_mcp_tools_schemas()return jsonify({"tools": tools}), 2005 unmodified lines@mcp_bp.route("/agentcache/mcp/tools", methods=["POST"])@mcp_bp.route("/agentmemory/mcp/tools", methods=["POST"])@require_authdef mcp_tools_call():try:kv = get_kv()body = request.get_json(force=True) or {}name = body.get("name")args = body.get("arguments") or {}16 unmodified lines{"error": "Unauthorized: Agent scope is isolated"}), 403agent_id = current_aidsearch_svc = get_search_service()if search_svc is not None:res = search_svc.search(query=q,36 unmodified lines{"error": "Unauthorized: Agent scope is isolated"}), 403agent_id = current_aidsearch_svc = get_search_service()if search_svc is not None:res = search_svc.search(query=q,21 unmodified lines{"error": "Unauthorized: Agent scope is isolated"}), 403request_aid = current_aidobs_store = get_observation_store()if obs_store is not None:forget_payload = {"memoryId": args.get("memoryId"),56 unmodified lines"files": args.get("files"),"importance": args.get("importance"),}obs_store = get_observation_store()if obs_store is not None:res = obs_store.ingest(payload)else:70 unmodified lines{"error": "Unauthorized: Agent scope is isolated"}), 403request_aid = current_aidobs_store = get_observation_store()if obs_store is not None:res = obs_store.timeline(limit=int(args.get("limit", 100)),16 unmodified lines{"error": "Unauthorized: Agent scope is isolated"}), 403request_aid = current_aidobs_store = get_observation_store()if obs_store is not None:res = obs_store.dedup(args.get("folderPath") or None,
11 unmodified lines121314151617181920212223242526272829305 unmodified lines3637383940414234 unmodified lines777879808182838 unmodified lines929394959697989 unmodified lines10810911011111211311411 unmodified linesfrom .. import legacy as functionsfrom ..core import KVfrom .auth import require_authdef create_memories_bp(kv=None):"""Blueprint factory — receives kv at registration time."""bp = Blueprint("memories", __name__)def _get_kv():if kv is not None:return kvfrom .. import app as app_modulereturn app_module.kv# ------------------------------------------------------------------# POST /agentmemory/remember5 unmodified linesdef api_remember():try:body = request.get_json(force=True) or {}res = functions.remember(_get_kv(), body)return jsonify(res), 201except Exception as e:return jsonify({"error": str(e)}), 40034 unmodified linesif agent_id:payload["agentId"] = agent_idres = functions.remember(_get_kv(), payload)return jsonify(res), 201except Exception as e:return jsonify({"error": str(e)}), 4008 unmodified linesdef api_memories_list():latest_only = request.args.get("latest", "false").lower() == "true"limit = int(request.args.get("limit", "500"))all_mems = _get_kv().list(KV.memories)if latest_only:all_mems = [m for m in all_mems if m.get("isLatest") is not False]all_mems.sort(key=lambda m: m.get("createdAt", ""), reverse=True)9 unmodified linesdef api_forget():try:body = request.get_json(force=True) or {}res = functions.forget(_get_kv(), body)return jsonify(res), 200except Exception as e:return jsonify({"error": str(e)}), 40011 unmodified lines121314151617181920212223242526275 unmodified lines3334353637383934 unmodified lines747576777879808 unmodified lines899091929394959 unmodified lines10510610710810911011111 unmodified linesfrom .. import legacy as functionsfrom ..core import KVfrom ._deps import get_kvfrom .auth import require_authdef create_memories_bp(kv=None):"""Blueprint factory — receives kv at registration time (falls back to get_kv())."""bp = Blueprint("memories", __name__)def _kv():return kv if kv is not None else get_kv()# ------------------------------------------------------------------# POST /agentmemory/remember5 unmodified linesdef api_remember():try:body = request.get_json(force=True) or {}res = functions.remember(_kv(), body)return jsonify(res), 201except Exception as e:return jsonify({"error": str(e)}), 40034 unmodified linesif agent_id:payload["agentId"] = agent_idres = functions.remember(_kv(), payload)return jsonify(res), 201except Exception as e:return jsonify({"error": str(e)}), 4008 unmodified linesdef api_memories_list():latest_only = request.args.get("latest", "false").lower() == "true"limit = int(request.args.get("limit", "500"))all_mems = _kv().list(KV.memories)if latest_only:all_mems = [m for m in all_mems if m.get("isLatest") is not False]all_mems.sort(key=lambda m: m.get("createdAt", ""), reverse=True)9 unmodified linesdef api_forget():try:body = request.get_json(force=True) or {}res = functions.forget(_kv(), body)return jsonify(res), 200except Exception as e:return jsonify({"error": str(e)}), 400
4 unmodified lines56789101112131415161718192021222324252627282930313233343536373839401 unmodified line42434445464748495051525354554 unmodified linesPOST /agentmemory/migrate"""import osfrom flask import Blueprint, jsonify, requestfrom .. import legacy as functionsmigration_bp = Blueprint("migration", __name__)def _check_auth():import hmacsecret = os.getenv("AGENTCACHE_SECRET") or os.getenv("AGENTMEMORY_SECRET")if not secret:return Noneauth = request.headers.get("Authorization") or request.headers.get("authorization")if not auth or not auth.startswith("Bearer "):return jsonify({"error": "unauthorized"}), 401provided_token = auth[7:].strip()if not hmac.compare_digest(provided_token.encode("utf-8"), secret.encode("utf-8")):return jsonify({"error": "unauthorized"}), 401return Nonedef _get_kv():from .. import app as app_modulereturn app_module.kv# ---------------------------------------------------------------------------# POST /agentcache/migrate# ---------------------------------------------------------------------------1 unmodified line@migration_bp.route("/agentcache/migrate", methods=["POST"])@migration_bp.route("/agentmemory/migrate", methods=["POST"])def api_migrate():auth_err = _check_auth()if auth_err:return auth_errtry:body = request.get_json(force=True) or {}dry_run = bool(body.get("dry_run", False))result = functions.migrate_sessions_to_folders(_get_kv(), dry_run)return jsonify(result), 200except Exception as e:return jsonify({"error": str(e)}), 4004 unmodified lines56789101112131415161718191 unmodified line2122232425262728293031324 unmodified linesPOST /agentmemory/migrate"""from flask import Blueprint, jsonify, requestfrom .. import legacy as functionsfrom ._deps import get_kvfrom .auth import require_authmigration_bp = Blueprint("migration", __name__)# ---------------------------------------------------------------------------# POST /agentcache/migrate# ---------------------------------------------------------------------------1 unmodified line@migration_bp.route("/agentcache/migrate", methods=["POST"])@migration_bp.route("/agentmemory/migrate", methods=["POST"])@require_authdef api_migrate():try:body = request.get_json(force=True) or {}dry_run = bool(body.get("dry_run", False))result = functions.migrate_sessions_to_folders(get_kv(), dry_run)return jsonify(result), 200except Exception as e:return jsonify({"error": str(e)}), 400
9 unmodified lines101112131415161718192021222 unmodified lines25262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747541 unmodified lines11711811912012112212312412512612738 unmodified lines1661671681691701711721731741759 unmodified lines18518618718818919019119219319424 unmodified lines21922022122222322422522622722822911 unmodified lines2412422432442452462472482492501 unmodified line2522532542552562572582592602615 unmodified lines2672682692702712722732742752762779 unmodified lines"""import datetimeimport osfrom typing import Optionalfrom flask import Blueprint, jsonify, requestfrom ..core.kv_scopes import KVfrom ..core.observation_store import ObservationStoredef _datetime_now_iso() -> str:2 unmodified lines)def _check_auth():"""Replicate the check_auth() pattern from app.py."""import hmacsecret = os.getenv("AGENTCACHE_SECRET") or os.getenv("AGENTMEMORY_SECRET")if not secret:return Noneauth = request.headers.get("Authorization") or request.headers.get("authorization")if not auth or not auth.startswith("Bearer "):return jsonify({"error": "unauthorized"}), 401provided_token = auth[7:].strip()if not hmac.compare_digest(provided_token.encode("utf-8"), secret.encode("utf-8")):return jsonify({"error": "unauthorized"}), 401return Nonedef create_observations_bp(observation_store: Optional[ObservationStore] = None,) -> Blueprint:bp = Blueprint("observations", __name__)def get_store() -> ObservationStore:if observation_store is not None:return observation_storefrom flask import current_appstore = current_app.extensions.get("observation_store")if store is None:from .. import app as app_modulestore = getattr(app_module, "observation_store", None)if store is None:raise RuntimeError("ObservationStore is not initialized")return storedef get_kv():return get_store().kv@bp.route("/agentcache/observe", methods=["POST"])@bp.route("/agentmemory/observe", methods=["POST"])def api_observe():auth_err = _check_auth()if auth_err:return auth_errbody = {}try:body = request.get_json(force=True) or {}41 unmodified lines@bp.route("/agentcache/agent/observe", methods=["POST"])@bp.route("/agentmemory/agent/observe", methods=["POST"])def api_agent_observe():auth_err = _check_auth()if auth_err:return auth_errtry:body = request.get_json(force=True) or {}folder_path = body.get("folderPath")38 unmodified lines@bp.route("/agentcache/folders", methods=["GET"])@bp.route("/agentmemory/folders", methods=["GET"])def api_folders():auth_err = _check_auth()if auth_err:return auth_errfrom .. import legacyfolders = sorted(9 unmodified lines@bp.route("/agentcache/folder/observations", methods=["GET"])@bp.route("/agentmemory/folder/observations", methods=["GET"])def api_folder_observations():auth_err = _check_auth()if auth_err:return auth_errfp = request.args.get("folderPath")aid = request.args.get("agentId")if not fp or not aid:24 unmodified lines@bp.route("/agentcache/session/start", methods=["POST"])@bp.route("/agentmemory/session/start", methods=["POST"])def api_session_start():auth_err = _check_auth()if auth_err:return auth_errimport uuidbody = request.get_json(force=True) or {}11 unmodified lines@bp.route("/agentcache/session/end", methods=["POST"])@bp.route("/agentmemory/session/end", methods=["POST"])def api_session_end():auth_err = _check_auth()if auth_err:return auth_errreturn (jsonify({"success": True, "message": "Session model is now folder-based."}),200,1 unmodified line@bp.route("/agentcache/folder/dedup", methods=["POST"])@bp.route("/agentmemory/folder/dedup", methods=["POST"])def api_folder_dedup():auth_err = _check_auth()if auth_err:return auth_errtry:body = request.get_json(force=True) or {}folder_path = body.get("folderPath") or None5 unmodified lines@bp.route("/agentcache/observations", methods=["GET"])@bp.route("/agentmemory/observations", methods=["GET"])def api_observations_legacy():auth_err = _check_auth()if auth_err:return auth_errsession_id = request.args.get("sessionId", "")if not session_id:return jsonify({"observations": [], "sessionId": ""}), 2009 unmodified lines10111213141516171819202122232 unmodified lines26272829303132333435363738394041424344454641 unmodified lines888990919293949538 unmodified lines1341351361371381391401419 unmodified lines15115215315415515615715824 unmodified lines18318418518618718818919011 unmodified lines2022032042052062072082091 unmodified line2112122132142152162172185 unmodified lines2242252262272282292302319 unmodified lines"""import datetimefrom typing import Optionalfrom flask import Blueprint, jsonify, requestfrom ..core.kv_scopes import KVfrom ..core.observation_store import ObservationStorefrom ._deps import get_observation_storefrom .auth import require_authdef _datetime_now_iso() -> str:2 unmodified lines)def create_observations_bp(observation_store: Optional[ObservationStore] = None,) -> Blueprint:bp = Blueprint("observations", __name__)def get_store() -> ObservationStore:return observation_store if observation_store is not None else get_observation_store()def get_kv():return get_store().kv@bp.route("/agentcache/observe", methods=["POST"])@bp.route("/agentmemory/observe", methods=["POST"])@require_authdef api_observe():body = {}try:body = request.get_json(force=True) or {}41 unmodified lines@bp.route("/agentcache/agent/observe", methods=["POST"])@bp.route("/agentmemory/agent/observe", methods=["POST"])@require_authdef api_agent_observe():try:body = request.get_json(force=True) or {}folder_path = body.get("folderPath")38 unmodified lines@bp.route("/agentcache/folders", methods=["GET"])@bp.route("/agentmemory/folders", methods=["GET"])@require_authdef api_folders():from .. import legacyfolders = sorted(9 unmodified lines@bp.route("/agentcache/folder/observations", methods=["GET"])@bp.route("/agentmemory/folder/observations", methods=["GET"])@require_authdef api_folder_observations():fp = request.args.get("folderPath")aid = request.args.get("agentId")if not fp or not aid:24 unmodified lines@bp.route("/agentcache/session/start", methods=["POST"])@bp.route("/agentmemory/session/start", methods=["POST"])@require_authdef api_session_start():import uuidbody = request.get_json(force=True) or {}11 unmodified lines@bp.route("/agentcache/session/end", methods=["POST"])@bp.route("/agentmemory/session/end", methods=["POST"])@require_authdef api_session_end():return (jsonify({"success": True, "message": "Session model is now folder-based."}),200,1 unmodified line@bp.route("/agentcache/folder/dedup", methods=["POST"])@bp.route("/agentmemory/folder/dedup", methods=["POST"])@require_authdef api_folder_dedup():try:body = request.get_json(force=True) or {}folder_path = body.get("folderPath") or None5 unmodified lines@bp.route("/agentcache/observations", methods=["GET"])@bp.route("/agentmemory/observations", methods=["GET"])@require_authdef api_observations_legacy():session_id = request.args.get("sessionId", "")if not session_id:return jsonify({"observations": [], "sessionId": ""}), 200
5 unmodified lines6789101112131415161718192021222324252627282930313233343536373839404142434445464748493 unmodified lines53545556575859606162633 unmodified lines67686970717273747576777879809 unmodified lines909192939495969798991001 unmodified line1021031041051061071085 unmodified linesPOST /agentmemory/timeline"""import osfrom flask import Blueprint, jsonify, requestsearch_bp = Blueprint("search", __name__)def _check_auth():import hmacsecret = os.getenv("AGENTCACHE_SECRET") or os.getenv("AGENTMEMORY_SECRET")if not secret:return Noneauth = request.headers.get("Authorization") or request.headers.get("authorization")if not auth or not auth.startswith("Bearer "):return jsonify({"error": "unauthorized"}), 401provided_token = auth[7:].strip()if not hmac.compare_digest(provided_token.encode("utf-8"), secret.encode("utf-8")):return jsonify({"error": "unauthorized"}), 401return Nonedef _get_kv():from .. import app as app_modulereturn app_module.kvdef _get_search_service():from .. import app as app_modulereturn app_module.search_servicedef _get_observation_store():from .. import app as app_modulereturn app_module.observation_store# ---------------------------------------------------------------------------3 unmodified lines@search_bp.route("/agentcache/search", methods=["POST"])@search_bp.route("/agentmemory/search", methods=["POST"])def api_search():auth_err = _check_auth()if auth_err:return auth_errtry:body = request.get_json(force=True) or {}query = body.get("query")3 unmodified linesfolder_path = body.get("folderPath")agent_id = body.get("agentId")search_svc = _get_search_service()if search_svc is not None:res = search_svc.search(query=query,limit=limit,folder_path=folder_path,agent_id=agent_id,kv=_get_kv(),)else:res = []9 unmodified lines@search_bp.route("/agentcache/timeline", methods=["POST"])@search_bp.route("/agentmemory/timeline", methods=["POST"])def api_timeline():auth_err = _check_auth()if auth_err:return auth_errtry:body = request.get_json(force=True) or {}folder_path = body.get("folderPath")1 unmodified linelimit = body.get("limit") or 100before = body.get("before")after = body.get("after")obs_store = _get_observation_store()if obs_store is not None:result = obs_store.timeline(limit=limit,5 unmodified lines678910111213141516173 unmodified lines21222324252627283 unmodified lines32333435363738394041424344459 unmodified lines55565758596061621 unmodified line646566676869705 unmodified linesPOST /agentmemory/timeline"""from flask import Blueprint, jsonify, requestfrom ._deps import get_kv, get_observation_store, get_search_servicefrom .auth import require_authsearch_bp = Blueprint("search", __name__)# ---------------------------------------------------------------------------3 unmodified lines@search_bp.route("/agentcache/search", methods=["POST"])@search_bp.route("/agentmemory/search", methods=["POST"])@require_authdef api_search():try:body = request.get_json(force=True) or {}query = body.get("query")3 unmodified linesfolder_path = body.get("folderPath")agent_id = body.get("agentId")search_svc = get_search_service()if search_svc is not None:res = search_svc.search(query=query,limit=limit,folder_path=folder_path,agent_id=agent_id,kv=get_kv(),)else:res = []9 unmodified lines@search_bp.route("/agentcache/timeline", methods=["POST"])@search_bp.route("/agentmemory/timeline", methods=["POST"])@require_authdef api_timeline():try:body = request.get_json(force=True) or {}folder_path = body.get("folderPath")1 unmodified linelimit = body.get("limit") or 100before = body.get("before")after = body.get("after")obs_store = get_observation_store()if obs_store is not None:result = obs_store.timeline(limit=limit,
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151"""Auth matrix — every registered HTTP rule in the Flask app.
For each rule this test asserts: 1. 401 when a secret is set and no token is provided 2. non-401 when a valid token is provided 3. non-401 when no secret is configured (auth disabled mode)
Rules explicitly marked in ``UNPROTECTED_PATHS`` are expected to skip autheven when the secret is set (livez, health, auth.md, static viewer routes).
Rules that don't take our synthetic empty payload cleanly (e.g. WebSocket,POST endpoints requiring specific fields) may 4xx/5xx on the *body* — that'sstill not a 401, which is all this matrix cares about."""
from __future__ import annotations
import pytest
import agentcache.app as app_modfrom agentcache.app import create_app
UNPROTECTED_PATHS = { "/auth.md", "/agentcache/livez", "/agentmemory/livez", "/agentcache/health", "/agentmemory/health", "/", "/viewer", "/agentcache/viewer", "/agentmemory/viewer", "/favicon.svg",}
def _reset_app_globals() -> None: app_mod.kv = None app_mod.search_service = None app_mod.observation_store = None
def _iter_http_rules(app): """Yield (method, path) for every non-static HTTP rule, one method per row.""" for rule in app.url_map.iter_rules(): # skip rules with URL parameters — we can't synthesise a valid one if "<" in rule.rule: continue # skip static asset endpoint if rule.endpoint == "static": continue # skip WebSocket rules — they can't be exercised via HTTP test client if rule.rule.startswith("/stream/"): continue methods = (rule.methods or set()) - {"HEAD", "OPTIONS"} for method in sorted(methods): yield method, rule.rule
@pytest.fixturedef secured_app(tmp_path, monkeypatch): monkeypatch.setenv("AGENTCACHE_DB_PATH", str(tmp_path / "matrix_secured.db")) monkeypatch.setenv("AGENTCACHE_SECRET", "matrix-secret") _reset_app_globals() return create_app()
@pytest.fixturedef open_app(tmp_path, monkeypatch): monkeypatch.setenv("AGENTCACHE_DB_PATH", str(tmp_path / "matrix_open.db")) monkeypatch.delenv("AGENTCACHE_SECRET", raising=False) monkeypatch.delenv("AGENTMEMORY_SECRET", raising=False) _reset_app_globals() return create_app()
def _invoke(client, method: str, path: str, headers=None): fn = getattr(client, method.lower()) if method in ("POST", "PUT", "PATCH", "DELETE"): return fn(path, json={}, headers=headers or {}) return fn(path, headers=headers or {})
def test_every_route_requires_auth_when_secret_is_set(secured_app): """Protected routes 401 without a token; unprotected routes pass through.""" client = secured_app.test_client() failures = []
for method, path in _iter_http_rules(secured_app): res = _invoke(client, method, path) if path in UNPROTECTED_PATHS: if res.status_code == 401: failures.append( f"{method} {path} unexpectedly required auth (401)" ) else: if res.status_code != 401: failures.append( f"{method} {path} did not require auth (got {res.status_code})" )
assert not failures, "auth-matrix mismatches:\n " + "\n ".join(failures)
def test_every_route_accepts_valid_token(secured_app): """With a valid Bearer token, no route returns 401.""" client = secured_app.test_client() headers = {"Authorization": "Bearer matrix-secret"} failures = []
for method, path in _iter_http_rules(secured_app): res = _invoke(client, method, path, headers=headers) if res.status_code == 401: failures.append(f"{method} {path} rejected a valid token (401)")
assert not failures, "rejected valid token:\n " + "\n ".join(failures)
def test_every_route_open_when_no_secret_configured(open_app): """When no secret env var is set, every route passes auth (no 401 anywhere).""" client = open_app.test_client() failures = []
for method, path in _iter_http_rules(open_app): res = _invoke(client, method, path) if res.status_code == 401: failures.append( f"{method} {path} returned 401 in open (no-secret) mode" )
assert not failures, "unexpected 401s in open mode:\n " + "\n ".join(failures)
def test_every_route_rejects_invalid_token(secured_app): """With a wrong Bearer token, protected routes must still 401.""" client = secured_app.test_client() bad_headers = {"Authorization": "Bearer not-the-secret"} failures = []
for method, path in _iter_http_rules(secured_app): if path in UNPROTECTED_PATHS: continue res = _invoke(client, method, path, headers=bad_headers) if res.status_code != 401: failures.append( f"{method} {path} accepted a bad token (got {res.status_code})" )
assert not failures, "invalid-token acceptance:\n " + "\n ".join(failures)