25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

214 lines
24KB

  1. #!/usr/bin/env bash
  2. # Graph relationship checks (spec FR-023, section 8.1, section 14, ADR-014): entities, POST /relate with required
  3. # evidence, review (verify, no self-review without admin), listing and fetching edges, bounded traversal
  4. # (POST /graph/traverse: depth, direction, types, node limit, proposed edges, validity window, retired memories)
  5. # and the visibility rule: an edge whose namespace or either endpoint the caller cannot read does not exist for the
  6. # caller, so traversal never reveals hidden nodes or edges. Also deletion cascades (forget a memory, delete an
  7. # entity), tenant isolation, validation (422), 404/405, UTF-8 and a cold first request.
  8. #
  9. # Needs the container from docker-compose.yml running. Provisions two throw-away tenants and purges them at the end.
  10. # bash tests/phase4-graph.sh
  11. set -u
  12. BASE=${BASE:-http://localhost:8801/api/v1}
  13. PASS=0; FAIL=0; FAILED=(); TENANTS=()
  14. TMP=$(mktemp -d)
  15. prov() {
  16. MSYS_NO_PATHCONV=1 docker exec -u axonasp -e SERVER_WEB_ROOT=/opt/axonasp/site \
  17. -e "PROV_ACTION=$1" -e "PROV_ARG1=${2:-}" -e "PROV_ARG2=${3:-}" -e "PROV_ARG3=${4:-}" -e "PROV_ARG4=${5:-}" \
  18. axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/provision.asp 2>&1 | tr -d '\015'
  19. }
  20. field() { sed -n "s/^$1: *\([^ ]*\).*/\1/p" | head -1; }
  21. cleanup() { for t in "${TENANTS[@]}"; do prov purge "$t" >/dev/null; done; rm -rf "$TMP"; }
  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. jq_() { python -I -c "import sys,json;sys.stdin.reconfigure(encoding='utf-8');d=json.load(sys.stdin);print($1)" | tr -d '\015'; }
  27. mk() { local out; out=$(prov principal "$1" "$2" "$3"); P_ID=$(echo "$out" | field principal_id); P_KEY=$(echo "$out" | field api_key); }
  28. ref() { printf '{"kind":"%s","id":"%s"}' "$1" "$2"; }
  29. ev() { printf '[{"kind":"%s","id":"%s"}]' "$1" "$2"; }
  30. # relate <key> <ns> <srcKind> <srcId> <type> <tgtKind> <tgtId> <evidence json> [extra json fields]
  31. relate() { body "$1" POST /relate -d "{\"namespace_id\":\"$2\",\"source\":$(ref "$3" "$4"),\"type\":\"$5\",\"target\":$(ref "$6" "$7"),\"evidence\":$8${9:+,$9}}"; }
  32. accept() { body "$1" POST "/relationships/$2/review" -d '{"decision":"accept"}' | jq_ "d.get('state')"; }
  33. entity() { body "$1" POST /entities -d "{\"namespace_id\":\"$2\",\"type\":\"$3\",\"name\":\"$4\"${5:+,$5}}" | jq_ "d['data']['id']"; }
  34. traverse() { body "$1" POST /graph/traverse -d "$2"; }
  35. ids() { jq_ "' '.join(sorted(n['id'][:8] for n in d['nodes']))"; }
  36. pyf() { python -I -c "import sys,json,hashlib;a=sys.argv[2:];$1" "$@" | tr -d '\015'; }
  37. export_() { curl -s -o "$2" -w '%{http_code}' -X POST -H "Authorization: Bearer $1" -d '{}' "$BASE/exports"; }
  38. import_() { curl -s -w '\n%{http_code}' -X POST -H "Authorization: Bearer $1" --data-binary @"$2" "$BASE/imports"; }
  39. # ---- setup ------------------------------------------------------------------------------------------------------
  40. TA=$(prov tenant "graph-A" | field tenant_id); TB=$(prov tenant "graph-B" | field tenant_id); TENANTS=("$TA" "$TB")
  41. mk "$TA" writer agent; WID=$P_ID; WK=$P_KEY
  42. mk "$TA" reviewer human; RID=$P_ID; RK=$P_KEY
  43. mk "$TA" limited agent; LID=$P_ID; LK=$P_KEY
  44. mk "$TA" owner human; AID=$P_ID; AK=$P_KEY
  45. mk "$TB" other agent; BID=$P_ID; BK=$P_KEY
  46. NS=$(prov namespace "$TA" /kb | field namespace_id)
  47. PUB=$(prov namespace "$TA" /kb/pub | field namespace_id)
  48. SEC=$(prov namespace "$TA" /kb/secret | field namespace_id)
  49. NSB=$(prov namespace "$TB" /kb | field namespace_id)
  50. prov grant "$WID" /kb "read,write" 1 >/dev/null
  51. prov grant "$RID" /kb "read,write,verify" 1 >/dev/null
  52. prov grant "$LID" /kb/pub "read" 0 >/dev/null
  53. prov grant "$AID" /kb "read,write,verify,delete,admin" 1 >/dev/null
  54. prov grant "$BID" /kb "read,write" 1 >/dev/null
  55. [ -n "$SEC" ] && [ -n "$WK" ] && [ -n "$BK" ] || { echo "setup failed"; exit 2; }
  56. # ---- cold start: the first request after a restart creates an entity ------------------------------------------------------
  57. docker restart axonasp >/dev/null; for i in $(seq 1 20); do curl -s -o /dev/null "$BASE/health/live" && break; sleep 1; done
  58. R=$(body "$WK" POST /entities -d "{\"namespace_id\":\"$PUB\",\"type\":\"component\",\"name\":\" Gate Scanner \",\"aliases\":[\"OCR gate\",\"pelican cam\"],\"properties\":{\"vendor\":\"Acme\"}}")
  59. E1=$(echo "$R" | jq_ "d['data']['id']")
  60. check "cold: create entity -> canonical key normalized" "gate scanner|Gate Scanner|2|Acme" "$(echo "$R" | jq_ "'|'.join([d['data']['canonical_key'],d['data']['name'],str(len(d['data']['aliases'])),d['data']['properties']['vendor']])")"
  61. E2=$(entity "$WK" "$PUB" component "Yard API")
  62. E3=$(entity "$WK" "$SEC" component "Vault Signer")
  63. UTF=$(python -I -c "print('Gr'+chr(92)+'u00fc'+chr(92)+'u00dfe '+chr(92)+'u65e5')")
  64. EU=$(entity "$WK" "$PUB" concept "$UTF")
  65. check "UTF-8 entity name round trip" "yes" "$(body "$WK" GET "/entities/$EU" | jq_ "'yes' if d['data']['name']=='Gr'+chr(252)+chr(223)+'e '+chr(0x65e5) else 'no'")"
  66. R=$(body "$WK" POST /entities -d "{\"namespace_id\":\"$PUB\",\"type\":\"component\",\"name\":\"GATE scanner\"}")
  67. check "duplicate entity -> 409 with existing id" "entity_exists $E1" "$(echo "$R" | jq_ "d['error']['code']+' '+d['error']['existing_id']")"
  68. check "entity bad type -> 422" "422" "$(code "$WK" POST /entities -d "{\"namespace_id\":\"$PUB\",\"type\":\"Bad Type\",\"name\":\"x\"}")"
  69. check "entity without name -> 422" "422" "$(code "$WK" POST /entities -d "{\"namespace_id\":\"$PUB\",\"type\":\"component\"}")"
  70. check "entity aliases not an array -> 422" "422" "$(code "$WK" POST /entities -d "{\"namespace_id\":\"$PUB\",\"type\":\"component\",\"name\":\"y\",\"aliases\":\"x\"}")"
  71. check "entity without write permission -> 404" "404" "$(code "$LK" POST /entities -d "{\"namespace_id\":\"$PUB\",\"type\":\"component\",\"name\":\"z\"}")"
  72. check "entity list: alias search" "$E1" "$(body "$LK" GET "/entities?q=pelican" | jq_ "' '.join(e['id'] for e in d['data'])")"
  73. check "entity list: type filter, hidden namespace left out" "2" "$(body "$LK" GET "/entities?type=component" | jq_ "len(d['data'])")"
  74. check "entity in unreadable namespace -> 404" "404" "$(code "$LK" GET "/entities/$E3")"
  75. check "entity of another tenant -> 404" "404" "$(code "$BK" GET "/entities/$E1")"
  76. R=$(body "$WK" PATCH "/entities/$E2" -d '{"aliases":["yard gateway"],"description":"REST API of the yard"}')
  77. check "PATCH entity aliases and description" "yard gateway|REST API of the yard" "$(echo "$R" | jq_ "d['data']['aliases'][0]+'|'+d['data']['description']")"
  78. check "PATCH entity type -> 422" "422" "$(code "$WK" PATCH "/entities/$E2" -d '{"type":"concept"}')"
  79. check "PATCH entity by reader -> 404" "404" "$(code "$LK" PATCH "/entities/$E2" -d '{"name":"x"}')"
  80. # memories and a document as graph nodes
  81. M1=$(body "$WK" POST /remember -d "{\"namespace_id\":\"$PUB\",\"type\":\"procedural\",\"title\":\"Restart the gate scanner\",\"content\":\"Power-cycle the scanner, then recalibrate.\"}" | jq_ "d['id']")
  82. M2=$(body "$WK" POST /remember -d "{\"namespace_id\":\"$SEC\",\"type\":\"semantic\",\"title\":\"Signer key location\",\"content\":\"Kept in the vault.\"}" | jq_ "d['id']")
  83. M3=$(body "$WK" POST /remember -d "{\"namespace_id\":\"$PUB\",\"type\":\"semantic\",\"title\":\"Scanner firmware note\",\"content\":\"Firmware 2.1 fixes glare.\"}" | jq_ "d['id']")
  84. D1=$(body "$WK" POST /ingestion/jobs -d "{\"namespace_id\":\"$PUB\",\"title\":\"Scanner manual\",\"format\":\"markdown\",\"content\":\"# Scanner\\nCalibrate weekly.\"}" | jq_ "d['document_id']")
  85. [ -n "$M1" ] && [ -n "$D1" ] || { echo "data setup failed"; exit 2; }
  86. MB=$(body "$BK" POST /remember -d "{\"namespace_id\":\"$NSB\",\"type\":\"semantic\",\"title\":\"B fact\",\"content\":\"tenant B\"}" | jq_ "d['id']")
  87. # ---- relate: validation --------------------------------------------------------------------------------------------------
  88. check "relate without evidence -> 422" "422" "$(code "$WK" POST /relate -d "{\"namespace_id\":\"$PUB\",\"source\":$(ref entity "$E1"),\"type\":\"DEPENDS_ON\",\"target\":$(ref entity "$E2")}")"
  89. check "relate empty evidence -> 422 mentions evidence" "yes" "$(relate "$WK" "$PUB" entity "$E1" DEPENDS_ON entity "$E2" '[]' | jq_ "'yes' if 'evidence' in str(d['error']['details']) else 'no'")"
  90. check "relate bad type -> 422" "422" "$(code "$WK" POST /relate -d "{\"namespace_id\":\"$PUB\",\"source\":$(ref entity "$E1"),\"type\":\"depends on\",\"target\":$(ref entity "$E2"),\"evidence\":$(ev memory "$M1")}")"
  91. check "relate self-loop -> 422" "422" "$(code "$WK" POST /relate -d "{\"namespace_id\":\"$PUB\",\"source\":$(ref entity "$E1"),\"type\":\"IS_A\",\"target\":$(ref entity "$E1"),\"evidence\":$(ev memory "$M1")}")"
  92. check "relate bad kind -> 422" "422" "$(code "$WK" POST /relate -d "{\"namespace_id\":\"$PUB\",\"source\":$(ref chunk "$E1"),\"type\":\"IS_A\",\"target\":$(ref entity "$E2"),\"evidence\":$(ev memory "$M1")}")"
  93. check "relate missing target -> 422" "422" "$(code "$WK" POST /relate -d "{\"namespace_id\":\"$PUB\",\"source\":$(ref entity "$E1"),\"type\":\"IS_A\",\"evidence\":$(ev memory "$M1")}")"
  94. check "relate endpoint of another tenant -> 422 not found" "source was not found." "$(relate "$WK" "$PUB" memory "$MB" RELATES_TO entity "$E1" "$(ev memory "$M1")" | jq_ "d['error']['details'][0]")"
  95. check "relate validity window reversed -> 422" "422" "$(code "$WK" POST /relate -d "{\"namespace_id\":\"$PUB\",\"source\":$(ref entity "$E1"),\"type\":\"IS_A\",\"target\":$(ref entity "$E2"),\"evidence\":$(ev memory "$M1"),\"valid_from\":\"2027-01-01 00:00:00\",\"valid_until\":\"2026-01-01 00:00:00\"}")"
  96. check "relate without write permission -> 404" "404" "$(code "$LK" POST /relate -d "{\"namespace_id\":\"$PUB\",\"source\":$(ref entity "$E1"),\"type\":\"IS_A\",\"target\":$(ref entity "$E2"),\"evidence\":$(ev memory "$M1")}")"
  97. check "GET /relate -> 405" "405" "$(code "$WK" GET /relate)"
  98. # ---- relate, review ------------------------------------------------------------------------------------------------------
  99. R=$(body "$WK" POST /relate -H "Idempotency-Key: rel-1" -d "{\"namespace_id\":\"$PUB\",\"source\":$(ref entity "$E1"),\"type\":\"depends_on\",\"target\":$(ref entity "$E2"),\"evidence\":[{\"kind\":\"memory\",\"id\":\"$M1\"},{\"kind\":\"memory\",\"id\":\"$M2\",\"role\":\"context\"}],\"confidence\":0.9,\"description\":\"scanner calls the API\"}")
  100. R1=$(echo "$R" | jq_ "d['id']")
  101. check "relate -> proposed, type upper-cased, 2 evidence" "proposed DEPENDS_ON 2" "$(echo "$R" | jq_ "d['state']+' '+d['type']+' '+str(d['evidence_count'])")"
  102. check "relate idempotent replay -> same id" "$R1" "$(body "$WK" POST /relate -H "Idempotency-Key: rel-1" -d "{\"namespace_id\":\"$PUB\",\"source\":$(ref entity "$E1"),\"type\":\"depends_on\",\"target\":$(ref entity "$E2"),\"evidence\":[{\"kind\":\"memory\",\"id\":\"$M1\"},{\"kind\":\"memory\",\"id\":\"$M2\",\"role\":\"context\"}],\"confidence\":0.9,\"description\":\"scanner calls the API\"}" | jq_ "d['id']")"
  103. check "duplicate live relationship -> 409 with existing id" "relationship_exists $R1" "$(relate "$WK" "$PUB" entity "$E1" DEPENDS_ON entity "$E2" "$(ev memory "$M1")" | jq_ "d['error']['code']+' '+d['error']['existing_id']")"
  104. check "review by author without verify -> 404" "404" "$(code "$WK" POST "/relationships/$R1/review" -d '{"decision":"accept"}')"
  105. check "review bad decision -> 422" "422" "$(code "$RK" POST "/relationships/$R1/review" -d '{"decision":"maybe"}')"
  106. check "review by verifier -> accepted" "accepted" "$(accept "$RK" "$R1")"
  107. check "review twice -> 409" "409" "$(code "$RK" POST "/relationships/$R1/review" -d '{"decision":"reject"}')"
  108. RS=$(relate "$RK" "$PUB" entity "$E2" PART_OF entity "$EU" "$(ev memory "$M1")" | jq_ "d['id']")
  109. check "self-review without admin -> 403" "403" "$(code "$RK" POST "/relationships/$RS/review" -d '{"decision":"accept"}')"
  110. check "reject -> rejected" "rejected" "$(body "$AK" POST "/relationships/$RS/review" -d '{"decision":"reject","notes":"not a part"}' | jq_ "d['state']")"
  111. check "rejected edge can be proposed again" "proposed" "$(relate "$RK" "$PUB" entity "$E2" PART_OF entity "$EU" "$(ev memory "$M1")" | jq_ "d['state']")"
  112. # the graph: E1 -DEPENDS_ON-> E2 -DESCRIBED_BY-> M1 -VERIFIED_BY-> D1 (pub); E1 -DEPENDS_ON-> E3 (secret endpoint);
  113. # E1 -CALLS-> E2 in the secret namespace; E2 -PART_OF-> E1 proposed only; expired and future edges; M3 -> E1
  114. R2=$(relate "$WK" "$PUB" entity "$E2" DESCRIBED_BY memory "$M1" "$(ev memory "$M1")" | jq_ "d['id']"); accept "$RK" "$R2" >/dev/null
  115. R3=$(relate "$WK" "$PUB" memory "$M1" VERIFIED_BY document "$D1" "$(ev document "$D1")" | jq_ "d['id']"); accept "$RK" "$R3" >/dev/null
  116. R4=$(relate "$WK" "$PUB" entity "$E1" DEPENDS_ON entity "$E3" "$(ev memory "$M2")" | jq_ "d['id']"); accept "$RK" "$R4" >/dev/null
  117. R5=$(relate "$WK" "$SEC" entity "$E1" CALLS entity "$E2" "$(ev memory "$M2")" | jq_ "d['id']"); accept "$RK" "$R5" >/dev/null
  118. R6=$(relate "$WK" "$PUB" entity "$E2" PART_OF entity "$E1" "$(ev memory "$M1")" | jq_ "d['id']")
  119. R7=$(relate "$WK" "$PUB" entity "$E1" SUPERSEDES entity "$EU" "$(ev memory "$M1")" '"valid_until":"2020-01-01 00:00:00"' | jq_ "d['id']"); accept "$RK" "$R7" >/dev/null
  120. R8=$(relate "$WK" "$PUB" entity "$E1" IMPLEMENTS entity "$EU" "$(ev memory "$M1")" '"valid_from":"2099-01-01 00:00:00","inferred":true' | jq_ "d['id']"); accept "$RK" "$R8" >/dev/null
  121. R9=$(relate "$WK" "$PUB" memory "$M3" RELATES_TO entity "$E1" "$(ev memory "$M3")" | jq_ "d['id']"); accept "$RK" "$R9" >/dev/null
  122. [ -n "$R9" ] && [ -n "$R5" ] || { echo "graph setup failed"; exit 2; }
  123. s8() { for x in "$@"; do echo "${x:0:8}"; done | sort | tr '\n' ' ' | sed 's/ $//'; }
  124. # ---- fetch and list -------------------------------------------------------------------------------------------------------
  125. R=$(body "$LK" GET "/relationships/$R1")
  126. check "reader fetches edge with evidence; hidden evidence has no id" "accepted|False:-|True:$M1" "$(echo "$R" | jq_ "d['data']['state']+'|'+'|'.join(sorted(str(e['available'])+':'+e.get('id','-') for e in d['data']['evidence']))")"
  127. check "edge with a hidden endpoint -> 404" "404" "$(code "$LK" GET "/relationships/$R4")"
  128. check "edge in a hidden namespace -> 404" "404" "$(code "$LK" GET "/relationships/$R5")"
  129. check "edge of another tenant -> 404" "404" "$(code "$BK" GET "/relationships/$R1")"
  130. check "unknown edge id -> 404" "404" "$(code "$WK" GET /relationships/00000000-0000-0000-0000-000000000000)"
  131. R=$(body "$LK" GET "/relationships?limit=200")
  132. check "list: reader sees only visible edges" "9 none" "$(echo "$R" | jq_ "str(len(d['data']))+' '+(' '.join(x[:8] for x in ['$R4','$R5','$E3','$M2'] if x in json.dumps(d)) or 'none')")"
  133. check "list: node filter" "$(s8 "$R2" "$R3")" "$(body "$WK" GET "/relationships?node_kind=memory&node_id=$M1" | jq_ "' '.join(sorted(r['id'][:8] for r in d['data']))")"
  134. check "list: bad node_kind -> 422" "422" "$(code "$WK" GET "/relationships?node_kind=chunk&node_id=$M1")"
  135. # ---- traversal ------------------------------------------------------------------------------------------------------------
  136. check "traverse depth 1 (writer): neighbours incl. secret" "$(s8 "$E1" "$E2" "$E3" "$M3")" "$(traverse "$WK" "{\"start\":$(ref entity "$E1"),\"max_depth\":1}" | ids)"
  137. R=$(traverse "$WK" "{\"start\":$(ref entity "$E1"),\"max_depth\":1}")
  138. check "traverse depth 1 edges (CALLS edge in secret ns visible to writer)" "$(s8 "$R1" "$R4" "$R5" "$R9")" "$(echo "$R" | jq_ "' '.join(sorted(e['id'][:8] for e in d['edges']))")"
  139. check "traverse depth 3 (writer) reaches the document" "$(s8 "$E1" "$E2" "$E3" "$M1" "$M3" "$D1")" "$(traverse "$WK" "{\"start\":$(ref entity "$E1"),\"max_depth\":3}" | ids)"
  140. R=$(traverse "$LK" "{\"start\":$(ref entity "$E1"),\"max_depth\":3}")
  141. check "reader traversal: hidden node and edges left out" "$(s8 "$E1" "$E2" "$M1" "$M3" "$D1")" "$(echo "$R" | ids)"
  142. check "reader traversal: no hidden id anywhere in the response" "none" "$(echo "$R" | jq_ "' '.join(x for x in ['$E3','$R4','$R5','$M2','$SEC'] if x in json.dumps(d)) or 'none'")"
  143. check "node depth and labels" "0 1 2 3|Restart the gate scanner|untrusted_reference" "$(echo "$R" | jq_ "' '.join(str(x) for x in sorted(set(n['depth'] for n in d['nodes'])))+'|'+[n['label'] for n in d['nodes'] if n['kind']=='memory' and n['depth']==2][0]+'|'+[n for n in d['nodes'] if n['kind']=='document'][0]['content_trust']")"
  144. check "direction out from M1" "$(s8 "$M1" "$D1")" "$(traverse "$LK" "{\"start\":$(ref memory "$M1"),\"direction\":\"out\",\"max_depth\":3}" | ids)"
  145. check "direction in from M1" "$(s8 "$M1" "$E2" "$E1" "$M3")" "$(traverse "$LK" "{\"start\":$(ref memory "$M1"),\"direction\":\"in\",\"max_depth\":3}" | ids)"
  146. check "types filter" "$(s8 "$M1" "$D1")" "$(traverse "$LK" "{\"start\":$(ref memory "$M1"),\"types\":[\"verified_by\"],\"max_depth\":3}" | ids)"
  147. check "proposed edges only on request" "no yes" "$(traverse "$LK" "{\"start\":$(ref entity "$E2"),\"max_depth\":1}" | jq_ "'yes' if '$R6' in json.dumps(d) else 'no'") $(traverse "$LK" "{\"start\":$(ref entity "$E2"),\"max_depth\":1,\"include_proposed\":true}" | jq_ "'yes' if '$R6' in json.dumps(d) else 'no'")"
  148. check "expired and not-yet-valid edges left out" "none" "$(traverse "$WK" "{\"start\":$(ref entity "$EU"),\"max_depth\":1}" | jq_ "' '.join(x[:8] for x in ['$R7','$R8'] if x in json.dumps(d)) or 'none'")"
  149. R=$(traverse "$WK" "{\"start\":$(ref entity "$E1"),\"max_depth\":3,\"max_nodes\":2}")
  150. check "max_nodes bounds the result and sets truncated" "2 True" "$(echo "$R" | jq_ "str(len(d['nodes']))+' '+str(d['truncated'])")"
  151. check "edges only between returned nodes" "yes" "$(echo "$R" | jq_ "'yes' if all(e['source']['id'] in [n['id'] for n in d['nodes']] and e['target']['id'] in [n['id'] for n in d['nodes']] for e in d['edges']) else 'no'")"
  152. check "untruncated result says so" "False" "$(traverse "$WK" "{\"start\":$(ref entity "$E1"),\"max_depth\":3}" | jq_ "d['truncated']")"
  153. check "traverse start not readable -> 404" "404" "$(code "$LK" POST /graph/traverse -d "{\"start\":$(ref entity "$E3")}")"
  154. check "traverse start of another tenant -> 404" "404" "$(code "$BK" POST /graph/traverse -d "{\"start\":$(ref entity "$E1")}")"
  155. check "traverse max_depth 4 -> 422" "422" "$(code "$WK" POST /graph/traverse -d "{\"start\":$(ref entity "$E1"),\"max_depth\":4}")"
  156. check "traverse max_nodes 0 -> 422" "422" "$(code "$WK" POST /graph/traverse -d "{\"start\":$(ref entity "$E1"),\"max_nodes\":0}")"
  157. check "traverse bad direction -> 422" "422" "$(code "$WK" POST /graph/traverse -d "{\"start\":$(ref entity "$E1"),\"direction\":\"up\"}")"
  158. check "traverse bad types -> 422" "422" "$(code "$WK" POST /graph/traverse -d "{\"start\":$(ref entity "$E1"),\"types\":[\"no good\"]}")"
  159. check "traverse without start -> 422" "422" "$(code "$WK" POST /graph/traverse -d '{}')"
  160. check "GET /graph/traverse -> 405" "405" "$(code "$WK" GET /graph/traverse)"
  161. check "traverse without key -> 401" "401" "$(curl -s -o /dev/null -w '%{http_code}' -X POST -d '{}' "$BASE/graph/traverse")"
  162. # ---- export (schema version 2): entities, relationships and their evidence ---------------------------------------------
  163. check "owner export -> 200" "200" "$(export_ "$AK" "$TMP/a.json")"
  164. check "export version 2 with graph counts" "2 4 11 0" "$(pyf "d=json.load(open(a[0],encoding='utf-8'));c=d['counts'];print(d['schema_version'],c['entities'],c['relationships'],c['relationships_omitted'])" "$TMP/a.json")"
  165. check "edge evidence exported with owner_kind relationship" "2" "$(pyf "d=json.load(open(a[0],encoding='utf-8'))['data'];print(len([e for e in d['evidence_links'] if e['owner_kind']=='relationship' and e['owner_id']==a[1]]))" "$TMP/a.json" "$R1")"
  166. check "exported edge keeps state, validity and inferred flag" "proposed|2099-01-01 00:00:00 True" "$(pyf "d=json.load(open(a[0],encoding='utf-8'))['data']['relationships'];x={r['id']:r for r in d};print(x[a[1]]['state']+'|'+x[a[2]]['valid_from'],x[a[2]]['inferred'])" "$TMP/a.json" "$R6" "$R8")"
  167. export_ "$LK" "$TMP/l.json" >/dev/null
  168. check "reader export: hidden edges omitted, counted" "3 9 1" "$(pyf "c=json.load(open(a[0],encoding='utf-8'))['counts'];print(c['entities'],c['relationships'],c['relationships_omitted'])" "$TMP/l.json")"
  169. check "reader export: no hidden id" "none" "$(pyf "t=open(a[0],encoding='utf-8').read();print(' '.join(x[:8] for x in a[1:] if x in t) or 'none')" "$TMP/l.json" "$E3" "$R4" "$R5" "$M2")"
  170. # ---- lifecycle: retired memories, forget and entity deletion cascade -----------------------------------------------------
  171. check "retire M1" "200" "$(code "$WK" POST "/memories/$M1/retire" -d '{"reason":"replaced"}')"
  172. check "retired memory left out of traversal (and what lies behind it)" "$(s8 "$E1" "$E2" "$M3")" "$(traverse "$LK" "{\"start\":$(ref entity "$E1"),\"max_depth\":3}" | ids)"
  173. check "traversal may start at a retired memory" "$(s8 "$M1" "$D1" "$E2")" "$(traverse "$LK" "{\"start\":$(ref memory "$M1"),\"max_depth\":1}" | ids)"
  174. check "forget M3 (delete permission)" "200" "$(code "$AK" DELETE "/memories/$M3")"
  175. check "edges of a forgotten memory are deleted" "404 0" "$(code "$WK" GET "/relationships/$R9") $(body "$WK" GET "/relationships?node_kind=memory&node_id=$M3" | jq_ "len(d['data'])")"
  176. check "delete edge without delete permission -> 404" "404" "$(code "$WK" DELETE "/relationships/$R2")"
  177. check "delete edge" "200" "$(code "$AK" DELETE "/relationships/$R2")"
  178. check "deleted edge -> 404" "404" "$(code "$AK" GET "/relationships/$R2")"
  179. check "delete entity without delete permission -> 404" "404" "$(code "$WK" DELETE "/entities/$E1")"
  180. check "delete entity" "200" "$(code "$AK" DELETE "/entities/$E1")"
  181. check "entity edges deleted with it" "404 404 404" "$(code "$AK" GET "/relationships/$R1") $(code "$AK" GET "/relationships/$R5") $(code "$AK" GET "/entities/$E1")"
  182. # ---- import (schema version 2) into a clean tenant: the graph survives the round trip (AC-14) ---------------------------
  183. prov purge "$TA" >/dev/null
  184. TC=$(prov tenant "graph-C" | field tenant_id); TENANTS+=("$TC")
  185. mk "$TC" restorer human; CID=$P_ID; CK=$P_KEY
  186. prov grant "$CID" /kb "read,write,verify,delete,admin" 1 >/dev/null
  187. prov namespace "$TC" /kb >/dev/null; prov namespace "$TC" /kb/pub >/dev/null; prov namespace "$TC" /kb/secret >/dev/null
  188. # an edge whose endpoint is not part of the export is refused (digest recomputed so only the content is wrong)
  189. pyf "d=json.load(open(a[0],encoding='utf-8'));d['data']['entities']=[e for e in d['data']['entities'] if e['id']!=a[2]];t=json.dumps(d['data'],ensure_ascii=False,separators=(',',':'));d['integrity']['digest']=hashlib.sha256(t.encode('utf-8')).hexdigest();open(a[1],'w',encoding='utf-8').write(json.dumps(d,ensure_ascii=False,separators=(',',':')))" "$TMP/a.json" "$TMP/bad.json" "$E3"
  190. check "import: edge endpoint missing from the export -> 422" "422 yes" "$(import_ "$CK" "$TMP/bad.json" | tr '\n' ' ' | python -I -c "import sys;t=sys.stdin.read();print(t.strip()[-3:], 'yes' if 'of this export' in t else 'no')")"
  191. R=$(import_ "$CK" "$TMP/a.json")
  192. check "import version 2 -> 201 with graph counts" "201 4 11" "$(tail -1 <<<"$R") $(head -1 <<<"$R" | jq_ "str(d['imported']['entities'])+' '+str(d['imported']['relationships'])")"
  193. check "imported graph traverses like the original" "$(s8 "$E1" "$E2" "$E3" "$M1" "$M3" "$D1")" "$(traverse "$CK" "{\"start\":$(ref entity "$E1"),\"max_depth\":3}" | ids)"
  194. check "imported edge keeps evidence and provenance" "2 $WID $RID" "$(body "$CK" GET "/relationships/$R1" | jq_ "str(len(d['data']['evidence']))+' '+d['data']['author']+' '+d['data']['reviewer']")"
  195. check "imported proposed edge stays proposed" "proposed" "$(body "$CK" GET "/relationships/$R6" | jq_ "d['data']['state']")"
  196. export_ "$CK" "$TMP/c.json" >/dev/null
  197. 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)" "$TMP/a.json" "$TMP/c.json")"
  198. check "importing twice -> 409" "409" "$(import_ "$CK" "$TMP/a.json" | tail -1)"
  199. echo "passed: $PASS failed: $FAIL"
  200. for f in "${FAILED[@]}"; do echo " FAIL: $f"; done
  201. [ "$FAIL" -eq 0 ]

Powered by TurnKey Linux.