Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

515 řádky
20KB

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

Powered by TurnKey Linux.