Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

146 строки
14KB

  1. #!/usr/bin/env bash
  2. # Export/import checks (spec FR-018, NFR-007, NFR-009, AC-06, AC-14): canonical export with schema version and
  3. # integrity digest, filtering by read permission (no disclosure of unreadable namespaces or evidence targets), import
  4. # into a clean tenant with ids, revisions, verifications, provenance, documents, chunks and evidence intact (a second
  5. # export of the imported data equals the first), integrity and validation errors, all-or-nothing conflicts, size limit.
  6. #
  7. # Needs the container from docker-compose.yml running (name "axonasp", http://localhost:8801). It provisions throw-away
  8. # tenants and purges them at the end (even on failure).
  9. # bash tests/phase3-portability.sh
  10. set -u
  11. BASE=${BASE:-http://localhost:8801/api/v1}
  12. PASS=0; FAIL=0; FAILED=(); TENANTS=()
  13. TMP=$(mktemp -d)
  14. prov() {
  15. MSYS_NO_PATHCONV=1 docker exec -u axonasp -e SERVER_WEB_ROOT=/opt/axonasp/site \
  16. -e "PROV_ACTION=$1" -e "PROV_ARG1=${2:-}" -e "PROV_ARG2=${3:-}" -e "PROV_ARG3=${4:-}" -e "PROV_ARG4=${5:-}" \
  17. axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/provision.asp 2>&1 | tr -d '\r'
  18. }
  19. field() { sed -n "s/^$1: *\([^ ]*\).*/\1/p" | head -1; }
  20. jget() { sed -n "s/.*\"$1\":\"\([^\"]*\)\".*/\1/p" | head -1; }
  21. cleanup() { for t in "${TENANTS[@]}"; do prov purge "$t" >/dev/null; done; if [ -n "${KEEP:-}" ]; then echo "kept $TMP"; else rm -rf "$TMP"; fi; }
  22. trap cleanup EXIT
  23. check() { if [ "$2" = "$3" ]; then PASS=$((PASS+1)); else FAIL=$((FAIL+1)); FAILED+=("$1 (expected $2, got $3)"); fi; }
  24. 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"; }
  25. body() { local key=$1 m=$2 p=$3; shift 3; curl -s -X "$m" -H "Authorization: Bearer $key" "$@" "$BASE$p"; }
  26. has() { grep -q -- "$1" <<<"$2" && echo yes || echo no; }
  27. pyf() { python -I -c "import sys,json,hashlib;a=sys.argv[2:];$1" "$@"; } # pyf '<python using a[]>' args...
  28. jq_() { python -I -c "import sys,json;sys.stdin.reconfigure(encoding='utf-8');d=json.load(sys.stdin);print($1)"; }
  29. js() { python -I -c "import json,sys;print(json.dumps(sys.argv[1]))" "$1"; }
  30. remember() { body "$1" POST /remember -d "{\"namespace_id\":\"$2\",\"type\":\"$3\",\"title\":$(js "$4"),\"content\":$(js "$5")${6:-}}" | jget id; }
  31. # rememberj: like remember, but $5 is already a JSON string literal
  32. rememberj() { body "$1" POST /remember -d "{\"namespace_id\":\"$2\",\"type\":\"$3\",\"title\":$(js "$4"),\"content\":$5}" | jget id; }
  33. verify() { code "$1" POST /memories/$2/verifications -d "{\"result\":\"verified\",\"method\":\"manual\",\"revision\":${3:-1}}" >/dev/null; }
  34. # export <key> <file> [body]
  35. export_() { curl -s -X POST -H "Authorization: Bearer $1" -d "${3:-{\}}" -o "$2" -w '%{http_code}' "$BASE/exports"; }
  36. import_() { curl -s -X POST -H "Authorization: Bearer $1" --data-binary @"$2" -w '\n%{http_code}' "$BASE/imports"; }
  37. 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"; }
  38. mk() { local out; out=$(prov principal "$1" "$2" "$3"); P_ID=$(echo "$out" | field principal_id); P_KEY=$(echo "$out" | field api_key); }
  39. # ---- setup: tenant A with two namespaces and a secret one ------------------------------------------------------
  40. TA=$(prov tenant "port-A" | field tenant_id); TB=$(prov tenant "port-B" | field tenant_id); TENANTS=("$TA" "$TB")
  41. mk "$TA" owner human; OID=$P_ID; OK=$P_KEY
  42. mk "$TA" writer agent; WID=$P_ID; WK=$P_KEY
  43. mk "$TA" reader agent; RID=$P_ID; RK=$P_KEY
  44. mk "$TA" blind agent; BLID=$P_ID; BLK=$P_KEY
  45. mk "$TB" ownerB human; BID=$P_ID; BK=$P_KEY
  46. prov grant "$OID" /kb admin 1 >/dev/null; prov grant "$OID" /secret admin 1 >/dev/null
  47. prov grant "$WID" /kb "read,write" 1 >/dev/null
  48. prov grant "$RID" /kb read 1 >/dev/null
  49. prov grant "$BLID" /elsewhere read 1 >/dev/null
  50. prov grant "$BID" /kb admin 1 >/dev/null
  51. NS=$(prov namespace "$TA" /kb | field namespace_id); NSUB=$(prov namespace "$TA" /kb/sub | field namespace_id)
  52. NSS=$(prov namespace "$TA" /secret | field namespace_id); NSB=$(prov namespace "$TB" /kb | field namespace_id)
  53. [ -n "$NS" ] && [ -n "$NSUB" ] && [ -n "$NSS" ] && [ -n "$NSB" ] && [ -n "$OK" ] || { echo "setup failed"; exit 2; }
  54. M1=$(remember "$WK" "$NS" semantic "Pelican port" "The pelican service listens on port 9100." ',"tags":["ports","pelican"],"confidence":0.75')
  55. code "$WK" PATCH /memories/$M1 -H 'If-Match: 1' -d '{"content":"The pelican service listens on port 9200.","change_reason":"moved"}' >/dev/null
  56. verify "$OK" "$M1" 2
  57. 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:]')
  58. M2=$(rememberj "$WK" "$NSUB" lesson "Escapes <b>" "$M2C")
  59. M3=$(remember "$WK" "$NS" semantic "Old pelican host" "Pelican ran on host alpha.")
  60. code "$OK" POST /memories/$M3/retire >/dev/null
  61. MS=$(remember "$OK" "$NSS" semantic "Pelican secret" "The pelican vault key is in safe nine.")
  62. 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.\"}"
  63. 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)
  64. CH=$(body "$RK" POST /search -d '{"query":"pelican 9200"}' | jq_ "d['results'][0]['chunk_id']" 2>/dev/null)
  65. # evidence: a candidate citing M1 and the chunk (readable) and the secret memory (owner only), accepted by the owner
  66. 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)
  67. M4=$(body "$OK" POST /candidates/$C1/review -d '{"decision":"accept","verify":true}' | jget resulting_memory_id)
  68. MB=$(remember "$BK" "$NSB" semantic "B pelican" "Tenant B pelican fact.")
  69. [ -n "$M1" ] && [ -n "$M2" ] && [ -n "$DOC" ] && [ -n "$CH" ] && [ -n "$M4" ] && [ -n "$MB" ] || { echo "data setup failed"; exit 2; }
  70. # ---- export ----------------------------------------------------------------------------------------------------
  71. docker restart axonasp >/dev/null; for i in $(seq 1 20); do curl -s -o /dev/null "$BASE/health/live" && break; sleep 1; done
  72. check "cold: owner export -> 200" "200" "$(export_ "$OK" "$TMP/owner.json")"
  73. E="$TMP/owner.json"
  74. 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")"
  75. check "integrity digest valid" "True" "$(digest_ok "$E")"
  76. 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")"
  77. 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")"
  78. 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")"
  79. 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")"
  80. 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")"
  81. 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)"
  82. export_ "$RK" "$TMP/reader.json" >/dev/null
  83. check "reader export: no secret namespace" "no" "$(has '/secret' "$(cat "$TMP/reader.json")")"
  84. check "reader export: secret memory id absent" "no" "$(has "$MS" "$(cat "$TMP/reader.json")")"
  85. check "reader export: unreadable evidence omitted" "1" "$(pyf "print(json.load(open(a[0],encoding='utf-8'))['counts']['evidence_links_omitted'])" "$TMP/reader.json")"
  86. export_ "$BLK" "$TMP/blind.json" >/dev/null
  87. 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")"
  88. export_ "$BK" "$TMP/b.json" >/dev/null
  89. check "tenant B export has only B" "yes no" "$(has "$MB" "$(cat "$TMP/b.json")") $(has "$M1" "$(cat "$TMP/b.json")")"
  90. export_ "$OK" "$TMP/sub.json" "{\"namespace_ids\":[\"$NSUB\"]}" >/dev/null
  91. 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")"
  92. 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")"
  93. check "export bad namespace_ids -> 422" "422" "$(code "$OK" POST /exports -d '{"namespace_ids":"x"}')"
  94. check "export no auth -> 401" "401" "$(curl -s -o /dev/null -w '%{http_code}' -X POST -d '{}' "$BASE/exports")"
  95. check "export wrong method -> 405" "405" "$(code "$OK" GET /exports)"
  96. # ---- import validation (nothing written) ------------------------------------------------------------------------
  97. 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"
  98. check "import wrong format -> 422" "422" "$(import_ "$BK" "$TMP/badfmt.json" | tail -1)"
  99. 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"
  100. check "import schema_version 2 -> 422" "unsupported_schema_version" "$(import_ "$BK" "$TMP/v2.json" | head -1 | jget code)"
  101. 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"
  102. check "tampered data -> integrity_mismatch" "integrity_mismatch" "$(import_ "$BK" "$TMP/tampered.json" | head -1 | jget code)"
  103. check "import into tenant without /secret -> 422" "422" "$(import_ "$BK" "$E" | tail -1)"
  104. export_ "$OK" "$TMP/kb.json" "{\"namespace_ids\":[\"$NS\"]}" >/dev/null
  105. check "import into existing ids -> 409" "409" "$(import_ "$BK" "$TMP/kb.json" | tail -1)"
  106. 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")"
  107. check "import by non-admin -> 422" "422" "$(import_ "$RK" "$TMP/sub.json" | tail -1)"
  108. check "import empty body -> 400" "400" "$(code "$OK" POST /imports)"
  109. check "import invalid JSON -> 400" "400" "$(code "$OK" POST /imports -d '{"format":')"
  110. python -I -c "import sys;open(sys.argv[1],'w').write('{\"pad\":\"'+'x'*(9*1024*1024)+'\"}')" "$TMP/big.json"
  111. 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")"
  112. # ---- round trip: purge tenant A, recreate its namespaces, import, export again ----------------------------------
  113. prov purge "$TA" >/dev/null
  114. TA2=$(prov tenant "port-A2" | field tenant_id); TENANTS+=("$TA2")
  115. mk "$TA2" restorer human; RSID=$P_ID; RSK=$P_KEY
  116. prov grant "$RSID" /kb admin 1 >/dev/null; prov grant "$RSID" /secret admin 1 >/dev/null
  117. prov namespace "$TA2" /kb >/dev/null; prov namespace "$TA2" /kb/sub >/dev/null; prov namespace "$TA2" /secret >/dev/null
  118. docker restart axonasp >/dev/null; for i in $(seq 1 20); do curl -s -o /dev/null "$BASE/health/live" && break; sleep 1; done
  119. R=$(import_ "$RSK" "$E")
  120. check "cold: import into clean tenant -> 201" "201" "$(tail -1 <<<"$R")"
  121. 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'])")"
  122. R=$(body "$RSK" GET /memories/$M1)
  123. check "imported memory: same id, revision 2" "2" "$(echo "$R" | jq_ "d['data']['current_revision']")"
  124. check "imported memory: verified" "verified" "$(echo "$R" | jq_ "d['data']['verification_status']")"
  125. check "imported memory: provenance" "$WID" "$(echo "$R" | jq_ "d['data']['created_by']")"
  126. check "imported memory: tags" "['ports', 'pelican']" "$(echo "$R" | jq_ "d['data']['tags']")"
  127. check "imported history: 2 versions" "2" "$(body "$RSK" GET /memories/$M1/versions | jq_ "len(d['data'])")"
  128. 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'")"
  129. check "imported retired memory stays retired" "retired" "$(body "$RSK" GET /memories/$M3 | jq_ "d['data']['status']")"
  130. 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'")"
  131. 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'")"
  132. check "document keeps revision 2" "2" "$(body "$RSK" GET /documents/$DOC | jq_ "d['data']['current_revision']")"
  133. check "imported evidence available" "3" "$(body "$RSK" GET /memories/$M4/sources | jq_ "len([e for e in d['evidence'] if e['available']])")"
  134. export_ "$RSK" "$TMP/again.json" >/dev/null
  135. 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")"
  136. check "importing twice -> 409" "409" "$(import_ "$RSK" "$E" | tail -1)"
  137. echo "passed: $PASS failed: $FAIL"
  138. for f in "${FAILED[@]:-}"; do [ -n "$f" ] && echo " FAIL: $f"; done
  139. [ "$FAIL" -eq 0 ]

Powered by TurnKey Linux.