|
- #!/usr/bin/env bash
- # Export/import checks (spec FR-018, NFR-007, NFR-009, AC-06, AC-14): canonical export with schema version and
- # integrity digest, filtering by read permission (no disclosure of unreadable namespaces or evidence targets), import
- # into a clean tenant with ids, revisions, verifications, provenance, documents, chunks and evidence intact (a second
- # export of the imported data equals the first), integrity and validation errors, all-or-nothing conflicts, size limit.
- #
- # Needs the container from docker-compose.yml running (name "axonasp", http://localhost:8801). It provisions throw-away
- # tenants and purges them at the end (even on failure).
- # bash tests/phase3-portability.sh
- set -u
- BASE=${BASE:-http://localhost:8801/api/v1}
- PASS=0; FAIL=0; FAILED=(); TENANTS=()
- TMP=$(mktemp -d)
- prov() {
- MSYS_NO_PATHCONV=1 docker exec -u axonasp -e SERVER_WEB_ROOT=/opt/axonasp/site \
- -e "PROV_ACTION=$1" -e "PROV_ARG1=${2:-}" -e "PROV_ARG2=${3:-}" -e "PROV_ARG3=${4:-}" -e "PROV_ARG4=${5:-}" \
- axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/provision.asp 2>&1 | tr -d '\r'
- }
- field() { sed -n "s/^$1: *\([^ ]*\).*/\1/p" | head -1; }
- jget() { sed -n "s/.*\"$1\":\"\([^\"]*\)\".*/\1/p" | head -1; }
- cleanup() { for t in "${TENANTS[@]}"; do prov purge "$t" >/dev/null; done; if [ -n "${KEEP:-}" ]; then echo "kept $TMP"; else rm -rf "$TMP"; fi; }
- trap cleanup EXIT
- check() { if [ "$2" = "$3" ]; then PASS=$((PASS+1)); else FAIL=$((FAIL+1)); FAILED+=("$1 (expected $2, got $3)"); fi; }
- code() { local key=$1 m=$2 p=$3; shift 3; curl -s -o /dev/null -w '%{http_code}' -X "$m" -H "Authorization: Bearer $key" "$@" "$BASE$p"; }
- body() { local key=$1 m=$2 p=$3; shift 3; curl -s -X "$m" -H "Authorization: Bearer $key" "$@" "$BASE$p"; }
- has() { grep -q -- "$1" <<<"$2" && echo yes || echo no; }
- pyf() { python -I -c "import sys,json,hashlib;a=sys.argv[2:];$1" "$@"; } # pyf '<python using a[]>' args...
- jq_() { python -I -c "import sys,json;sys.stdin.reconfigure(encoding='utf-8');d=json.load(sys.stdin);print($1)"; }
- js() { python -I -c "import json,sys;print(json.dumps(sys.argv[1]))" "$1"; }
- remember() { body "$1" POST /remember -d "{\"namespace_id\":\"$2\",\"type\":\"$3\",\"title\":$(js "$4"),\"content\":$(js "$5")${6:-}}" | jget id; }
- # rememberj: like remember, but $5 is already a JSON string literal
- rememberj() { body "$1" POST /remember -d "{\"namespace_id\":\"$2\",\"type\":\"$3\",\"title\":$(js "$4"),\"content\":$5}" | jget id; }
- verify() { code "$1" POST /memories/$2/verifications -d "{\"result\":\"verified\",\"method\":\"manual\",\"revision\":${3:-1}}" >/dev/null; }
- # export <key> <file> [body]
- export_() { curl -s -X POST -H "Authorization: Bearer $1" -d "${3:-{\}}" -o "$2" -w '%{http_code}' "$BASE/exports"; }
- import_() { curl -s -X POST -H "Authorization: Bearer $1" --data-binary @"$2" -w '\n%{http_code}' "$BASE/imports"; }
- digest_ok() { pyf "raw=open(a[0],'rb').read().decode('utf-8');d=json.loads(raw);i=raw.index('\"data\":')+7;j=raw.rindex(',\"counts\":');print(hashlib.sha256(raw[i:j].encode('utf-8')).hexdigest()==d['integrity']['digest'])" "$1"; }
- mk() { local out; out=$(prov principal "$1" "$2" "$3"); P_ID=$(echo "$out" | field principal_id); P_KEY=$(echo "$out" | field api_key); }
-
- # ---- setup: tenant A with two namespaces and a secret one ------------------------------------------------------
- TA=$(prov tenant "port-A" | field tenant_id); TB=$(prov tenant "port-B" | field tenant_id); TENANTS=("$TA" "$TB")
- mk "$TA" owner human; OID=$P_ID; OK=$P_KEY
- mk "$TA" writer agent; WID=$P_ID; WK=$P_KEY
- mk "$TA" reader agent; RID=$P_ID; RK=$P_KEY
- mk "$TA" blind agent; BLID=$P_ID; BLK=$P_KEY
- mk "$TB" ownerB human; BID=$P_ID; BK=$P_KEY
- prov grant "$OID" /kb admin 1 >/dev/null; prov grant "$OID" /secret admin 1 >/dev/null
- prov grant "$WID" /kb "read,write" 1 >/dev/null
- prov grant "$RID" /kb read 1 >/dev/null
- prov grant "$BLID" /elsewhere read 1 >/dev/null
- prov grant "$BID" /kb admin 1 >/dev/null
- NS=$(prov namespace "$TA" /kb | field namespace_id); NSUB=$(prov namespace "$TA" /kb/sub | field namespace_id)
- NSS=$(prov namespace "$TA" /secret | field namespace_id); NSB=$(prov namespace "$TB" /kb | field namespace_id)
- [ -n "$NS" ] && [ -n "$NSUB" ] && [ -n "$NSS" ] && [ -n "$NSB" ] && [ -n "$OK" ] || { echo "setup failed"; exit 2; }
-
- M1=$(remember "$WK" "$NS" semantic "Pelican port" "The pelican service listens on port 9100." ',"tags":["ports","pelican"],"confidence":0.75')
- code "$WK" PATCH /memories/$M1 -H 'If-Match: 1' -d '{"content":"The pelican service listens on port 9200.","change_reason":"moved"}' >/dev/null
- verify "$OK" "$M1" 2
- M2C=$(python -I -c "import json;print(json.dumps('Quote \"q\", backslash '+chr(92)+', tab'+chr(9)+' and Gr'+chr(252)+chr(223)+'e '+chr(0x65e5)+'.'))" | tr -d '[:cntrl:]')
- M2=$(rememberj "$WK" "$NSUB" lesson "Escapes <b>" "$M2C")
- M3=$(remember "$WK" "$NS" semantic "Old pelican host" "Pelican ran on host alpha.")
- code "$OK" POST /memories/$M3/retire >/dev/null
- MS=$(remember "$OK" "$NSS" semantic "Pelican secret" "The pelican vault key is in safe nine.")
- curl -s -o /dev/null -X POST -H "Authorization: Bearer $WK" "$BASE/ingestion/jobs" -d "{\"namespace_id\":\"$NS\",\"title\":\"Pelican runbook\",\"source_uri\":\"kb://pelican\",\"format\":\"markdown\",\"content\":\"# Pelican\n\nRestart pelican gently.\n\n## Ports\n\nPelican uses 9100.\"}"
- DOC=$(curl -s -X POST -H "Authorization: Bearer $WK" "$BASE/ingestion/jobs" -d "{\"namespace_id\":\"$NS\",\"title\":\"Pelican runbook\",\"source_uri\":\"kb://pelican\",\"format\":\"markdown\",\"content\":\"# Pelican\n\nRestart pelican gently.\n\n## Ports\n\nPelican uses 9200 now.\"}" | jget document_id)
- CH=$(body "$RK" POST /search -d '{"query":"pelican 9200"}' | jq_ "d['results'][0]['chunk_id']" 2>/dev/null)
- # evidence: a candidate citing M1 and the chunk (readable) and the secret memory (owner only), accepted by the owner
- C1=$(body "$OK" POST /learn -d "{\"namespace_id\":\"$NS\",\"type\":\"lesson\",\"title\":\"Pelican moved\",\"content\":\"Pelican moved from 9100 to 9200.\",\"evidence\":[{\"kind\":\"memory\",\"id\":\"$M1\"},{\"kind\":\"chunk\",\"id\":\"$CH\",\"excerpt\":\"9200\"},{\"kind\":\"memory\",\"id\":\"$MS\",\"role\":\"context\"}]}" | jget id)
- M4=$(body "$OK" POST /candidates/$C1/review -d '{"decision":"accept","verify":true}' | jget resulting_memory_id)
- MB=$(remember "$BK" "$NSB" semantic "B pelican" "Tenant B pelican fact.")
- [ -n "$M1" ] && [ -n "$M2" ] && [ -n "$DOC" ] && [ -n "$CH" ] && [ -n "$M4" ] && [ -n "$MB" ] || { echo "data setup failed"; exit 2; }
-
- # ---- export ----------------------------------------------------------------------------------------------------
- docker restart axonasp >/dev/null; for i in $(seq 1 20); do curl -s -o /dev/null "$BASE/health/live" && break; sleep 1; done
- check "cold: owner export -> 200" "200" "$(export_ "$OK" "$TMP/owner.json")"
- E="$TMP/owner.json"
- check "format and schema version" "agent-memory-export 1" "$(pyf "d=json.load(open(a[0],encoding='utf-8'));print(d['format'],d['schema_version'])" "$E")"
- check "integrity digest valid" "True" "$(digest_ok "$E")"
- check "counts" "3 5 6 1 2 3" "$(pyf "c=json.load(open(a[0],encoding='utf-8'))['counts'];print(c['namespaces'],c['memories'],c['memory_revisions'],c['documents'],c['document_revisions'],c['evidence_links'])" "$E")"
- check "memory keeps both revisions" "2" "$(pyf "d=json.load(open(a[0],encoding='utf-8'))['data'];print(len([m for m in d['memories'] if m['id']==a[1]][0]['revisions']))" "$E" "$M1")"
- check "provenance kept (created_by)" "$WID" "$(pyf "d=json.load(open(a[0],encoding='utf-8'))['data'];print([m for m in d['memories'] if m['id']==a[1]][0]['created_by'])" "$E" "$M1")"
- check "retired status kept" "retired" "$(pyf "d=json.load(open(a[0],encoding='utf-8'))['data'];print([m for m in d['memories'] if m['id']==a[1]][0]['lifecycle_status'])" "$E" "$M3")"
- check "UTF-8 and escapes exported" "yes" "$(pyf "d=json.load(open(a[0],encoding='utf-8'))['data'];c=[m for m in d['memories'] if m['id']==a[1]][0]['revisions'][0]['content'];print('yes' if chr(92) in c and chr(252) in c and chr(0x65e5) in c and chr(9) in c else 'no')" "$E" "$M2")"
- check "export content-disposition" "yes" "$(curl -s -i -X POST -H "Authorization: Bearer $OK" -d '{}' "$BASE/exports" | grep -qi '^content-disposition: attachment' && echo yes || echo no)"
- export_ "$RK" "$TMP/reader.json" >/dev/null
- check "reader export: no secret namespace" "no" "$(has '/secret' "$(cat "$TMP/reader.json")")"
- check "reader export: secret memory id absent" "no" "$(has "$MS" "$(cat "$TMP/reader.json")")"
- check "reader export: unreadable evidence omitted" "1" "$(pyf "print(json.load(open(a[0],encoding='utf-8'))['counts']['evidence_links_omitted'])" "$TMP/reader.json")"
- export_ "$BLK" "$TMP/blind.json" >/dev/null
- check "blind export is empty" "0 0" "$(pyf "c=json.load(open(a[0],encoding='utf-8'))['counts'];print(c['memories'],c['documents'])" "$TMP/blind.json")"
- export_ "$BK" "$TMP/b.json" >/dev/null
- check "tenant B export has only B" "yes no" "$(has "$MB" "$(cat "$TMP/b.json")") $(has "$M1" "$(cat "$TMP/b.json")")"
- export_ "$OK" "$TMP/sub.json" "{\"namespace_ids\":[\"$NSUB\"]}" >/dev/null
- check "namespace filter" "1 /kb/sub" "$(pyf "d=json.load(open(a[0],encoding='utf-8'));print(d['counts']['memories'],d['data']['namespaces'][0]['path'])" "$TMP/sub.json")"
- check "filter with unreadable id gives nothing" "0" "$(export_ "$RK" "$TMP/x.json" "{\"namespace_ids\":[\"$NSS\"]}" >/dev/null; pyf "print(json.load(open(a[0],encoding='utf-8'))['counts']['memories'])" "$TMP/x.json")"
- check "export bad namespace_ids -> 422" "422" "$(code "$OK" POST /exports -d '{"namespace_ids":"x"}')"
- check "export no auth -> 401" "401" "$(curl -s -o /dev/null -w '%{http_code}' -X POST -d '{}' "$BASE/exports")"
- check "export wrong method -> 405" "405" "$(code "$OK" GET /exports)"
-
- # ---- import validation (nothing written) ------------------------------------------------------------------------
- pyf "d=json.load(open(a[0],encoding='utf-8'));d['format']='other';open(a[1],'w',encoding='utf-8').write(json.dumps(d))" "$E" "$TMP/badfmt.json"
- check "import wrong format -> 422" "422" "$(import_ "$BK" "$TMP/badfmt.json" | tail -1)"
- pyf "raw=open(a[0],encoding='utf-8').read();open(a[1],'w',encoding='utf-8').write(raw.replace('\"schema_version\":1','\"schema_version\":2',1))" "$E" "$TMP/v2.json"
- check "import schema_version 2 -> 422" "unsupported_schema_version" "$(import_ "$BK" "$TMP/v2.json" | head -1 | jget code)"
- pyf "raw=open(a[0],encoding='utf-8').read();open(a[1],'w',encoding='utf-8').write(raw.replace('port 9200','port 6666',1))" "$E" "$TMP/tampered.json"
- check "tampered data -> integrity_mismatch" "integrity_mismatch" "$(import_ "$BK" "$TMP/tampered.json" | head -1 | jget code)"
- check "import into tenant without /secret -> 422" "422" "$(import_ "$BK" "$E" | tail -1)"
- export_ "$OK" "$TMP/kb.json" "{\"namespace_ids\":[\"$NS\"]}" >/dev/null
- check "import into existing ids -> 409" "409" "$(import_ "$BK" "$TMP/kb.json" | tail -1)"
- check "failed imports wrote nothing in B" "1" "$(export_ "$BK" "$TMP/b2.json" >/dev/null; pyf "print(json.load(open(a[0],encoding='utf-8'))['counts']['memories'])" "$TMP/b2.json")"
- check "import by non-admin -> 422" "422" "$(import_ "$RK" "$TMP/sub.json" | tail -1)"
- check "import empty body -> 400" "400" "$(code "$OK" POST /imports)"
- check "import invalid JSON -> 400" "400" "$(code "$OK" POST /imports -d '{"format":')"
- python -I -c "import sys;open(sys.argv[1],'w').write('{\"pad\":\"'+'x'*(9*1024*1024)+'\"}')" "$TMP/big.json"
- check "import over 8 MiB -> 413" "413" "$(curl -s -o /dev/null -w '%{http_code}' -X POST -H "Authorization: Bearer $OK" --data-binary @"$TMP/big.json" "$BASE/imports")"
-
- # ---- round trip: purge tenant A, recreate its namespaces, import, export again ----------------------------------
- prov purge "$TA" >/dev/null
- TA2=$(prov tenant "port-A2" | field tenant_id); TENANTS+=("$TA2")
- mk "$TA2" restorer human; RSID=$P_ID; RSK=$P_KEY
- prov grant "$RSID" /kb admin 1 >/dev/null; prov grant "$RSID" /secret admin 1 >/dev/null
- prov namespace "$TA2" /kb >/dev/null; prov namespace "$TA2" /kb/sub >/dev/null; prov namespace "$TA2" /secret >/dev/null
- docker restart axonasp >/dev/null; for i in $(seq 1 20); do curl -s -o /dev/null "$BASE/health/live" && break; sleep 1; done
- R=$(import_ "$RSK" "$E")
- check "cold: import into clean tenant -> 201" "201" "$(tail -1 <<<"$R")"
- check "import counts" "5 6 3 1 2" "$(head -1 <<<"$R" | jq_ "' '.join(str(d['imported'][k]) for k in ['memories','memory_revisions','evidence_links','documents','document_revisions'])")"
- R=$(body "$RSK" GET /memories/$M1)
- check "imported memory: same id, revision 2" "2" "$(echo "$R" | jq_ "d['data']['current_revision']")"
- check "imported memory: verified" "verified" "$(echo "$R" | jq_ "d['data']['verification_status']")"
- check "imported memory: provenance" "$WID" "$(echo "$R" | jq_ "d['data']['created_by']")"
- check "imported memory: tags" "['ports', 'pelican']" "$(echo "$R" | jq_ "d['data']['tags']")"
- check "imported history: 2 versions" "2" "$(body "$RSK" GET /memories/$M1/versions | jq_ "len(d['data'])")"
- check "imported UTF-8 and escapes intact" "yes" "$(body "$RSK" GET /memories/$M2 | jq_ "'yes' if chr(92) in d['data']['content'] and chr(252) in d['data']['content'] and chr(0x65e5) in d['data']['content'] and chr(9) in d['data']['content'] else 'no'")"
- check "imported retired memory stays retired" "retired" "$(body "$RSK" GET /memories/$M3 | jq_ "d['data']['status']")"
- check "recall finds imported memory" "yes" "$(body "$RSK" POST /recall -d '{"query":"pelican service port"}' | jq_ "'yes' if any(x['id']=='$M1' for x in d['results']) else 'no'")"
- check "search finds imported chunk (same id)" "yes" "$(body "$RSK" POST /search -d '{"query":"pelican 9200"}' | jq_ "'yes' if any(x['chunk_id']=='$CH' for x in d['results']) else 'no'")"
- check "document keeps revision 2" "2" "$(body "$RSK" GET /documents/$DOC | jq_ "d['data']['current_revision']")"
- check "imported evidence available" "3" "$(body "$RSK" GET /memories/$M4/sources | jq_ "len([e for e in d['evidence'] if e['available']])")"
- export_ "$RSK" "$TMP/again.json" >/dev/null
- check "re-export equals the original (AC-14)" "True" "$(pyf "x=json.load(open(a[0],encoding='utf-8'))['data'];y=json.load(open(a[1],encoding='utf-8'))['data'];print(x==y)" "$E" "$TMP/again.json")"
- check "importing twice -> 409" "409" "$(import_ "$RSK" "$E" | tail -1)"
-
- echo "passed: $PASS failed: $FAIL"
- for f in "${FAILED[@]:-}"; do [ -n "$f" ] && echo " FAIL: $f"; done
- [ "$FAIL" -eq 0 ]
|