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

569 строки
23KB

  1. <%
  2. '=======================================================================================================================
  3. ' Api support for the memory platform JSON API (/api/v1/...).
  4. '
  5. ' Plain global functions (no native object is held across calls: G3CRYPTO is created per use, see AGENTS.md).
  6. ' Per-request identity lives in Api_TenantId / Api_PrincipalId, set by Api_Authenticate().
  7. '
  8. ' Authentication : "Authorization: Bearer <key>"; only the SHA-256 of a key is stored (table api_keys).
  9. ' Authorization : scope is not permission. A principal can touch a namespace only through an access_grants row
  10. ' on that namespace (or an ancestor when the grant has inherit = 1). Permissions: read, write,
  11. ' delete, admin (admin implies all). Anything the caller may not see is reported as 404.
  12. ' Errors : {"error":{"code":"...","message":"...","request_id":"..."}}
  13. '=======================================================================================================================
  14. Dim Api_TenantId, Api_PrincipalId, Api_RequestIdValue
  15. Api_TenantId = ""
  16. Api_PrincipalId = ""
  17. Api_RequestIdValue = ""
  18. '-----------------------------------------------------------------------------------------------------------------------
  19. ' Identifiers, time, hashing
  20. '-----------------------------------------------------------------------------------------------------------------------
  21. Function Api_NewId()
  22. Dim c
  23. Set c = Server.CreateObject("G3CRYPTO")
  24. Api_NewId = LCase(c.UUID())
  25. End Function
  26. Function Api_Sha256(text)
  27. Dim c
  28. Set c = Server.CreateObject("G3CRYPTO")
  29. Api_Sha256 = LCase(c.SHA256("" & text))
  30. End Function
  31. ' UTC timestamp as 'YYYY-MM-DD HH:MM:SS'. The container runs in UTC, so Now() is UTC.
  32. Function Api_Now()
  33. Dim d
  34. d = Now()
  35. Api_Now = Year(d) & "-" & Right("0" & Month(d), 2) & "-" & Right("0" & Day(d), 2) & " " & _
  36. Right("0" & Hour(d), 2) & ":" & Right("0" & Minute(d), 2) & ":" & Right("0" & Second(d), 2)
  37. End Function
  38. Function Api_RequestId()
  39. Dim re, h
  40. If Len(Api_RequestIdValue) = 0 Then
  41. ' A caller's X-Request-Id is kept for correlation when it is a plain token; otherwise a new id is made.
  42. h = "" & Request.ServerVariables("HTTP_X_REQUEST_ID")
  43. Set re = New RegExp
  44. re.Pattern = "^[A-Za-z0-9._:-]{8,64}$"
  45. If re.Test(h) Then
  46. Api_RequestIdValue = h
  47. Else
  48. Api_RequestIdValue = "req-" & Api_NewId()
  49. End If
  50. End If
  51. Api_RequestId = Api_RequestIdValue
  52. End Function
  53. ' True for the opaque ids this API issues (UUID text). Used before an id goes anywhere near SQL or a path.
  54. Function Api_IsId(s)
  55. Dim t, i, c
  56. Api_IsId = False
  57. t = "" & s
  58. If Len(t) <> 36 Then Exit Function
  59. For i = 1 To 36
  60. c = Mid(t, i, 1)
  61. If i = 9 Or i = 14 Or i = 19 Or i = 24 Then
  62. If c <> "-" Then Exit Function
  63. Else
  64. If Not ((c >= "0" And c <= "9") Or (c >= "a" And c <= "f")) Then Exit Function
  65. End If
  66. Next
  67. Api_IsId = True
  68. End Function
  69. '-----------------------------------------------------------------------------------------------------------------------
  70. ' Responses
  71. '-----------------------------------------------------------------------------------------------------------------------
  72. Function Api_StatusLine(status)
  73. Select Case status
  74. Case 200: Api_StatusLine = "200 OK"
  75. Case 201: Api_StatusLine = "201 Created"
  76. Case 400: Api_StatusLine = "400 Bad Request"
  77. Case 401: Api_StatusLine = "401 Unauthorized"
  78. Case 403: Api_StatusLine = "403 Forbidden"
  79. Case 404: Api_StatusLine = "404 Not Found"
  80. Case 405: Api_StatusLine = "405 Method Not Allowed"
  81. Case 409: Api_StatusLine = "409 Conflict"
  82. Case 412: Api_StatusLine = "412 Precondition Failed"
  83. Case 413: Api_StatusLine = "413 Payload Too Large"
  84. Case 422: Api_StatusLine = "422 Unprocessable Entity"
  85. Case 428: Api_StatusLine = "428 Precondition Required"
  86. Case 500: Api_StatusLine = "500 Internal Server Error"
  87. Case 503: Api_StatusLine = "503 Service Unavailable"
  88. Case Else: Api_StatusLine = status & " Status"
  89. End Select
  90. End Function
  91. Sub Api_Send(status, jsonText)
  92. Response.Clear
  93. Response.Status = Api_StatusLine(status)
  94. Response.ContentType = "application/json"
  95. Response.Charset = "utf-8"
  96. Response.AddHeader "X-Request-Id", Api_RequestId()
  97. Response.AddHeader "Cache-Control", "no-store"
  98. Response.Write jsonText
  99. Obs_Record status
  100. End Sub
  101. Sub Api_Error(status, code, message)
  102. Api_Send status, "{""error"":{""code"":" & JsonLite_Quote(code) & ",""message"":" & JsonLite_Quote(message) & _
  103. ",""request_id"":" & JsonLite_Quote(Api_RequestId()) & "}}"
  104. End Sub
  105. Sub Api_NotFound()
  106. Api_Error 404, "not_found", "Resource not found."
  107. End Sub
  108. Dim Api_LastDbError
  109. Api_LastDbError = ""
  110. ' Call straight after a failing statement (before any rollback) so the description is kept for Api_DbFailed.
  111. Sub Api_NoteDbError()
  112. Api_LastDbError = "" & Err.Description
  113. End Sub
  114. ' A failed database call becomes a JSON 500. The database text is only included when Environment = Development.
  115. Sub Api_DbFailed(errNumber, errDescription)
  116. Dim msg
  117. Err.Clear
  118. On Error GoTo 0
  119. msg = "Internal error (" & errNumber & "). The request was not completed."
  120. If LCase(GetAppSetting("Environment")) = "development" And Len(Api_LastDbError) > 0 Then
  121. msg = msg & " [dev] " & Api_LastDbError
  122. End If
  123. Api_Error 500, "internal_error", msg
  124. End Sub
  125. '-----------------------------------------------------------------------------------------------------------------------
  126. ' Request helpers
  127. '-----------------------------------------------------------------------------------------------------------------------
  128. Function Api_Header(name)
  129. Api_Header = Trim("" & Request.ServerVariables("HTTP_" & UCase(Replace(name, "-", "_"))))
  130. End Function
  131. ' Request body as UTF-8 text, or Empty after sending a 400.
  132. Function Api_ReadBody()
  133. Api_ReadBody = Api_ReadBodyMax(1048576)
  134. End Function
  135. ' Same with a caller-chosen size limit in bytes (imports accept more than ordinary writes).
  136. Function Api_ReadBodyMax(maxBytes)
  137. Dim n, text
  138. Api_ReadBodyMax = Empty
  139. n = Request.TotalBytes
  140. If n = 0 Then
  141. Api_Error 400, "empty_body", "Request body is empty. Send a JSON object."
  142. Exit Function
  143. End If
  144. If n > maxBytes Then
  145. Api_Error 413, "body_too_large", "Request body exceeds " & (maxBytes \ 1048576) & " MiB."
  146. Exit Function
  147. End If
  148. Api_Utf8Unsupported = False
  149. text = Api_Utf8Decode(CStr(Request.BinaryRead(n)))
  150. If JsonLite_Parse(text) Is Nothing Then
  151. Api_Error 400, "invalid_json", "Body must be a valid JSON object."
  152. Exit Function
  153. End If
  154. ' Reject rather than store damaged text (see Api_Utf8Decode)
  155. If Api_Utf8Unsupported Or JsonLite_SurrogateSeen Then
  156. Api_Error 422, "unsupported_character", "Characters above U+FFFF (for example emoji) are not supported yet. Remove or replace them."
  157. Exit Function
  158. End If
  159. Api_ReadBodyMax = text
  160. End Function
  161. Dim Api_Utf8Unsupported
  162. Api_Utf8Unsupported = False
  163. ' Decodes a string holding raw UTF-8 bytes (one byte per character, as AxonASP BinaryRead returns) into Unicode text.
  164. ' The bytes are split into alternating ASCII / non-ASCII runs with ONE call to the RegExp engine (character loops over a
  165. ' large body were quadratic on AxonASP and timed out). ASCII runs are copied; a strictly valid non-ASCII run is
  166. ' decoded natively (percent-encoded, then G3AXON AxUrlDecode); a run with invalid bytes, encoded surrogates or 4-byte
  167. ' sequences goes through Api_Utf8DecodeRun (U+FFFD, and Api_Utf8Unsupported for characters above U+FFFF).
  168. ' Match.FirstIndex is not used: on this build it is a byte offset into the runtime's UTF-8 string, not a character index.
  169. Function Api_Utf8Decode(ByVal s)
  170. Dim re, ms, m, sb, reOk, ax, v, enc, n
  171. Set re = Server.CreateObject("VBScript.RegExp")
  172. re.Global = True
  173. re.Pattern = "[\x00-\x7F]+|[\x80-\xFF]+"
  174. Set ms = re.Execute(s)
  175. If ms.Count <= 1 Then
  176. If ms.Count = 0 Then
  177. Api_Utf8Decode = s
  178. Exit Function
  179. End If
  180. If AscW(Left(s, 1)) < 128 Then
  181. If AscW(Left(s, 1)) >= 0 Then
  182. Api_Utf8Decode = s ' pure ASCII
  183. Exit Function
  184. End If
  185. End If
  186. End If
  187. ' well-formed UTF-8 of code points up to U+FFFF, excluding surrogates and overlong forms
  188. Set reOk = Server.CreateObject("VBScript.RegExp")
  189. reOk.Global = True
  190. reOk.Pattern = "[\xC2-\xDF][\x80-\xBF]|\xE0[\xA0-\xBF][\x80-\xBF]|[\xE1-\xEC\xEE\xEF][\x80-\xBF][\x80-\xBF]|\xED[\x80-\x9F][\x80-\xBF]"
  191. Set ax = Server.CreateObject("G3AXON.FUNCTIONS")
  192. Set sb = Server.CreateObject("G3STRINGBUILDER")
  193. For Each m In ms
  194. v = m.Value
  195. n = AscW(Left(v, 1))
  196. If n >= 0 And n < 128 Then
  197. sb.Append v
  198. ElseIf Len(reOk.Replace(v, "")) = 0 Then
  199. enc = v
  200. For n = 128 To 255
  201. enc = Replace(enc, ChrW(n), "%" & Hex(n))
  202. Next
  203. sb.Append ax.AxUrlDecode(enc)
  204. Else
  205. Api_Utf8DecodeRun v, sb
  206. End If
  207. Next
  208. Api_Utf8Decode = sb.ToString()
  209. Set sb = Nothing
  210. End Function
  211. ' Decodes one run of bytes >= 0x80 byte by byte (the slow path for runs that are not plain valid UTF-8). A sequence cut
  212. ' short at the end of the run is followed by an ASCII byte, so it is invalid there as well: U+FFFD, one byte at a time.
  213. Sub Api_Utf8DecodeRun(run, sb)
  214. Dim i, n, c, cp, extra, k, ok, b
  215. n = Len(run)
  216. i = 1
  217. Do While i <= n
  218. c = AscW(Mid(run, i, 1)) And 255
  219. extra = -1
  220. cp = 0
  221. If c >= 240 And c <= 247 Then
  222. extra = 3
  223. cp = c And 7
  224. ElseIf c >= 224 And c <= 239 Then
  225. extra = 2
  226. cp = c And 15
  227. ElseIf c >= 194 And c <= 223 Then
  228. extra = 1
  229. cp = c And 31
  230. End If
  231. ok = (extra > 0 And i + extra <= n)
  232. If ok Then
  233. For k = 1 To extra
  234. b = AscW(Mid(run, i + k, 1)) And 255
  235. If b < 128 Or b > 191 Then
  236. ok = False
  237. Else
  238. cp = cp * 64 + (b And 63)
  239. End If
  240. Next
  241. End If
  242. If ok And cp <= 1114111 Then
  243. ' On the pinned AxonASP build ChrW(cp > 65535) raises "Invalid procedure call" and a surrogate pair
  244. ' is written out as CESU-8, so code points above U+FFFF (and encoded surrogates) cannot be held.
  245. ' They become U+FFFD and set Api_Utf8Unsupported; Api_ReadBody then answers 422.
  246. If cp > 65535 Or (cp >= 55296 And cp <= 57343) Then
  247. Api_Utf8Unsupported = True
  248. sb.Append ChrW(65533)
  249. Else
  250. sb.Append ChrW(cp)
  251. End If
  252. i = i + extra + 1
  253. Else
  254. sb.Append ChrW(65533)
  255. i = i + 1
  256. End If
  257. Loop
  258. End Sub
  259. Function Api_ToInt(v, dflt, lo, hi)
  260. Dim s
  261. s = Trim("" & v)
  262. Api_ToInt = dflt
  263. If Len(s) > 0 Then
  264. If IsNumeric(s) Then
  265. Api_ToInt = CLng(s)
  266. End If
  267. End If
  268. If Api_ToInt < lo Then Api_ToInt = lo
  269. If Api_ToInt > hi Then Api_ToInt = hi
  270. End Function
  271. '-----------------------------------------------------------------------------------------------------------------------
  272. ' Authentication. Returns True and sets Api_TenantId / Api_PrincipalId; otherwise sends 401 and returns False.
  273. '-----------------------------------------------------------------------------------------------------------------------
  274. Function Api_Authenticate()
  275. Dim h, key, rs, expires, keyId
  276. Api_Authenticate = False
  277. Api_TenantId = ""
  278. Api_PrincipalId = ""
  279. h = Api_Header("Authorization")
  280. If LCase(Left(h, 7)) <> "bearer " Then
  281. Response.AddHeader "WWW-Authenticate", "Bearer"
  282. Api_Error 401, "unauthenticated", "Missing or malformed Authorization header. Use: Authorization: Bearer <api key>."
  283. Exit Function
  284. End If
  285. key = Trim(Mid(h, 8))
  286. If Len(key) < 16 Or Len(key) > 200 Then
  287. Response.AddHeader "WWW-Authenticate", "Bearer"
  288. Api_Error 401, "unauthenticated", "Invalid API key."
  289. Exit Function
  290. End If
  291. Set rs = DAL().Query("SELECT k.id, p.id, p.tenant_id, k.expires_at FROM api_keys k " & _
  292. "JOIN principals p ON p.id = k.principal_id JOIN tenants t ON t.id = p.tenant_id " & _
  293. "WHERE k.key_hash = ? AND k.status = 'active' AND p.status = 'active' AND t.status = 'active'", Api_Sha256(key))
  294. If rs.EOF Then
  295. rs.Close
  296. Response.AddHeader "WWW-Authenticate", "Bearer"
  297. Api_Error 401, "unauthenticated", "Invalid API key."
  298. Exit Function
  299. End If
  300. keyId = "" & rs(0)
  301. Api_PrincipalId = "" & rs(1)
  302. Api_TenantId = "" & rs(2)
  303. expires = rs(3)
  304. rs.Close
  305. If Not IsNull(expires) Then
  306. If Len("" & expires) > 0 Then
  307. If "" & expires <= Api_Now() Then
  308. Api_TenantId = ""
  309. Api_PrincipalId = ""
  310. Response.AddHeader "WWW-Authenticate", "Bearer"
  311. Api_Error 401, "unauthenticated", "API key has expired."
  312. Exit Function
  313. End If
  314. End If
  315. End If
  316. ' Best effort: bookkeeping must not lock everyone out when the database refuses writes (for example a
  317. ' read-only file); the write paths report such failures themselves.
  318. On Error Resume Next
  319. DAL().Execute "UPDATE api_keys SET last_used_at = ? WHERE id = ?", Array(Api_Now(), keyId)
  320. Err.Clear
  321. On Error GoTo 0
  322. Api_Authenticate = True
  323. End Function
  324. '-----------------------------------------------------------------------------------------------------------------------
  325. ' Authorization
  326. '-----------------------------------------------------------------------------------------------------------------------
  327. ' Path of a namespace in the caller's tenant, or Null when it does not exist there.
  328. Function Api_NamespacePath(namespaceId)
  329. Dim rs
  330. Api_NamespacePath = Null
  331. If Not Api_IsId(namespaceId) Then Exit Function
  332. Set rs = DAL().Query("SELECT path FROM namespaces WHERE id = ? AND tenant_id = ?", Array(namespaceId, Api_TenantId))
  333. If Not rs.EOF Then
  334. Api_NamespacePath = "" & rs(0)
  335. End If
  336. rs.Close
  337. End Function
  338. ' True when the principal holds `perm` (or admin) on the path itself, or on an ancestor via an inheriting grant.
  339. Function Api_PathAllows(targetPath, perm)
  340. Dim rs, gPath, perms, inherit, allowed, expires, now_
  341. Api_PathAllows = False
  342. now_ = Api_Now()
  343. Set rs = DAL().Query("SELECT n.path, g.permissions, g.inherit, g.expires_at FROM access_grants g " & _
  344. "JOIN namespaces n ON n.id = g.namespace_id " & _
  345. "WHERE g.principal_id = ? AND n.tenant_id = ?", Array(Api_PrincipalId, Api_TenantId))
  346. Do While Not rs.EOF
  347. gPath = "" & rs(0)
  348. perms = "," & LCase(Replace("" & rs(1), " ", "")) & ","
  349. inherit = rs(2)
  350. expires = rs(3)
  351. allowed = True
  352. If Not IsNull(expires) Then
  353. If Len("" & expires) > 0 Then
  354. If "" & expires <= now_ Then allowed = False
  355. End If
  356. End If
  357. If allowed Then
  358. If targetPath = gPath Then
  359. allowed = True
  360. ElseIf CLng(inherit) = 1 And Left(targetPath, Len(gPath) + 1) = gPath & "/" Then
  361. allowed = True
  362. ElseIf gPath = "/" And CLng(inherit) = 1 Then
  363. allowed = True
  364. Else
  365. allowed = False
  366. End If
  367. End If
  368. If allowed Then
  369. If InStr(perms, "," & LCase(perm) & ",") > 0 Or InStr(perms, ",admin,") > 0 Then
  370. Api_PathAllows = True
  371. Exit Do
  372. End If
  373. End If
  374. rs.MoveNext
  375. Loop
  376. rs.Close
  377. End Function
  378. ' True when the namespace exists in the caller's tenant AND the caller holds `perm` on it.
  379. Function Api_CanAccessNamespace(namespaceId, perm)
  380. Dim p
  381. Api_CanAccessNamespace = False
  382. p = Api_NamespacePath(namespaceId)
  383. If IsNull(p) Then Exit Function
  384. Api_CanAccessNamespace = Api_PathAllows(p, perm)
  385. End Function
  386. '-----------------------------------------------------------------------------------------------------------------------
  387. ' Imported data keeps its original author ids (provenance), which may not exist in this installation. This creates a
  388. ' placeholder principal (type service, status imported, no keys, no grants: it can never sign in) for every author id
  389. ' that canonical memory/document data references but that does not exist, so foreign keys stay valid.
  390. ' tenantId "" covers every tenant (repair); returns the number of placeholders created. Raises on a database error.
  391. '-----------------------------------------------------------------------------------------------------------------------
  392. Function Api_EnsureReferencedPrincipals(tenantId)
  393. Dim sql, rs, rows, i, n
  394. sql = "SELECT DISTINCT pid, tid FROM (" & _
  395. "SELECT creator_principal_id AS pid, tenant_id AS tid FROM memories UNION ALL " & _
  396. "SELECT r.created_by, m.tenant_id FROM memory_revisions r JOIN memories m ON m.id = r.memory_id UNION ALL " & _
  397. "SELECT v.reviewer_principal_id, m.tenant_id FROM verifications v JOIN memories m ON m.id = v.memory_id UNION ALL " & _
  398. "SELECT created_by, tenant_id FROM documents UNION ALL " & _
  399. "SELECT r.created_by, d.tenant_id FROM document_revisions r JOIN documents d ON d.id = r.document_id UNION ALL " & _
  400. "SELECT created_by, tenant_id FROM evidence_links" & _
  401. ") x WHERE pid IS NOT NULL AND NOT EXISTS (SELECT 1 FROM principals p WHERE p.id = x.pid)"
  402. If Len(tenantId) > 0 Then
  403. Set rs = DAL().Query(sql & " AND tid = ?", tenantId)
  404. Else
  405. Set rs = DAL().Query(sql, Empty)
  406. End If
  407. rows = Empty
  408. If Not rs.EOF Then
  409. rows = rs.GetRows()
  410. End If
  411. rs.Close
  412. n = 0
  413. If IsArray(rows) Then
  414. For i = 0 To UBound(rows, 2)
  415. If Api_IsId("" & rows(0, i)) Then
  416. DAL().Execute "INSERT OR IGNORE INTO principals (id, tenant_id, type, name, status, created_at) VALUES (?, ?, 'service', 'imported principal', 'imported', ?)", _
  417. Array("" & rows(0, i), "" & rows(1, i), Api_Now())
  418. n = n + 1
  419. End If
  420. Next
  421. End If
  422. Api_EnsureReferencedPrincipals = n
  423. End Function
  424. '-----------------------------------------------------------------------------------------------------------------------
  425. ' Audit trail (security-relevant actions; never log secrets or content)
  426. '-----------------------------------------------------------------------------------------------------------------------
  427. Sub Api_Audit(action, resourceType, resourceId, outcome)
  428. On Error Resume Next
  429. DAL().Execute "INSERT INTO audit_events (id, tenant_id, principal_id, action, resource_type, resource_id, outcome, request_id, created_at) " & _
  430. "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", _
  431. Array(Api_NewId(), Api_TenantId, Api_PrincipalId, action, resourceType, resourceId, outcome, Api_RequestId(), Api_Now())
  432. Err.Clear
  433. On Error GoTo 0
  434. End Sub
  435. ' 422 with a list of messages. details: array of strings.
  436. Sub Api_Invalid(details)
  437. Dim i, list
  438. list = ""
  439. For i = 0 To UBound(details)
  440. If i > 0 Then list = list & ","
  441. list = list & JsonLite_Quote(details(i))
  442. Next
  443. Api_Send 422, "{""error"":{""code"":""validation_failed"",""message"":""Validation failed."",""details"":[" & list & "],""request_id"":" & JsonLite_Quote(Api_RequestId()) & "}}"
  444. End Sub
  445. ' SQL list of the caller's namespace ids on which `perm` is held, e.g. 'id1','id2' (ids are UUIDs, safe to inline).
  446. ' Empty string when there are none. One grants query plus one namespaces query.
  447. Function Api_AllowedNamespaceIds(perm)
  448. Dim rs, gPaths(), gPerms(), gInh(), n, i, now_, expires, okGrant, p, out, id, path, hit
  449. Api_AllowedNamespaceIds = ""
  450. now_ = Api_Now()
  451. n = 0
  452. ReDim gPaths(7)
  453. ReDim gPerms(7)
  454. ReDim gInh(7)
  455. Set rs = DAL().Query("SELECT n.path, g.permissions, g.inherit, g.expires_at FROM access_grants g " & _
  456. "JOIN namespaces n ON n.id = g.namespace_id WHERE g.principal_id = ? AND n.tenant_id = ?", Array(Api_PrincipalId, Api_TenantId))
  457. Do While Not rs.EOF
  458. okGrant = True
  459. expires = rs(3)
  460. If Not IsNull(expires) Then
  461. If Len("" & expires) > 0 Then
  462. If "" & expires <= now_ Then okGrant = False
  463. End If
  464. End If
  465. p = "," & LCase(Replace("" & rs(1), " ", "")) & ","
  466. If okGrant And (InStr(p, "," & LCase(perm) & ",") > 0 Or InStr(p, ",admin,") > 0) Then
  467. If n > UBound(gPaths) Then
  468. ReDim Preserve gPaths(n * 2)
  469. ReDim Preserve gPerms(n * 2)
  470. ReDim Preserve gInh(n * 2)
  471. End If
  472. gPaths(n) = "" & rs(0)
  473. gInh(n) = CLng(rs(2))
  474. n = n + 1
  475. End If
  476. rs.MoveNext
  477. Loop
  478. rs.Close
  479. If n = 0 Then Exit Function
  480. out = ""
  481. Set rs = DAL().Query("SELECT id, path FROM namespaces WHERE tenant_id = ?", Api_TenantId)
  482. Do While Not rs.EOF
  483. id = "" & rs(0)
  484. path = "" & rs(1)
  485. hit = False
  486. For i = 0 To n - 1
  487. If path = gPaths(i) Then
  488. hit = True
  489. ElseIf gInh(i) = 1 Then
  490. If gPaths(i) = "/" Then
  491. hit = True
  492. ElseIf Left(path, Len(gPaths(i)) + 1) = gPaths(i) & "/" Then
  493. hit = True
  494. End If
  495. End If
  496. If hit Then Exit For
  497. Next
  498. If hit And Api_IsId(id) Then
  499. If Len(out) > 0 Then out = out & ","
  500. out = out & "'" & id & "'"
  501. End If
  502. rs.MoveNext
  503. Loop
  504. rs.Close
  505. Api_AllowedNamespaceIds = out
  506. End Function
  507. ' Replays the stored response for an Idempotency-Key. Returns True when the request may proceed (key unseen);
  508. ' False after sending the replayed response (same body) or a 409 (key reused with a different body).
  509. Function Api_IdempotencyGate(idemKey, requestHash)
  510. Dim rs
  511. Api_IdempotencyGate = True
  512. If Len(idemKey) = 0 Then Exit Function
  513. Set rs = DAL().Query("SELECT request_hash, status_code, response_body FROM idempotency_keys WHERE tenant_id = ? AND idem_key = ?", Array(Api_TenantId, idemKey))
  514. If Not rs.EOF Then
  515. Api_IdempotencyGate = False
  516. If "" & rs(0) = requestHash Then
  517. Dim st, bodyText
  518. st = CLng(rs(1))
  519. bodyText = "" & rs(2)
  520. rs.Close
  521. Api_Send st, bodyText
  522. Response.AddHeader "Idempotent-Replayed", "true"
  523. Else
  524. rs.Close
  525. Api_Error 409, "idempotency_conflict", "This Idempotency-Key was already used with a different request body."
  526. End If
  527. Exit Function
  528. End If
  529. rs.Close
  530. End Function
  531. Sub Api_IdempotencyStore(idemKey, requestHash, status, bodyText)
  532. If Len(idemKey) = 0 Then Exit Sub
  533. DAL().Execute "INSERT INTO idempotency_keys (tenant_id, idem_key, request_hash, status_code, response_body, created_at) VALUES (?, ?, ?, ?, ?, ?)", _
  534. Array(Api_TenantId, idemKey, requestHash, status, bodyText, Api_Now())
  535. End Sub
  536. %>

Powered by TurnKey Linux.